Path operation dependencies help you run shared code before your API handles a request. This keeps your code clean and avoids repeating yourself.
0
0
Path operation dependencies in FastAPI
Introduction
You want to check if a user is logged in before allowing access to certain pages.
You need to connect to a database before processing a request.
You want to validate or transform input data for many routes.
You want to add common headers or security checks to multiple endpoints.
Syntax
FastAPI
from fastapi import FastAPI, Depends app = FastAPI() def common_dependency(): # code to run before path operation return 'some value' @app.get('/items/') async def read_items(dep_value: str = Depends(common_dependency)): return {'dep_value': dep_value}
Use Depends() to declare a dependency in a path operation function.
The dependency function runs first and its return value is passed to the path operation.
Examples
This example runs
verify_token before the route and passes its result.FastAPI
from fastapi import FastAPI, Depends app = FastAPI() def verify_token(): return 'token verified' @app.get('/secure') async def secure_route(token_status: str = Depends(verify_token)): return {'status': token_status}
Dependency can also accept parameters and return values used in the path operation.
FastAPI
from fastapi import FastAPI, Depends app = FastAPI() def common_params(q: str | None = None): return q @app.get('/search') async def search(q: str | None = Depends(common_params)): return {'query': q}
Sample Program
This program defines a dependency get_token_header that runs before the /items/ route. The route receives the token value and returns it in the response.
FastAPI
from fastapi import FastAPI, Depends app = FastAPI() def get_token_header(): # Imagine checking a token here return 'token123' @app.get('/items/') async def read_items(token: str = Depends(get_token_header)): return {'token_received': token}
OutputSuccess
Important Notes
Dependencies can be reused in many routes to keep code DRY (Don't Repeat Yourself).
You can stack multiple dependencies by adding more parameters with Depends().
Dependencies can also raise errors to stop request processing early.
Summary
Path operation dependencies run shared code before handling requests.
Use Depends() to declare dependencies in your route functions.
This helps keep your API code clean and organized.