Movatterモバイル変換


[0]ホーム

URL:


콘텐츠로 이동
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

Dependencies -Depends() andSecurity()

Depends()

Dependencies are handled mainly with the special functionDepends() that takes a callable.

Here is the reference for it and its parameters.

You can import it directly fromfastapi:

fromfastapiimportDepends

fastapi.Depends

Depends(dependency=None,*,use_cache=True,scope=None)

Declare a FastAPI dependency.

It takes a single "dependable" callable (like a function).

Don't call it directly, FastAPI will call it for you.

Read more about it in theFastAPI docs for Dependencies.

Example

fromtypingimportAnnotatedfromfastapiimportDepends,FastAPIapp=FastAPI()asyncdefcommon_parameters(q:str|None=None,skip:int=0,limit:int=100):return{"q":q,"skip":skip,"limit":limit}@app.get("/items/")asyncdefread_items(commons:Annotated[dict,Depends(common_parameters)]):returncommons
PARAMETERDESCRIPTION
dependency

A "dependable" callable (like a function).

Don't call it directly, FastAPI will call it for you, just pass the objectdirectly.

Read more about it in theFastAPI docs for Dependencies

TYPE:Callable[...,Any] | NoneDEFAULT:None

use_cache

By default, after a dependency is called the first time in a request, ifthe dependency is declared again for the rest of the request (for exampleif the dependency is needed by several dependencies), the value will bere-used for the rest of the request.

Setuse_cache toFalse to disable this behavior and ensure thedependency is called again (if declared more than once) in the same request.

Read more about it in theFastAPI docs about sub-dependencies

TYPE:boolDEFAULT:True

scope

Mainly for dependencies withyield, define when the dependency functionshould start (the code beforeyield) and when it should end (the codeafteryield).

  • "function": start the dependency before thepath operation function that handles the request, end the dependency after thepath operation function ends, butbefore the response is sent back to the client. So, the dependency function will be executedaround thepath operationfunction.
  • "request": start the dependency before thepath operation function that handles the request (similar to when using"function"), but endafter the response is sent back to the client. So, the dependency function will be executedaround therequest and response cycle.

Read more about it in theFastAPI docs for FastAPI Dependencies with yield

TYPE:Literal['function', 'request'] | NoneDEFAULT:None

Source code infastapi/param_functions.py
228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370
defDepends(# noqa: N802dependency:Annotated[Callable[...,Any]|None,Doc("""            A "dependable" callable (like a function).            Don't call it directly, FastAPI will call it for you, just pass the object            directly.            Read more about it in the            [FastAPI docs for Dependencies](https://fastapi.tiangolo.com/tutorial/dependencies/)            """),]=None,*,use_cache:Annotated[bool,Doc("""            By default, after a dependency is called the first time in a request, if            the dependency is declared again for the rest of the request (for example            if the dependency is needed by several dependencies), the value will be            re-used for the rest of the request.            Set `use_cache` to `False` to disable this behavior and ensure the            dependency is called again (if declared more than once) in the same request.            Read more about it in the            [FastAPI docs about sub-dependencies](https://fastapi.tiangolo.com/tutorial/dependencies/sub-dependencies/#using-the-same-dependency-multiple-times)            """),]=True,scope:Annotated[Literal["function","request"]|None,Doc("""            Mainly for dependencies with `yield`, define when the dependency function            should start (the code before `yield`) and when it should end (the code            after `yield`).            * `"function"`: start the dependency before the *path operation function*                that handles the request, end the dependency after the *path operation                function* ends, but **before** the response is sent back to the client.                So, the dependency function will be executed **around** the *path operation                **function***.            * `"request"`: start the dependency before the *path operation function*                that handles the request (similar to when using `"function"`), but end                **after** the response is sent back to the client. So, the dependency                function will be executed **around** the **request** and response cycle.            Read more about it in the            [FastAPI docs for FastAPI Dependencies with yield](https://fastapi.tiangolo.com/tutorial/dependencies/dependencies-with-yield/#early-exit-and-scope)            """),]=None,)->Any:"""    Declare a FastAPI dependency.    It takes a single "dependable" callable (like a function).    Don't call it directly, FastAPI will call it for you.    Read more about it in the    [FastAPI docs for Dependencies](https://fastapi.tiangolo.com/tutorial/dependencies/).    **Example**    ```python    from typing import Annotated    from fastapi import Depends, FastAPI    app = FastAPI()    async def common_parameters(q: str | None = None, skip: int = 0, limit: int = 100):        return {"q": q, "skip": skip, "limit": limit}    @app.get("/items/")    async def read_items(commons: Annotated[dict, Depends(common_parameters)]):        return commons    ```    """returnparams.Depends(dependency=dependency,use_cache=use_cache,scope=scope)

Security()

For many scenarios, you can handle security (authorization, authentication, etc.) with dependencies, usingDepends().

But when you want to also declare OAuth2 scopes, you can useSecurity() instead ofDepends().

You can importSecurity() directly fromfastapi:

fromfastapiimportSecurity

fastapi.Security

Security(dependency=None,*,scopes=None,use_cache=True)

Declare a FastAPI Security dependency.

The only difference with a regular dependency is that it can declare OAuth2scopes that will be integrated with OpenAPI and the automatic UI docs (by defaultat/docs).

It takes a single "dependable" callable (like a function).

Don't call it directly, FastAPI will call it for you.

Read more about it in theFastAPI docs for Security andin theFastAPI docs for OAuth2 scopes.

Example

fromtypingimportAnnotatedfromfastapiimportSecurity,FastAPIfrom.dbimportUserfrom.securityimportget_current_active_userapp=FastAPI()@app.get("/users/me/items/")asyncdefread_own_items(current_user:Annotated[User,Security(get_current_active_user,scopes=["items"])]):return[{"item_id":"Foo","owner":current_user.username}]
PARAMETERDESCRIPTION
dependency

A "dependable" callable (like a function).

Don't call it directly, FastAPI will call it for you, just pass the objectdirectly.

Read more about it in theFastAPI docs for Dependencies

TYPE:Callable[...,Any] | NoneDEFAULT:None

scopes

OAuth2 scopes required for thepath operation that uses this Securitydependency.

The term "scope" comes from the OAuth2 specification, it seems to beintentionally vague and interpretable. It normally refers to permissions,in cases to roles.

These scopes are integrated with OpenAPI (and the API docs at/docs).So they are visible in the OpenAPI specification.

Read more about it in theFastAPI docs about OAuth2 scopes

TYPE:Sequence[str] | NoneDEFAULT:None

use_cache

By default, after a dependency is called the first time in a request, ifthe dependency is declared again for the rest of the request (for exampleif the dependency is needed by several dependencies), the value will bere-used for the rest of the request.

Setuse_cache toFalse to disable this behavior and ensure thedependency is called again (if declared more than once) in the same request.

Read more about it in theFastAPI docs about sub-dependencies

TYPE:boolDEFAULT:True

Source code infastapi/param_functions.py
23732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428242924302431243224332434243524362437243824392440244124422443244424452446244724482449245024512452245324542455245624572458245924602461
defSecurity(# noqa: N802dependency:Annotated[Callable[...,Any]|None,Doc("""            A "dependable" callable (like a function).            Don't call it directly, FastAPI will call it for you, just pass the object            directly.            Read more about it in the            [FastAPI docs for Dependencies](https://fastapi.tiangolo.com/tutorial/dependencies/)            """),]=None,*,scopes:Annotated[Sequence[str]|None,Doc("""            OAuth2 scopes required for the *path operation* that uses this Security            dependency.            The term "scope" comes from the OAuth2 specification, it seems to be            intentionally vague and interpretable. It normally refers to permissions,            in cases to roles.            These scopes are integrated with OpenAPI (and the API docs at `/docs`).            So they are visible in the OpenAPI specification.            Read more about it in the            [FastAPI docs about OAuth2 scopes](https://fastapi.tiangolo.com/advanced/security/oauth2-scopes/)            """),]=None,use_cache:Annotated[bool,Doc("""            By default, after a dependency is called the first time in a request, if            the dependency is declared again for the rest of the request (for example            if the dependency is needed by several dependencies), the value will be            re-used for the rest of the request.            Set `use_cache` to `False` to disable this behavior and ensure the            dependency is called again (if declared more than once) in the same request.            Read more about it in the            [FastAPI docs about sub-dependencies](https://fastapi.tiangolo.com/tutorial/dependencies/sub-dependencies/#using-the-same-dependency-multiple-times)            """),]=True,)->Any:"""    Declare a FastAPI Security dependency.    The only difference with a regular dependency is that it can declare OAuth2    scopes that will be integrated with OpenAPI and the automatic UI docs (by default    at `/docs`).    It takes a single "dependable" callable (like a function).    Don't call it directly, FastAPI will call it for you.    Read more about it in the    [FastAPI docs for Security](https://fastapi.tiangolo.com/tutorial/security/) and    in the    [FastAPI docs for OAuth2 scopes](https://fastapi.tiangolo.com/advanced/security/oauth2-scopes/).    **Example**    ```python    from typing import Annotated    from fastapi import Security, FastAPI    from .db import User    from .security import get_current_active_user    app = FastAPI()    @app.get("/users/me/items/")    async def read_own_items(        current_user: Annotated[User, Security(get_current_active_user, scopes=["items"])]    ):        return [{"item_id": "Foo", "owner": current_user.username}]    ```    """returnparams.Security(dependency=dependency,scopes=scopes,use_cache=use_cache)

[8]ページ先頭

©2009-2026 Movatter.jp