In FastAPI, what does Security() add over Depends(), and what does it leave for your own code to do?
answer
- a subclass with one extra field
- same resolution, same per-request cache
- scopes flow down to SecurityScopes
- operation security in OpenAPI
- no check without your dependency
basics
~20 sfastapi.Security declares a dependency exactly as Depends does, plus a scopes list that FastAPI passes down to SecurityScopes and writes into the operation's OpenAPI security. It checks nothing; your dependency must compare those scopes with the token.
solid answer
~40 s`Security(dependency, *, scopes=None, use_cache=True)` returns a `params.Security`, a subclass of `params.Depends` with one extra field, `scopes`. Resolution is identical: FastAPI calls the dependency, resolves its sub-dependencies and reuses the result within the request unless `use_cache=False`. The difference is bookkeeping. The scopes are added to the required list that every `SecurityScopes` parameter further down that branch receives, and they appear in the operation's OpenAPI `security` requirement, so `/docs` shows them. Nothing is enforced: if the dependency never reads `SecurityScopes` and compares it with the token's scopes, a read-only token passes. A plain `Depends(oauth2_scheme)` still documents the scheme; `Security` is needed only to declare scopes. It works in a decorator's or an `APIRouter`'s `dependencies` list as well.
code
python · 41 linesfrom typing import Annotated
from fastapi import Depends, FastAPI, Security
from fastapi.security import OAuth2PasswordBearer, SecurityScopes
from fastapi.testclient import TestClient
oauth2_scheme = OAuth2PasswordBearer(
tokenUrl="token",
scopes={"items:read": "Read items.", "items:write": "Change items.", "me": "Own profile."},
)
def get_current_principal(
security_scopes: SecurityScopes,
token: Annotated[str, Depends(oauth2_scheme)],
):
return {"token": token, "required": security_scopes.scopes}
app = FastAPI()
@app.get("/status")
def status(p: Annotated[dict, Depends(get_current_principal)]):
return p # required: []
@app.post("/items")
def create_item(
p: Annotated[dict, Security(get_current_principal, scopes=["items:write"])],
):
return p # required: ['items:write']
client = TestClient(app)
headers = {"Authorization": "Bearer read-only-token"}
print(client.get("/status", headers=headers).json())
print(client.post("/items", headers=headers).json())
ops = app.openapi()["paths"]
print(ops["/status"]["get"]["security"], ops["/items"]["post"]["security"])
# [{'OAuth2PasswordBearer': []}] [{'OAuth2PasswordBearer': ['items:write']}]go deeper
Remember that Security() is Depends() with a scopes list, and that a route still needs your own checking dependency for the scopes to mean anything.
Explain the subclass relationship, the shared caching and use_cache, how the scopes reach SecurityScopes and OpenAPI, and why Depends on a scheme still documents it.
Spot routes where Security() decorates a dependency that never reads SecurityScopes, and explain why a checker reached with two scope sets runs twice per request.
Decide where a team declares scopes, per route, per router or both, so the required scope of every endpoint stays visible in review and in the schema.
## Two declarations, one mechanism In FastAPI a **dependency** is a callable the framework runs before a route, injecting its return value into a parameter. `Depends(get_current_principal)` declares one. `Security(get_current_principal, scopes=["items:write"])` declares the same thing with extra information attached. In the source, `Security()` returns `params.Security`, a frozen dataclass that **subclasses** `params.Depends` and adds one field, `scopes`. The `Security()` function takes three arguments: - `dependency`, the callable, exactly as for `Depends`; - `scopes`, a sequence of required OAuth2 scope strings, default `None`; - `use_cache`, default `True`, with the same meaning as for `Depends`. It does **not** take the `scope="function"` argument that `Depends()` offers for yield dependencies; passing it raises `TypeError`. ## What stays the same Everything about running the dependency is shared: - FastAPI inspects the callable's signature and resolves its own parameters and sub-dependencies; - `def` callables run in the thread pool and `async def` ones on the event loop, as for any dependency; - within one request the result is cached and reused wherever the same dependency appears again, unless `use_cache=False`. One caching detail is specific to scopes. When a dependency **uses scopes** (it declares `SecurityScopes`, has scopes of its own, is a security class, or has such a sub-dependency), FastAPI 0.143 keys its per-request cache by the callable **plus the set of scopes it sees**. The same checker reached once with no scopes and once with `["items:read"]` therefore runs twice in one request. A dependency that uses no scopes, such as a settings loader, is cached once however many scope sets sit above it. ## What `Security` adds The `scopes` list does two things, both bookkeeping: 1. **It feeds `SecurityScopes`.** Any dependency below this point in the same branch that declares a parameter of type `SecurityScopes` receives these scopes merged with the ones declared above it. 2. **It feeds OpenAPI.** When the branch reaches a security class such as `OAuth2PasswordBearer`, the scopes are written into that operation's `security` requirement, for example `[{"OAuth2PasswordBearer": ["items:write"]}]`, and the docs UI shows the route as needing them. | | `Depends(dep)` | `Security(dep, scopes=[...])` | |---|---|---| | Runs the dependency | yes | yes | | Per-request cache, `use_cache` | yes | yes | | `scope="function"` for yield teardown | yes | no | | Adds required scopes for `SecurityScopes` | no | yes | | Puts the scopes in operation `security` | no | yes | | Documents a security class it reaches | yes | yes | The last row matters: `Depends(oauth2_scheme)` already makes the scheme appear in OpenAPI with an empty scope list. `Security` is needed only to **declare scopes**. ## What it leaves to you `Security` never compares anything. Enforcement is a dependency you write: - declare `security_scopes: SecurityScopes` and the token, usually through `Depends(oauth2_scheme)`; - decode the token and read the scopes it was granted; - raise `HTTPException` when any entry of `security_scopes.scopes` is missing. If the dependency named in `Security(...)` ignores `SecurityScopes`, or if `Security` is pointed straight at the scheme, as in `Security(oauth2_scheme, scopes=["items:write"])`, the scope is documented and nothing is checked. ## Where it can be declared Because it is a dependency marker, `Security` fits everywhere `Depends` does: in a parameter's `Annotated[...]`, in a path operation decorator's `dependencies=[...]`, and in `APIRouter(dependencies=[...])`, which applies the scope requirement to every route on that router. In the list forms the return value is discarded and only the side effect, raising when a scope is missing, matters. ## A worked comparison In an inventory API with one checker, `get_current_principal`, two routes differ by one word: - `GET /status` declares `Depends(get_current_principal)`. The checker runs, its `security_scopes.scopes` is `[]`, and the operation's OpenAPI security is `[{"OAuth2PasswordBearer": []}]`: authenticated, no scope required. - `POST /items` declares `Security(get_current_principal, scopes=["items:write"])`. The checker runs with `["items:write"]`, and OpenAPI shows `[{"OAuth2PasswordBearer": ["items:write"]}]`. Whether a read-only reporting token is refused on `POST /items` depends entirely on what `get_current_principal` does with that list. Swap `Security` back to `Depends` during a refactor and the docs lose the scope while the checker silently stops requiring it; the route keeps working for every valid token, which is why such regressions go unnoticed without a test.
- If one route reaches the same checker through Depends and through Security(scopes=["items:read"]), how often does it run?Twice in that request. Because the checker uses scopes, FastAPI 0.143 keys its per-request cache by the callable plus its sorted set of scopes, so the empty set and `{"items:read"}` are separate entries. A sub-dependency that uses no scopes, such as a settings loader, still runs once and is shared.
- Can Security() be used in an APIRouter's dependencies list?Yes. `APIRouter(dependencies=[Security(require_scopes, scopes=["items:write"])])` runs the checker for every route on that router with `items:write` in its `SecurityScopes`, and each operation's OpenAPI security lists the scope. The return value is discarded, so the checker's job there is only to raise.
- Security() validates the token's scopes before the dependency runs.
- Security() turns off the per-request cache so each check is fresh.
- A security class only appears in /docs when declared with Security().
- Security() accepts scope="function" like Depends() for yield teardown.
- Pointing Security() straight at OAuth2PasswordBearer enforces the listed scopes.
Assumes FastAPI 0.143; since 0.123.0 only dependencies that use scopes are cached per scope set.