Movatterモバイル変換


[0]ホーム

URL:


Skip to content
Join theFastAPI Cloud waiting list 🚀
Follow@fastapi onX (Twitter) to stay updated
FollowFastAPI onLinkedIn to stay updated
Subscribe to theFastAPI and friends newsletter 🎉
sponsor
sponsor
sponsor
sponsor
sponsor
sponsor
sponsor
sponsor
sponsor
sponsor
sponsor

Global Dependencies

For some types of applications you might want to add dependencies to the whole application.

Similar to the way you canadddependencies to thepath operation decorators, you can add them to theFastAPI application.

In that case, they will be applied to all thepath operations in the application:

fromtypingimportAnnotatedfromfastapiimportDepends,FastAPI,Header,HTTPExceptionasyncdefverify_token(x_token:Annotated[str,Header()]):ifx_token!="fake-super-secret-token":raiseHTTPException(status_code=400,detail="X-Token header invalid")asyncdefverify_key(x_key:Annotated[str,Header()]):ifx_key!="fake-super-secret-key":raiseHTTPException(status_code=400,detail="X-Key header invalid")returnx_keyapp=FastAPI(dependencies=[Depends(verify_token),Depends(verify_key)])@app.get("/items/")asyncdefread_items():return[{"item":"Portal Gun"},{"item":"Plumbus"}]@app.get("/users/")asyncdefread_users():return[{"username":"Rick"},{"username":"Morty"}]
🤓 Other versions and variants

Tip

Prefer to use theAnnotated version if possible.

fromfastapiimportDepends,FastAPI,Header,HTTPExceptionasyncdefverify_token(x_token:str=Header()):ifx_token!="fake-super-secret-token":raiseHTTPException(status_code=400,detail="X-Token header invalid")asyncdefverify_key(x_key:str=Header()):ifx_key!="fake-super-secret-key":raiseHTTPException(status_code=400,detail="X-Key header invalid")returnx_keyapp=FastAPI(dependencies=[Depends(verify_token),Depends(verify_key)])@app.get("/items/")asyncdefread_items():return[{"item":"Portal Gun"},{"item":"Plumbus"}]@app.get("/users/")asyncdefread_users():return[{"username":"Rick"},{"username":"Morty"}]

And all the ideas in the section aboutaddingdependencies to thepath operation decorators still apply, but in this case, to all of thepath operations in the app.

Dependencies for groups ofpath operations

Later, when reading about how to structure bigger applications (Bigger Applications - Multiple Files), possibly with multiple files, you will learn how to declare a singledependencies parameter for a group ofpath operations.


[8]ページ先頭

©2009-2026 Movatter.jp