Skip to content

Instantly share code, notes, and snippets.

@shearichard
Created April 2, 2025 19:00
Show Gist options
  • Save shearichard/3acacb5d05aef3215ff3e3ebe7ccdace to your computer and use it in GitHub Desktop.
Save shearichard/3acacb5d05aef3215ff3e3ebe7ccdace to your computer and use it in GitHub Desktop.
FastAPI - decorator vs Depends equivalance
'''
The same functionality expressed as decorators and Depends
'''
from fastapi import FastAPI, Request, Depends
import logging
app = FastAPI()
# Set up logging
logging.basicConfig(level=logging.INFO)
# Dependency 1: Log the request method
async def log_request_method(request: Request):
logging.info(f"Request Method: {request.method}")
# Dependency 2: Log the request URL
async def log_request_url(request: Request):
logging.info(f"Request URL: {request.url}")
@app.get("/data")
async def get_data(
user_id: int,
method: None = Depends(log_request_method), # Injecting the logging dependency
url: None = Depends(log_request_url) # Injecting the logging dependency
):
# Sample response
return {"message": "Data retrieved successfully", "user_id": user_id}
# To run the application, use the command:
# uvicorn filename:app --reload
'''
Is equivalent to this
'''
from fastapi import FastAPI, Request, HTTPException
from functools import wraps
app = FastAPI()
# Custom Decorator 1: Log the request method
def log_request_method(func):
@wraps(func)
async def wrapper(request: Request, *args, **kwargs):
print(f"Request Method: {request.method}")
return await func(request, *args, **kwargs)
return wrapper
# Custom Decorator 2: Log the request URL
def log_request_url(func):
@wraps(func)
async def wrapper(request: Request, *args, **kwargs):
print(f"Request URL: {request.url}")
return await func(request, *args, **kwargs)
return wrapper
@app.get("/data")
@log_request_method
@log_request_url
async def get_data(request: Request, user_id: int):
# Sample response
return {"message": "Data retrieved successfully", "user_id": user_id}
# To run the application, use the command:
# uvicorn filename:app --reload
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment