Saltar al contenido

Dependencias - Depends() y Security()

Depends()

Las dependencias se manejan principalmente con la función especial Depends() que toma un callable.

Aquí está la referencia para ella y sus parámetros.

Puedes importarlo directamente desde fastapi:

from fastapi import Depends

fastapi.Depends

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

Declara una dependencia de FastAPI.

Toma un único callable "dependable" (como una función).

No lo llames directamente, FastAPI lo llamará por ti.

Lee más sobre esto en la documentación de FastAPI para Dependencias.

Example

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
PARÁMETRO DESCRIPCIÓN
dependency

Un callable "dependable" (como una función).

No lo llames directamente, FastAPI lo llamará por ti, solo pasa el objeto directamente.

Lee más sobre esto en la documentación de FastAPI para Dependencias

TIPO: Callable[..., Any] | None DEFAULT: None

use_cache

Por defecto, después de que una dependencia es llamada la primera vez en una petición, si la dependencia se declara nuevamente para el resto de la petición (por ejemplo, si la dependencia es necesitada por varias dependencias), el valor será reutilizado para el resto de la petición.

Establece use_cache en False para deshabilitar este comportamiento y asegurar que la dependencia sea llamada nuevamente (si se declara más de una vez) en la misma petición.

Lee más sobre esto en la documentación de FastAPI sobre sub-dependencias

TYPE: bool DEFAULT: True

scope

Principalmente para dependencias con yield, define cuándo debería comenzar la función de dependencia (el código antes de yield) y cuándo debería terminar (el código después de yield).

  • "function": comienza la dependencia antes de la función de operación de ruta que maneja la petición, termina la dependencia después de que la función de operación de ruta termine, pero antes de que la respuesta sea enviada de vuelta al cliente. Por lo tanto, la función de dependencia será ejecutada alrededor de la función de operación de ruta.
  • "request": comienza la dependencia antes de la función de operación de ruta que maneja la petición (similar a cuando se usa "function"), pero termina después de que la respuesta sea enviada de vuelta al cliente. Por lo tanto, la función de dependencia será ejecutada alrededor del ciclo de petición y respuesta.

Lee más sobre esto en la documentación de FastAPI para Dependencias de FastAPI con yield

TIPO: Literal['function', 'request'] | None DEFAULT: None

Código fuente en fastapi/param_functions.py
def Depends(  # noqa: N802
    dependency: 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
    ```
    """
    return params.Depends(dependency=dependency, use_cache=use_cache, scope=scope)

Security()

Para muchos escenarios, puedes manejar la seguridad (autorización, autenticación, etc.) con dependencias, usando Depends().

Pero cuando también quieres declarar scopes de OAuth2, puedes usar Security() en lugar de Depends().

Puedes importar Security() directamente desde fastapi:

from fastapi import Security

fastapi.Security

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

Declara una dependencia de Security de FastAPI.

La única diferencia con una dependencia regular es que puede declarar scopes de OAuth2 que serán integrados con OpenAPI y la documentación automática de la UI (por defecto en /docs).

Toma un único callable "dependable" (como una función).

No lo llames directamente, FastAPI lo llamará por ti.

Lee más sobre esto en la documentación de FastAPI para Security y en la documentación de FastAPI para scopes de OAuth2.

Example

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}]
PARÁMETRO DESCRIPCIÓN
dependency

Un callable "dependable" (como una función).

No lo llames directamente, FastAPI lo llamará por ti, solo pasa el objeto directamente.

Lee más sobre esto en la documentación de FastAPI para Dependencias

TIPO: Callable[..., Any] | None DEFAULT: None

scopes

Scopes de OAuth2 requeridos para la operación de ruta que usa esta dependencia de Security.

El término "scope" viene de la especificación de OAuth2, parece ser intencionalmente vago e interpretable. Normalmente se refiere a permisos, en algunos casos a roles.

Estos scopes están integrados con OpenAPI (y la documentación de la API en /docs). Por lo tanto, son visibles en la especificación de OpenAPI.

Lee más sobre esto en la documentación de FastAPI sobre scopes de OAuth2

TIPO: Sequence[str] | None DEFAULT: None

use_cache

Por defecto, después de que una dependencia es llamada la primera vez en una petición, si la dependencia se declara nuevamente para el resto de la petición (por ejemplo, si la dependencia es necesitada por varias dependencias), el valor será reutilizado para el resto de la petición.

Establece use_cache en False para deshabilitar este comportamiento y asegurar que la dependencia sea llamada nuevamente (si se declara más de una vez) en la misma petición.

Lee más sobre esto en la documentación de FastAPI sobre sub-dependencias

TYPE: bool DEFAULT: True

Código fuente en fastapi/param_functions.py
def Security(  # noqa: N802
    dependency: 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}]
    ```
    """
    return params.Security(dependency=dependency, scopes=scopes, use_cache=use_cache)