Skip to content
You're not viewing the latest version. Click here to go to latest.

# `dependencies`

Here's the reference for the FastAPI dependency factory functions.

You can import them directly from `fastapi_toolsets.dependencies`:

    from fastapi_toolsets.dependencies import PathDependency, BodyDependency

## `fastapi_toolsets.dependencies.PathDependency(model, field, *, session_dep, param_name=None)`

Create a dependency that fetches a DB object from a path parameter.

Parameters:

Name | Type | Description | Default
--- | --- | --- | ---
`model` | `type[ModelType]` | SQLAlchemy model class | required
`field` | `Any` | Model field to filter by (e.g., User.id) | required
`session_dep` | `SessionDependency` | Session dependency function (e.g., get_db) | required
`param_name` | `str | None` | Path parameter name (defaults to model_field, e.g., user_id) | `None`

Returns:

Type | Description
--- | ---
`ModelType` | A Depends() instance that resolves to the model instance

Raises:

Type | Description
--- | ---
`NotFoundError` | If no matching record is found

Example

    UserDep = PathDependency(User, User.id, session_dep=get_db)

    @router.get("/user/{id}")
    async def get(
        user: User = UserDep,
    ): ...

## `fastapi_toolsets.dependencies.BodyDependency(model, field, *, session_dep, body_field)`

Create a dependency that fetches a DB object from a body field.

Parameters:

Name | Type | Description | Default
--- | --- | --- | ---
`model` | `type[ModelType]` | SQLAlchemy model class | required
`field` | `Any` | Model field to filter by (e.g., User.id) | required
`session_dep` | `SessionDependency` | Session dependency function (e.g., get_db) | required
`body_field` | `str` | Name of the field in the request body | required

Returns:

Type | Description
--- | ---
`ModelType` | A Depends() instance that resolves to the model instance

Raises:

Type | Description
--- | ---
`NotFoundError` | If no matching record is found

Example

    UserDep = BodyDependency(
        User, User.ctfd_id, session_dep=get_db, body_field="user_id"
    )

    @router.post("/assign")
    async def assign(
        user: User = UserDep,
    ): ...