Skip to content

Security

plateforme.core.api.security

This module provides utilities for managing security within the Plateforme framework's API using FastAPI and Starlette features.

APIKeyCookie

APIKeyCookie(
    *,
    name: Annotated[str, Doc("Cookie name.")],
    scheme_name: Annotated[
        Optional[str],
        Doc(
            "\n                Security scheme name.\n\n                It will be included in the generated OpenAPI (e.g. visible at `/docs`).\n                "
        ),
    ] = None,
    description: Annotated[
        Optional[str],
        Doc(
            "\n                Security scheme description.\n\n                It will be included in the generated OpenAPI (e.g. visible at `/docs`).\n                "
        ),
    ] = None,
    auto_error: Annotated[
        bool,
        Doc(
            "\n                By default, if the cookie is not provided, `APIKeyCookie` will\n                automatically cancel the request and send the client an error.\n\n                If `auto_error` is set to `False`, when the cookie is not available,\n                instead of erroring out, the dependency result will be `None`.\n\n                This is useful when you want to have optional authentication.\n\n                It is also useful when you want to have authentication that can be\n                provided in one of multiple optional ways (for example, in a cookie or\n                in an HTTP Bearer token).\n                "
        ),
    ] = True,
)

Bases: APIKeyBase

API key authentication using a cookie.

This defines the name of the cookie that should be provided in the request with the API key and integrates that into the OpenAPI documentation. It extracts the key value sent in the cookie automatically and provides it as the dependency result. But it doesn't define how to set that cookie.

Usage

Create an instance object and use that object as the dependency in Depends().

The dependency result will be a string containing the key value.

Example
from fastapi import Depends, FastAPI
from fastapi.security import APIKeyCookie

app = FastAPI()

cookie_scheme = APIKeyCookie(name="session")


@app.get("/items/")
async def read_items(session: str = Depends(cookie_scheme)):
    return {"session": session}
Source code in .venv/lib/python3.12/site-packages/fastapi/security/api_key.py
def __init__(
    self,
    *,
    name: Annotated[str, Doc("Cookie name.")],
    scheme_name: Annotated[
        Optional[str],
        Doc(
            """
            Security scheme name.

            It will be included in the generated OpenAPI (e.g. visible at `/docs`).
            """
        ),
    ] = None,
    description: Annotated[
        Optional[str],
        Doc(
            """
            Security scheme description.

            It will be included in the generated OpenAPI (e.g. visible at `/docs`).
            """
        ),
    ] = None,
    auto_error: Annotated[
        bool,
        Doc(
            """
            By default, if the cookie is not provided, `APIKeyCookie` will
            automatically cancel the request and send the client an error.

            If `auto_error` is set to `False`, when the cookie is not available,
            instead of erroring out, the dependency result will be `None`.

            This is useful when you want to have optional authentication.

            It is also useful when you want to have authentication that can be
            provided in one of multiple optional ways (for example, in a cookie or
            in an HTTP Bearer token).
            """
        ),
    ] = True,
):
    self.model: APIKey = APIKey(
        **{"in": APIKeyIn.cookie},  # type: ignore[arg-type]
        name=name,
        description=description,
    )
    self.scheme_name = scheme_name or self.__class__.__name__
    self.auto_error = auto_error

APIKeyHeader

APIKeyHeader(
    *,
    name: Annotated[str, Doc("Header name.")],
    scheme_name: Annotated[
        Optional[str],
        Doc(
            "\n                Security scheme name.\n\n                It will be included in the generated OpenAPI (e.g. visible at `/docs`).\n                "
        ),
    ] = None,
    description: Annotated[
        Optional[str],
        Doc(
            "\n                Security scheme description.\n\n                It will be included in the generated OpenAPI (e.g. visible at `/docs`).\n                "
        ),
    ] = None,
    auto_error: Annotated[
        bool,
        Doc(
            "\n                By default, if the header is not provided, `APIKeyHeader` will\n                automatically cancel the request and send the client an error.\n\n                If `auto_error` is set to `False`, when the header is not available,\n                instead of erroring out, the dependency result will be `None`.\n\n                This is useful when you want to have optional authentication.\n\n                It is also useful when you want to have authentication that can be\n                provided in one of multiple optional ways (for example, in a header or\n                in an HTTP Bearer token).\n                "
        ),
    ] = True,
)

Bases: APIKeyBase

API key authentication using a header.

This defines the name of the header that should be provided in the request with the API key and integrates that into the OpenAPI documentation. It extracts the key value sent in the header automatically and provides it as the dependency result. But it doesn't define how to send that key to the client.

Usage

Create an instance object and use that object as the dependency in Depends().

The dependency result will be a string containing the key value.

Example
from fastapi import Depends, FastAPI
from fastapi.security import APIKeyHeader

app = FastAPI()

header_scheme = APIKeyHeader(name="x-key")


@app.get("/items/")
async def read_items(key: str = Depends(header_scheme)):
    return {"key": key}
Source code in .venv/lib/python3.12/site-packages/fastapi/security/api_key.py
def __init__(
    self,
    *,
    name: Annotated[str, Doc("Header name.")],
    scheme_name: Annotated[
        Optional[str],
        Doc(
            """
            Security scheme name.

            It will be included in the generated OpenAPI (e.g. visible at `/docs`).
            """
        ),
    ] = None,
    description: Annotated[
        Optional[str],
        Doc(
            """
            Security scheme description.

            It will be included in the generated OpenAPI (e.g. visible at `/docs`).
            """
        ),
    ] = None,
    auto_error: Annotated[
        bool,
        Doc(
            """
            By default, if the header is not provided, `APIKeyHeader` will
            automatically cancel the request and send the client an error.

            If `auto_error` is set to `False`, when the header is not available,
            instead of erroring out, the dependency result will be `None`.

            This is useful when you want to have optional authentication.

            It is also useful when you want to have authentication that can be
            provided in one of multiple optional ways (for example, in a header or
            in an HTTP Bearer token).
            """
        ),
    ] = True,
):
    self.model: APIKey = APIKey(
        **{"in": APIKeyIn.header},  # type: ignore[arg-type]
        name=name,
        description=description,
    )
    self.scheme_name = scheme_name or self.__class__.__name__
    self.auto_error = auto_error

APIKeyQuery

APIKeyQuery(
    *,
    name: Annotated[str, Doc("Query parameter name.")],
    scheme_name: Annotated[
        Optional[str],
        Doc(
            "\n                Security scheme name.\n\n                It will be included in the generated OpenAPI (e.g. visible at `/docs`).\n                "
        ),
    ] = None,
    description: Annotated[
        Optional[str],
        Doc(
            "\n                Security scheme description.\n\n                It will be included in the generated OpenAPI (e.g. visible at `/docs`).\n                "
        ),
    ] = None,
    auto_error: Annotated[
        bool,
        Doc(
            "\n                By default, if the query parameter is not provided, `APIKeyQuery` will\n                automatically cancel the request and sebd the client an error.\n\n                If `auto_error` is set to `False`, when the query parameter is not\n                available, instead of erroring out, the dependency result will be\n                `None`.\n\n                This is useful when you want to have optional authentication.\n\n                It is also useful when you want to have authentication that can be\n                provided in one of multiple optional ways (for example, in a query\n                parameter or in an HTTP Bearer token).\n                "
        ),
    ] = True,
)

Bases: APIKeyBase

API key authentication using a query parameter.

This defines the name of the query parameter that should be provided in the request with the API key and integrates that into the OpenAPI documentation. It extracts the key value sent in the query parameter automatically and provides it as the dependency result. But it doesn't define how to send that API key to the client.

Usage

Create an instance object and use that object as the dependency in Depends().

The dependency result will be a string containing the key value.

Example
from fastapi import Depends, FastAPI
from fastapi.security import APIKeyQuery

app = FastAPI()

query_scheme = APIKeyQuery(name="api_key")


@app.get("/items/")
async def read_items(api_key: str = Depends(query_scheme)):
    return {"api_key": api_key}
Source code in .venv/lib/python3.12/site-packages/fastapi/security/api_key.py
def __init__(
    self,
    *,
    name: Annotated[
        str,
        Doc("Query parameter name."),
    ],
    scheme_name: Annotated[
        Optional[str],
        Doc(
            """
            Security scheme name.

            It will be included in the generated OpenAPI (e.g. visible at `/docs`).
            """
        ),
    ] = None,
    description: Annotated[
        Optional[str],
        Doc(
            """
            Security scheme description.

            It will be included in the generated OpenAPI (e.g. visible at `/docs`).
            """
        ),
    ] = None,
    auto_error: Annotated[
        bool,
        Doc(
            """
            By default, if the query parameter is not provided, `APIKeyQuery` will
            automatically cancel the request and sebd the client an error.

            If `auto_error` is set to `False`, when the query parameter is not
            available, instead of erroring out, the dependency result will be
            `None`.

            This is useful when you want to have optional authentication.

            It is also useful when you want to have authentication that can be
            provided in one of multiple optional ways (for example, in a query
            parameter or in an HTTP Bearer token).
            """
        ),
    ] = True,
):
    self.model: APIKey = APIKey(
        **{"in": APIKeyIn.query},  # type: ignore[arg-type]
        name=name,
        description=description,
    )
    self.scheme_name = scheme_name or self.__class__.__name__
    self.auto_error = auto_error

HTTPAuthorizationCredentials

HTTPAuthorizationCredentials(**data: Any)

Bases: BaseModel

The HTTP authorization credentials in the result of using HTTPBearer or HTTPDigest in a dependency.

The HTTP authorization header value is split by the first space.

The first part is the scheme, the second part is the credentials.

For example, in an HTTP Bearer token scheme, the client will send a header like:

Authorization: Bearer deadbeef12346

In this case:

  • scheme will have the value "Bearer"
  • credentials will have the value "deadbeef12346"

Create a new model by parsing and validating input data from keyword arguments.

Raises ValidationError if the input data cannot be validated to form a valid model.

self is explicitly positional-only to allow self as a field name.

Source code in .venv/lib/python3.12/site-packages/pydantic/main.py
def __init__(self, /, **data: Any) -> None:  # type: ignore
    """Create a new model by parsing and validating input data from keyword arguments.

    Raises [`ValidationError`][pydantic_core.ValidationError] if the input data cannot be
    validated to form a valid model.

    `self` is explicitly positional-only to allow `self` as a field name.
    """
    # `__tracebackhide__` tells pytest and some other tools to omit this function from tracebacks
    __tracebackhide__ = True
    self.__pydantic_validator__.validate_python(data, self_instance=self)

model_config class-attribute instance-attribute

model_config: ConfigDict = ConfigDict()

Configuration for the model, should be a dictionary conforming to ConfigDict.

model_fields class-attribute

model_fields: dict[str, FieldInfo]

Metadata about the fields defined on the model, mapping of field names to FieldInfo.

This replaces Model.__fields__ from Pydantic V1.

model_computed_fields class-attribute

model_computed_fields: dict[str, ComputedFieldInfo]

A dictionary of computed field names and their corresponding ComputedFieldInfo objects.

model_extra property

model_extra: dict[str, Any] | None

Get extra fields set during validation.

Returns:

Type Description
dict[str, Any] | None

A dictionary of extra fields, or None if config.extra is not set to "allow".

model_fields_set property

model_fields_set: set[str]

Returns the set of fields that have been explicitly set on this model instance.

Returns:

Type Description
set[str]

A set of strings representing the fields that have been set, i.e. that were not filled from defaults.

model_construct classmethod

model_construct(
    _fields_set: set[str] | None = None, **values: Any
) -> Model

Creates a new instance of the Model class with validated data.

Creates a new model setting __dict__ and __pydantic_fields_set__ from trusted or pre-validated data. Default values are respected, but no other validation is performed. Behaves as if Config.extra = 'allow' was set since it adds all passed values

Parameters:

Name Type Description Default
_fields_set set[str] | None

The set of field names accepted for the Model instance.

None
values Any

Trusted or pre-validated data dictionary.

{}

Returns:

Type Description
Model

A new instance of the Model class with validated data.

Source code in .venv/lib/python3.12/site-packages/pydantic/main.py
@classmethod
def model_construct(cls: type[Model], _fields_set: set[str] | None = None, **values: Any) -> Model:
    """Creates a new instance of the `Model` class with validated data.

    Creates a new model setting `__dict__` and `__pydantic_fields_set__` from trusted or pre-validated data.
    Default values are respected, but no other validation is performed.
    Behaves as if `Config.extra = 'allow'` was set since it adds all passed values

    Args:
        _fields_set: The set of field names accepted for the Model instance.
        values: Trusted or pre-validated data dictionary.

    Returns:
        A new instance of the `Model` class with validated data.
    """
    m = cls.__new__(cls)
    fields_values: dict[str, Any] = {}
    fields_set = set()

    for name, field in cls.model_fields.items():
        if field.alias and field.alias in values:
            fields_values[name] = values.pop(field.alias)
            fields_set.add(name)
        elif name in values:
            fields_values[name] = values.pop(name)
            fields_set.add(name)
        elif not field.is_required():
            fields_values[name] = field.get_default(call_default_factory=True)
    if _fields_set is None:
        _fields_set = fields_set

    _extra: dict[str, Any] | None = None
    if cls.model_config.get('extra') == 'allow':
        _extra = {}
        for k, v in values.items():
            _extra[k] = v
    else:
        fields_values.update(values)
    _object_setattr(m, '__dict__', fields_values)
    _object_setattr(m, '__pydantic_fields_set__', _fields_set)
    if not cls.__pydantic_root_model__:
        _object_setattr(m, '__pydantic_extra__', _extra)

    if cls.__pydantic_post_init__:
        m.model_post_init(None)
        # update private attributes with values set
        if hasattr(m, '__pydantic_private__') and m.__pydantic_private__ is not None:
            for k, v in values.items():
                if k in m.__private_attributes__:
                    m.__pydantic_private__[k] = v

    elif not cls.__pydantic_root_model__:
        # Note: if there are any private attributes, cls.__pydantic_post_init__ would exist
        # Since it doesn't, that means that `__pydantic_private__` should be set to None
        _object_setattr(m, '__pydantic_private__', None)

    return m

model_copy

model_copy(
    *,
    update: dict[str, Any] | None = None,
    deep: bool = False,
) -> Model

Usage docs: https://docs.pydantic.dev/2.6/concepts/serialization/#model_copy

Returns a copy of the model.

Parameters:

Name Type Description Default
update dict[str, Any] | None

Values to change/add in the new model. Note: the data is not validated before creating the new model. You should trust this data.

None
deep bool

Set to True to make a deep copy of the model.

False

Returns:

Type Description
Model

New model instance.

Source code in .venv/lib/python3.12/site-packages/pydantic/main.py
def model_copy(self: Model, *, update: dict[str, Any] | None = None, deep: bool = False) -> Model:
    """Usage docs: https://docs.pydantic.dev/2.6/concepts/serialization/#model_copy

    Returns a copy of the model.

    Args:
        update: Values to change/add in the new model. Note: the data is not validated
            before creating the new model. You should trust this data.
        deep: Set to `True` to make a deep copy of the model.

    Returns:
        New model instance.
    """
    copied = self.__deepcopy__() if deep else self.__copy__()
    if update:
        if self.model_config.get('extra') == 'allow':
            for k, v in update.items():
                if k in self.model_fields:
                    copied.__dict__[k] = v
                else:
                    if copied.__pydantic_extra__ is None:
                        copied.__pydantic_extra__ = {}
                    copied.__pydantic_extra__[k] = v
        else:
            copied.__dict__.update(update)
        copied.__pydantic_fields_set__.update(update.keys())
    return copied

model_dump

model_dump(
    *,
    mode: Literal["json", "python"] | str = "python",
    include: IncEx = None,
    exclude: IncEx = None,
    by_alias: bool = False,
    exclude_unset: bool = False,
    exclude_defaults: bool = False,
    exclude_none: bool = False,
    round_trip: bool = False,
    warnings: bool = True,
) -> dict[str, Any]

Usage docs: https://docs.pydantic.dev/2.6/concepts/serialization/#modelmodel_dump

Generate a dictionary representation of the model, optionally specifying which fields to include or exclude.

Parameters:

Name Type Description Default
mode Literal['json', 'python'] | str

The mode in which to_python should run. If mode is 'json', the output will only contain JSON serializable types. If mode is 'python', the output may contain non-JSON-serializable Python objects.

'python'
include IncEx

A list of fields to include in the output.

None
exclude IncEx

A list of fields to exclude from the output.

None
by_alias bool

Whether to use the field's alias in the dictionary key if defined.

False
exclude_unset bool

Whether to exclude fields that have not been explicitly set.

False
exclude_defaults bool

Whether to exclude fields that are set to their default value.

False
exclude_none bool

Whether to exclude fields that have a value of None.

False
round_trip bool

If True, dumped values should be valid as input for non-idempotent types such as Json[T].

False
warnings bool

Whether to log warnings when invalid fields are encountered.

True

Returns:

Type Description
dict[str, Any]

A dictionary representation of the model.

Source code in .venv/lib/python3.12/site-packages/pydantic/main.py
def model_dump(
    self,
    *,
    mode: Literal['json', 'python'] | str = 'python',
    include: IncEx = None,
    exclude: IncEx = None,
    by_alias: bool = False,
    exclude_unset: bool = False,
    exclude_defaults: bool = False,
    exclude_none: bool = False,
    round_trip: bool = False,
    warnings: bool = True,
) -> dict[str, Any]:
    """Usage docs: https://docs.pydantic.dev/2.6/concepts/serialization/#modelmodel_dump

    Generate a dictionary representation of the model, optionally specifying which fields to include or exclude.

    Args:
        mode: The mode in which `to_python` should run.
            If mode is 'json', the output will only contain JSON serializable types.
            If mode is 'python', the output may contain non-JSON-serializable Python objects.
        include: A list of fields to include in the output.
        exclude: A list of fields to exclude from the output.
        by_alias: Whether to use the field's alias in the dictionary key if defined.
        exclude_unset: Whether to exclude fields that have not been explicitly set.
        exclude_defaults: Whether to exclude fields that are set to their default value.
        exclude_none: Whether to exclude fields that have a value of `None`.
        round_trip: If True, dumped values should be valid as input for non-idempotent types such as Json[T].
        warnings: Whether to log warnings when invalid fields are encountered.

    Returns:
        A dictionary representation of the model.
    """
    return self.__pydantic_serializer__.to_python(
        self,
        mode=mode,
        by_alias=by_alias,
        include=include,
        exclude=exclude,
        exclude_unset=exclude_unset,
        exclude_defaults=exclude_defaults,
        exclude_none=exclude_none,
        round_trip=round_trip,
        warnings=warnings,
    )

model_dump_json

model_dump_json(
    *,
    indent: int | None = None,
    include: IncEx = None,
    exclude: IncEx = None,
    by_alias: bool = False,
    exclude_unset: bool = False,
    exclude_defaults: bool = False,
    exclude_none: bool = False,
    round_trip: bool = False,
    warnings: bool = True,
) -> str

Usage docs: https://docs.pydantic.dev/2.6/concepts/serialization/#modelmodel_dump_json

Generates a JSON representation of the model using Pydantic's to_json method.

Parameters:

Name Type Description Default
indent int | None

Indentation to use in the JSON output. If None is passed, the output will be compact.

None
include IncEx

Field(s) to include in the JSON output.

None
exclude IncEx

Field(s) to exclude from the JSON output.

None
by_alias bool

Whether to serialize using field aliases.

False
exclude_unset bool

Whether to exclude fields that have not been explicitly set.

False
exclude_defaults bool

Whether to exclude fields that are set to their default value.

False
exclude_none bool

Whether to exclude fields that have a value of None.

False
round_trip bool

If True, dumped values should be valid as input for non-idempotent types such as Json[T].

False
warnings bool

Whether to log warnings when invalid fields are encountered.

True

Returns:

Type Description
str

A JSON string representation of the model.

Source code in .venv/lib/python3.12/site-packages/pydantic/main.py
def model_dump_json(
    self,
    *,
    indent: int | None = None,
    include: IncEx = None,
    exclude: IncEx = None,
    by_alias: bool = False,
    exclude_unset: bool = False,
    exclude_defaults: bool = False,
    exclude_none: bool = False,
    round_trip: bool = False,
    warnings: bool = True,
) -> str:
    """Usage docs: https://docs.pydantic.dev/2.6/concepts/serialization/#modelmodel_dump_json

    Generates a JSON representation of the model using Pydantic's `to_json` method.

    Args:
        indent: Indentation to use in the JSON output. If None is passed, the output will be compact.
        include: Field(s) to include in the JSON output.
        exclude: Field(s) to exclude from the JSON output.
        by_alias: Whether to serialize using field aliases.
        exclude_unset: Whether to exclude fields that have not been explicitly set.
        exclude_defaults: Whether to exclude fields that are set to their default value.
        exclude_none: Whether to exclude fields that have a value of `None`.
        round_trip: If True, dumped values should be valid as input for non-idempotent types such as Json[T].
        warnings: Whether to log warnings when invalid fields are encountered.

    Returns:
        A JSON string representation of the model.
    """
    return self.__pydantic_serializer__.to_json(
        self,
        indent=indent,
        include=include,
        exclude=exclude,
        by_alias=by_alias,
        exclude_unset=exclude_unset,
        exclude_defaults=exclude_defaults,
        exclude_none=exclude_none,
        round_trip=round_trip,
        warnings=warnings,
    ).decode()

model_json_schema classmethod

model_json_schema(
    by_alias: bool = True,
    ref_template: str = DEFAULT_REF_TEMPLATE,
    schema_generator: type[
        GenerateJsonSchema
    ] = GenerateJsonSchema,
    mode: JsonSchemaMode = "validation",
) -> dict[str, Any]

Generates a JSON schema for a model class.

Parameters:

Name Type Description Default
by_alias bool

Whether to use attribute aliases or not.

True
ref_template str

The reference template.

DEFAULT_REF_TEMPLATE
schema_generator type[GenerateJsonSchema]

To override the logic used to generate the JSON schema, as a subclass of GenerateJsonSchema with your desired modifications

GenerateJsonSchema
mode JsonSchemaMode

The mode in which to generate the schema.

'validation'

Returns:

Type Description
dict[str, Any]

The JSON schema for the given model class.

Source code in .venv/lib/python3.12/site-packages/pydantic/main.py
@classmethod
def model_json_schema(
    cls,
    by_alias: bool = True,
    ref_template: str = DEFAULT_REF_TEMPLATE,
    schema_generator: type[GenerateJsonSchema] = GenerateJsonSchema,
    mode: JsonSchemaMode = 'validation',
) -> dict[str, Any]:
    """Generates a JSON schema for a model class.

    Args:
        by_alias: Whether to use attribute aliases or not.
        ref_template: The reference template.
        schema_generator: To override the logic used to generate the JSON schema, as a subclass of
            `GenerateJsonSchema` with your desired modifications
        mode: The mode in which to generate the schema.

    Returns:
        The JSON schema for the given model class.
    """
    return model_json_schema(
        cls, by_alias=by_alias, ref_template=ref_template, schema_generator=schema_generator, mode=mode
    )

model_parametrized_name classmethod

model_parametrized_name(
    params: tuple[type[Any], ...],
) -> str

Compute the class name for parametrizations of generic classes.

This method can be overridden to achieve a custom naming scheme for generic BaseModels.

Parameters:

Name Type Description Default
params tuple[type[Any], ...]

Tuple of types of the class. Given a generic class Model with 2 type variables and a concrete model Model[str, int], the value (str, int) would be passed to params.

required

Returns:

Type Description
str

String representing the new class where params are passed to cls as type variables.

Raises:

Type Description
TypeError

Raised when trying to generate concrete names for non-generic models.

Source code in .venv/lib/python3.12/site-packages/pydantic/main.py
@classmethod
def model_parametrized_name(cls, params: tuple[type[Any], ...]) -> str:
    """Compute the class name for parametrizations of generic classes.

    This method can be overridden to achieve a custom naming scheme for generic BaseModels.

    Args:
        params: Tuple of types of the class. Given a generic class
            `Model` with 2 type variables and a concrete model `Model[str, int]`,
            the value `(str, int)` would be passed to `params`.

    Returns:
        String representing the new class where `params` are passed to `cls` as type variables.

    Raises:
        TypeError: Raised when trying to generate concrete names for non-generic models.
    """
    if not issubclass(cls, typing.Generic):
        raise TypeError('Concrete names should only be generated for generic models.')

    # Any strings received should represent forward references, so we handle them specially below.
    # If we eventually move toward wrapping them in a ForwardRef in __class_getitem__ in the future,
    # we may be able to remove this special case.
    param_names = [param if isinstance(param, str) else _repr.display_as_type(param) for param in params]
    params_component = ', '.join(param_names)
    return f'{cls.__name__}[{params_component}]'

model_post_init

model_post_init(__context: Any) -> None

Override this method to perform additional initialization after __init__ and model_construct. This is useful if you want to do some validation that requires the entire model to be initialized.

Source code in .venv/lib/python3.12/site-packages/pydantic/main.py
def model_post_init(self, __context: Any) -> None:
    """Override this method to perform additional initialization after `__init__` and `model_construct`.
    This is useful if you want to do some validation that requires the entire model to be initialized.
    """
    pass

model_rebuild classmethod

model_rebuild(
    *,
    force: bool = False,
    raise_errors: bool = True,
    _parent_namespace_depth: int = 2,
    _types_namespace: dict[str, Any] | None = None,
) -> bool | None

Try to rebuild the pydantic-core schema for the model.

This may be necessary when one of the annotations is a ForwardRef which could not be resolved during the initial attempt to build the schema, and automatic rebuilding fails.

Parameters:

Name Type Description Default
force bool

Whether to force the rebuilding of the model schema, defaults to False.

False
raise_errors bool

Whether to raise errors, defaults to True.

True
_parent_namespace_depth int

The depth level of the parent namespace, defaults to 2.

2
_types_namespace dict[str, Any] | None

The types namespace, defaults to None.

None

Returns:

Type Description
bool | None

Returns None if the schema is already "complete" and rebuilding was not required.

bool | None

If rebuilding was required, returns True if rebuilding was successful, otherwise False.

Source code in .venv/lib/python3.12/site-packages/pydantic/main.py
@classmethod
def model_rebuild(
    cls,
    *,
    force: bool = False,
    raise_errors: bool = True,
    _parent_namespace_depth: int = 2,
    _types_namespace: dict[str, Any] | None = None,
) -> bool | None:
    """Try to rebuild the pydantic-core schema for the model.

    This may be necessary when one of the annotations is a ForwardRef which could not be resolved during
    the initial attempt to build the schema, and automatic rebuilding fails.

    Args:
        force: Whether to force the rebuilding of the model schema, defaults to `False`.
        raise_errors: Whether to raise errors, defaults to `True`.
        _parent_namespace_depth: The depth level of the parent namespace, defaults to 2.
        _types_namespace: The types namespace, defaults to `None`.

    Returns:
        Returns `None` if the schema is already "complete" and rebuilding was not required.
        If rebuilding _was_ required, returns `True` if rebuilding was successful, otherwise `False`.
    """
    if not force and cls.__pydantic_complete__:
        return None
    else:
        if '__pydantic_core_schema__' in cls.__dict__:
            delattr(cls, '__pydantic_core_schema__')  # delete cached value to ensure full rebuild happens
        if _types_namespace is not None:
            types_namespace: dict[str, Any] | None = _types_namespace.copy()
        else:
            if _parent_namespace_depth > 0:
                frame_parent_ns = _typing_extra.parent_frame_namespace(parent_depth=_parent_namespace_depth) or {}
                cls_parent_ns = (
                    _model_construction.unpack_lenient_weakvaluedict(cls.__pydantic_parent_namespace__) or {}
                )
                types_namespace = {**cls_parent_ns, **frame_parent_ns}
                cls.__pydantic_parent_namespace__ = _model_construction.build_lenient_weakvaluedict(types_namespace)
            else:
                types_namespace = _model_construction.unpack_lenient_weakvaluedict(
                    cls.__pydantic_parent_namespace__
                )

            types_namespace = _typing_extra.get_cls_types_namespace(cls, types_namespace)

        # manually override defer_build so complete_model_class doesn't skip building the model again
        config = {**cls.model_config, 'defer_build': False}
        return _model_construction.complete_model_class(
            cls,
            cls.__name__,
            _config.ConfigWrapper(config, check=False),
            raise_errors=raise_errors,
            types_namespace=types_namespace,
        )

model_validate classmethod

model_validate(
    obj: Any,
    *,
    strict: bool | None = None,
    from_attributes: bool | None = None,
    context: dict[str, Any] | None = None,
) -> Model

Validate a pydantic model instance.

Parameters:

Name Type Description Default
obj Any

The object to validate.

required
strict bool | None

Whether to enforce types strictly.

None
from_attributes bool | None

Whether to extract data from object attributes.

None
context dict[str, Any] | None

Additional context to pass to the validator.

None

Raises:

Type Description
ValidationError

If the object could not be validated.

Returns:

Type Description
Model

The validated model instance.

Source code in .venv/lib/python3.12/site-packages/pydantic/main.py
@classmethod
def model_validate(
    cls: type[Model],
    obj: Any,
    *,
    strict: bool | None = None,
    from_attributes: bool | None = None,
    context: dict[str, Any] | None = None,
) -> Model:
    """Validate a pydantic model instance.

    Args:
        obj: The object to validate.
        strict: Whether to enforce types strictly.
        from_attributes: Whether to extract data from object attributes.
        context: Additional context to pass to the validator.

    Raises:
        ValidationError: If the object could not be validated.

    Returns:
        The validated model instance.
    """
    # `__tracebackhide__` tells pytest and some other tools to omit this function from tracebacks
    __tracebackhide__ = True
    return cls.__pydantic_validator__.validate_python(
        obj, strict=strict, from_attributes=from_attributes, context=context
    )

model_validate_json classmethod

model_validate_json(
    json_data: str | bytes | bytearray,
    *,
    strict: bool | None = None,
    context: dict[str, Any] | None = None,
) -> Model

Usage docs: https://docs.pydantic.dev/2.6/concepts/json/#json-parsing

Validate the given JSON data against the Pydantic model.

Parameters:

Name Type Description Default
json_data str | bytes | bytearray

The JSON data to validate.

required
strict bool | None

Whether to enforce types strictly.

None
context dict[str, Any] | None

Extra variables to pass to the validator.

None

Returns:

Type Description
Model

The validated Pydantic model.

Raises:

Type Description
ValueError

If json_data is not a JSON string.

Source code in .venv/lib/python3.12/site-packages/pydantic/main.py
@classmethod
def model_validate_json(
    cls: type[Model],
    json_data: str | bytes | bytearray,
    *,
    strict: bool | None = None,
    context: dict[str, Any] | None = None,
) -> Model:
    """Usage docs: https://docs.pydantic.dev/2.6/concepts/json/#json-parsing

    Validate the given JSON data against the Pydantic model.

    Args:
        json_data: The JSON data to validate.
        strict: Whether to enforce types strictly.
        context: Extra variables to pass to the validator.

    Returns:
        The validated Pydantic model.

    Raises:
        ValueError: If `json_data` is not a JSON string.
    """
    # `__tracebackhide__` tells pytest and some other tools to omit this function from tracebacks
    __tracebackhide__ = True
    return cls.__pydantic_validator__.validate_json(json_data, strict=strict, context=context)

model_validate_strings classmethod

model_validate_strings(
    obj: Any,
    *,
    strict: bool | None = None,
    context: dict[str, Any] | None = None,
) -> Model

Validate the given object contains string data against the Pydantic model.

Parameters:

Name Type Description Default
obj Any

The object contains string data to validate.

required
strict bool | None

Whether to enforce types strictly.

None
context dict[str, Any] | None

Extra variables to pass to the validator.

None

Returns:

Type Description
Model

The validated Pydantic model.

Source code in .venv/lib/python3.12/site-packages/pydantic/main.py
@classmethod
def model_validate_strings(
    cls: type[Model],
    obj: Any,
    *,
    strict: bool | None = None,
    context: dict[str, Any] | None = None,
) -> Model:
    """Validate the given object contains string data against the Pydantic model.

    Args:
        obj: The object contains string data to validate.
        strict: Whether to enforce types strictly.
        context: Extra variables to pass to the validator.

    Returns:
        The validated Pydantic model.
    """
    # `__tracebackhide__` tells pytest and some other tools to omit this function from tracebacks
    __tracebackhide__ = True
    return cls.__pydantic_validator__.validate_strings(obj, strict=strict, context=context)

copy

copy(
    *,
    include: AbstractSetIntStr
    | MappingIntStrAny
    | None = None,
    exclude: AbstractSetIntStr
    | MappingIntStrAny
    | None = None,
    update: Dict[str, Any] | None = None,
    deep: bool = False,
) -> Model

Returns a copy of the model.

Deprecated

This method is now deprecated; use model_copy instead.

If you need include or exclude, use:

data = self.model_dump(include=include, exclude=exclude, round_trip=True)
data = {**data, **(update or {})}
copied = self.model_validate(data)

Parameters:

Name Type Description Default
include AbstractSetIntStr | MappingIntStrAny | None

Optional set or mapping specifying which fields to include in the copied model.

None
exclude AbstractSetIntStr | MappingIntStrAny | None

Optional set or mapping specifying which fields to exclude in the copied model.

None
update Dict[str, Any] | None

Optional dictionary of field-value pairs to override field values in the copied model.

None
deep bool

If True, the values of fields that are Pydantic models will be deep-copied.

False

Returns:

Type Description
Model

A copy of the model with included, excluded and updated fields as specified.

Source code in .venv/lib/python3.12/site-packages/pydantic/main.py
@typing_extensions.deprecated(
    'The `copy` method is deprecated; use `model_copy` instead. '
    'See the docstring of `BaseModel.copy` for details about how to handle `include` and `exclude`.',
    category=None,
)
def copy(
    self: Model,
    *,
    include: AbstractSetIntStr | MappingIntStrAny | None = None,
    exclude: AbstractSetIntStr | MappingIntStrAny | None = None,
    update: typing.Dict[str, Any] | None = None,  # noqa UP006
    deep: bool = False,
) -> Model:  # pragma: no cover
    """Returns a copy of the model.

    !!! warning "Deprecated"
        This method is now deprecated; use `model_copy` instead.

    If you need `include` or `exclude`, use:

    ```py
    data = self.model_dump(include=include, exclude=exclude, round_trip=True)
    data = {**data, **(update or {})}
    copied = self.model_validate(data)
    ```

    Args:
        include: Optional set or mapping specifying which fields to include in the copied model.
        exclude: Optional set or mapping specifying which fields to exclude in the copied model.
        update: Optional dictionary of field-value pairs to override field values in the copied model.
        deep: If True, the values of fields that are Pydantic models will be deep-copied.

    Returns:
        A copy of the model with included, excluded and updated fields as specified.
    """
    warnings.warn(
        'The `copy` method is deprecated; use `model_copy` instead. '
        'See the docstring of `BaseModel.copy` for details about how to handle `include` and `exclude`.',
        category=PydanticDeprecatedSince20,
    )
    from .deprecated import copy_internals

    values = dict(
        copy_internals._iter(
            self, to_dict=False, by_alias=False, include=include, exclude=exclude, exclude_unset=False
        ),
        **(update or {}),
    )
    if self.__pydantic_private__ is None:
        private = None
    else:
        private = {k: v for k, v in self.__pydantic_private__.items() if v is not PydanticUndefined}

    if self.__pydantic_extra__ is None:
        extra: dict[str, Any] | None = None
    else:
        extra = self.__pydantic_extra__.copy()
        for k in list(self.__pydantic_extra__):
            if k not in values:  # k was in the exclude
                extra.pop(k)
        for k in list(values):
            if k in self.__pydantic_extra__:  # k must have come from extra
                extra[k] = values.pop(k)

    # new `__pydantic_fields_set__` can have unset optional fields with a set value in `update` kwarg
    if update:
        fields_set = self.__pydantic_fields_set__ | update.keys()
    else:
        fields_set = set(self.__pydantic_fields_set__)

    # removing excluded fields from `__pydantic_fields_set__`
    if exclude:
        fields_set -= set(exclude)

    return copy_internals._copy_and_set_values(self, values, fields_set, extra, private, deep=deep)

HTTPBasic

HTTPBasic(
    *,
    scheme_name: Annotated[
        Optional[str],
        Doc(
            "\n                Security scheme name.\n\n                It will be included in the generated OpenAPI (e.g. visible at `/docs`).\n                "
        ),
    ] = None,
    realm: Annotated[
        Optional[str],
        Doc(
            "\n                HTTP Basic authentication realm.\n                "
        ),
    ] = None,
    description: Annotated[
        Optional[str],
        Doc(
            "\n                Security scheme description.\n\n                It will be included in the generated OpenAPI (e.g. visible at `/docs`).\n                "
        ),
    ] = None,
    auto_error: Annotated[
        bool,
        Doc(
            "\n                By default, if the HTTP Basic authentication is not provided (a\n                header), `HTTPBasic` will automatically cancel the request and send the\n                client an error.\n\n                If `auto_error` is set to `False`, when the HTTP Basic authentication\n                is not available, instead of erroring out, the dependency result will\n                be `None`.\n\n                This is useful when you want to have optional authentication.\n\n                It is also useful when you want to have authentication that can be\n                provided in one of multiple optional ways (for example, in HTTP Basic\n                authentication or in an HTTP Bearer token).\n                "
        ),
    ] = True,
)

Bases: HTTPBase

HTTP Basic authentication.

Usage

Create an instance object and use that object as the dependency in Depends().

The dependency result will be an HTTPBasicCredentials object containing the username and the password.

Read more about it in the FastAPI docs for HTTP Basic Auth.

Example
from typing import Annotated

from fastapi import Depends, FastAPI
from fastapi.security import HTTPBasic, HTTPBasicCredentials

app = FastAPI()

security = HTTPBasic()


@app.get("/users/me")
def read_current_user(credentials: Annotated[HTTPBasicCredentials, Depends(security)]):
    return {"username": credentials.username, "password": credentials.password}
Source code in .venv/lib/python3.12/site-packages/fastapi/security/http.py
def __init__(
    self,
    *,
    scheme_name: Annotated[
        Optional[str],
        Doc(
            """
            Security scheme name.

            It will be included in the generated OpenAPI (e.g. visible at `/docs`).
            """
        ),
    ] = None,
    realm: Annotated[
        Optional[str],
        Doc(
            """
            HTTP Basic authentication realm.
            """
        ),
    ] = None,
    description: Annotated[
        Optional[str],
        Doc(
            """
            Security scheme description.

            It will be included in the generated OpenAPI (e.g. visible at `/docs`).
            """
        ),
    ] = None,
    auto_error: Annotated[
        bool,
        Doc(
            """
            By default, if the HTTP Basic authentication is not provided (a
            header), `HTTPBasic` will automatically cancel the request and send the
            client an error.

            If `auto_error` is set to `False`, when the HTTP Basic authentication
            is not available, instead of erroring out, the dependency result will
            be `None`.

            This is useful when you want to have optional authentication.

            It is also useful when you want to have authentication that can be
            provided in one of multiple optional ways (for example, in HTTP Basic
            authentication or in an HTTP Bearer token).
            """
        ),
    ] = True,
):
    self.model = HTTPBaseModel(scheme="basic", description=description)
    self.scheme_name = scheme_name or self.__class__.__name__
    self.realm = realm
    self.auto_error = auto_error

HTTPBasicCredentials

HTTPBasicCredentials(**data: Any)

Bases: BaseModel

The HTTP Basic credendials given as the result of using HTTPBasic in a dependency.

Read more about it in the FastAPI docs for HTTP Basic Auth.

Create a new model by parsing and validating input data from keyword arguments.

Raises ValidationError if the input data cannot be validated to form a valid model.

self is explicitly positional-only to allow self as a field name.

Source code in .venv/lib/python3.12/site-packages/pydantic/main.py
def __init__(self, /, **data: Any) -> None:  # type: ignore
    """Create a new model by parsing and validating input data from keyword arguments.

    Raises [`ValidationError`][pydantic_core.ValidationError] if the input data cannot be
    validated to form a valid model.

    `self` is explicitly positional-only to allow `self` as a field name.
    """
    # `__tracebackhide__` tells pytest and some other tools to omit this function from tracebacks
    __tracebackhide__ = True
    self.__pydantic_validator__.validate_python(data, self_instance=self)

model_config class-attribute instance-attribute

model_config: ConfigDict = ConfigDict()

Configuration for the model, should be a dictionary conforming to ConfigDict.

model_fields class-attribute

model_fields: dict[str, FieldInfo]

Metadata about the fields defined on the model, mapping of field names to FieldInfo.

This replaces Model.__fields__ from Pydantic V1.

model_computed_fields class-attribute

model_computed_fields: dict[str, ComputedFieldInfo]

A dictionary of computed field names and their corresponding ComputedFieldInfo objects.

model_extra property

model_extra: dict[str, Any] | None

Get extra fields set during validation.

Returns:

Type Description
dict[str, Any] | None

A dictionary of extra fields, or None if config.extra is not set to "allow".

model_fields_set property

model_fields_set: set[str]

Returns the set of fields that have been explicitly set on this model instance.

Returns:

Type Description
set[str]

A set of strings representing the fields that have been set, i.e. that were not filled from defaults.

model_construct classmethod

model_construct(
    _fields_set: set[str] | None = None, **values: Any
) -> Model

Creates a new instance of the Model class with validated data.

Creates a new model setting __dict__ and __pydantic_fields_set__ from trusted or pre-validated data. Default values are respected, but no other validation is performed. Behaves as if Config.extra = 'allow' was set since it adds all passed values

Parameters:

Name Type Description Default
_fields_set set[str] | None

The set of field names accepted for the Model instance.

None
values Any

Trusted or pre-validated data dictionary.

{}

Returns:

Type Description
Model

A new instance of the Model class with validated data.

Source code in .venv/lib/python3.12/site-packages/pydantic/main.py
@classmethod
def model_construct(cls: type[Model], _fields_set: set[str] | None = None, **values: Any) -> Model:
    """Creates a new instance of the `Model` class with validated data.

    Creates a new model setting `__dict__` and `__pydantic_fields_set__` from trusted or pre-validated data.
    Default values are respected, but no other validation is performed.
    Behaves as if `Config.extra = 'allow'` was set since it adds all passed values

    Args:
        _fields_set: The set of field names accepted for the Model instance.
        values: Trusted or pre-validated data dictionary.

    Returns:
        A new instance of the `Model` class with validated data.
    """
    m = cls.__new__(cls)
    fields_values: dict[str, Any] = {}
    fields_set = set()

    for name, field in cls.model_fields.items():
        if field.alias and field.alias in values:
            fields_values[name] = values.pop(field.alias)
            fields_set.add(name)
        elif name in values:
            fields_values[name] = values.pop(name)
            fields_set.add(name)
        elif not field.is_required():
            fields_values[name] = field.get_default(call_default_factory=True)
    if _fields_set is None:
        _fields_set = fields_set

    _extra: dict[str, Any] | None = None
    if cls.model_config.get('extra') == 'allow':
        _extra = {}
        for k, v in values.items():
            _extra[k] = v
    else:
        fields_values.update(values)
    _object_setattr(m, '__dict__', fields_values)
    _object_setattr(m, '__pydantic_fields_set__', _fields_set)
    if not cls.__pydantic_root_model__:
        _object_setattr(m, '__pydantic_extra__', _extra)

    if cls.__pydantic_post_init__:
        m.model_post_init(None)
        # update private attributes with values set
        if hasattr(m, '__pydantic_private__') and m.__pydantic_private__ is not None:
            for k, v in values.items():
                if k in m.__private_attributes__:
                    m.__pydantic_private__[k] = v

    elif not cls.__pydantic_root_model__:
        # Note: if there are any private attributes, cls.__pydantic_post_init__ would exist
        # Since it doesn't, that means that `__pydantic_private__` should be set to None
        _object_setattr(m, '__pydantic_private__', None)

    return m

model_copy

model_copy(
    *,
    update: dict[str, Any] | None = None,
    deep: bool = False,
) -> Model

Usage docs: https://docs.pydantic.dev/2.6/concepts/serialization/#model_copy

Returns a copy of the model.

Parameters:

Name Type Description Default
update dict[str, Any] | None

Values to change/add in the new model. Note: the data is not validated before creating the new model. You should trust this data.

None
deep bool

Set to True to make a deep copy of the model.

False

Returns:

Type Description
Model

New model instance.

Source code in .venv/lib/python3.12/site-packages/pydantic/main.py
def model_copy(self: Model, *, update: dict[str, Any] | None = None, deep: bool = False) -> Model:
    """Usage docs: https://docs.pydantic.dev/2.6/concepts/serialization/#model_copy

    Returns a copy of the model.

    Args:
        update: Values to change/add in the new model. Note: the data is not validated
            before creating the new model. You should trust this data.
        deep: Set to `True` to make a deep copy of the model.

    Returns:
        New model instance.
    """
    copied = self.__deepcopy__() if deep else self.__copy__()
    if update:
        if self.model_config.get('extra') == 'allow':
            for k, v in update.items():
                if k in self.model_fields:
                    copied.__dict__[k] = v
                else:
                    if copied.__pydantic_extra__ is None:
                        copied.__pydantic_extra__ = {}
                    copied.__pydantic_extra__[k] = v
        else:
            copied.__dict__.update(update)
        copied.__pydantic_fields_set__.update(update.keys())
    return copied

model_dump

model_dump(
    *,
    mode: Literal["json", "python"] | str = "python",
    include: IncEx = None,
    exclude: IncEx = None,
    by_alias: bool = False,
    exclude_unset: bool = False,
    exclude_defaults: bool = False,
    exclude_none: bool = False,
    round_trip: bool = False,
    warnings: bool = True,
) -> dict[str, Any]

Usage docs: https://docs.pydantic.dev/2.6/concepts/serialization/#modelmodel_dump

Generate a dictionary representation of the model, optionally specifying which fields to include or exclude.

Parameters:

Name Type Description Default
mode Literal['json', 'python'] | str

The mode in which to_python should run. If mode is 'json', the output will only contain JSON serializable types. If mode is 'python', the output may contain non-JSON-serializable Python objects.

'python'
include IncEx

A list of fields to include in the output.

None
exclude IncEx

A list of fields to exclude from the output.

None
by_alias bool

Whether to use the field's alias in the dictionary key if defined.

False
exclude_unset bool

Whether to exclude fields that have not been explicitly set.

False
exclude_defaults bool

Whether to exclude fields that are set to their default value.

False
exclude_none bool

Whether to exclude fields that have a value of None.

False
round_trip bool

If True, dumped values should be valid as input for non-idempotent types such as Json[T].

False
warnings bool

Whether to log warnings when invalid fields are encountered.

True

Returns:

Type Description
dict[str, Any]

A dictionary representation of the model.

Source code in .venv/lib/python3.12/site-packages/pydantic/main.py
def model_dump(
    self,
    *,
    mode: Literal['json', 'python'] | str = 'python',
    include: IncEx = None,
    exclude: IncEx = None,
    by_alias: bool = False,
    exclude_unset: bool = False,
    exclude_defaults: bool = False,
    exclude_none: bool = False,
    round_trip: bool = False,
    warnings: bool = True,
) -> dict[str, Any]:
    """Usage docs: https://docs.pydantic.dev/2.6/concepts/serialization/#modelmodel_dump

    Generate a dictionary representation of the model, optionally specifying which fields to include or exclude.

    Args:
        mode: The mode in which `to_python` should run.
            If mode is 'json', the output will only contain JSON serializable types.
            If mode is 'python', the output may contain non-JSON-serializable Python objects.
        include: A list of fields to include in the output.
        exclude: A list of fields to exclude from the output.
        by_alias: Whether to use the field's alias in the dictionary key if defined.
        exclude_unset: Whether to exclude fields that have not been explicitly set.
        exclude_defaults: Whether to exclude fields that are set to their default value.
        exclude_none: Whether to exclude fields that have a value of `None`.
        round_trip: If True, dumped values should be valid as input for non-idempotent types such as Json[T].
        warnings: Whether to log warnings when invalid fields are encountered.

    Returns:
        A dictionary representation of the model.
    """
    return self.__pydantic_serializer__.to_python(
        self,
        mode=mode,
        by_alias=by_alias,
        include=include,
        exclude=exclude,
        exclude_unset=exclude_unset,
        exclude_defaults=exclude_defaults,
        exclude_none=exclude_none,
        round_trip=round_trip,
        warnings=warnings,
    )

model_dump_json

model_dump_json(
    *,
    indent: int | None = None,
    include: IncEx = None,
    exclude: IncEx = None,
    by_alias: bool = False,
    exclude_unset: bool = False,
    exclude_defaults: bool = False,
    exclude_none: bool = False,
    round_trip: bool = False,
    warnings: bool = True,
) -> str

Usage docs: https://docs.pydantic.dev/2.6/concepts/serialization/#modelmodel_dump_json

Generates a JSON representation of the model using Pydantic's to_json method.

Parameters:

Name Type Description Default
indent int | None

Indentation to use in the JSON output. If None is passed, the output will be compact.

None
include IncEx

Field(s) to include in the JSON output.

None
exclude IncEx

Field(s) to exclude from the JSON output.

None
by_alias bool

Whether to serialize using field aliases.

False
exclude_unset bool

Whether to exclude fields that have not been explicitly set.

False
exclude_defaults bool

Whether to exclude fields that are set to their default value.

False
exclude_none bool

Whether to exclude fields that have a value of None.

False
round_trip bool

If True, dumped values should be valid as input for non-idempotent types such as Json[T].

False
warnings bool

Whether to log warnings when invalid fields are encountered.

True

Returns:

Type Description
str

A JSON string representation of the model.

Source code in .venv/lib/python3.12/site-packages/pydantic/main.py
def model_dump_json(
    self,
    *,
    indent: int | None = None,
    include: IncEx = None,
    exclude: IncEx = None,
    by_alias: bool = False,
    exclude_unset: bool = False,
    exclude_defaults: bool = False,
    exclude_none: bool = False,
    round_trip: bool = False,
    warnings: bool = True,
) -> str:
    """Usage docs: https://docs.pydantic.dev/2.6/concepts/serialization/#modelmodel_dump_json

    Generates a JSON representation of the model using Pydantic's `to_json` method.

    Args:
        indent: Indentation to use in the JSON output. If None is passed, the output will be compact.
        include: Field(s) to include in the JSON output.
        exclude: Field(s) to exclude from the JSON output.
        by_alias: Whether to serialize using field aliases.
        exclude_unset: Whether to exclude fields that have not been explicitly set.
        exclude_defaults: Whether to exclude fields that are set to their default value.
        exclude_none: Whether to exclude fields that have a value of `None`.
        round_trip: If True, dumped values should be valid as input for non-idempotent types such as Json[T].
        warnings: Whether to log warnings when invalid fields are encountered.

    Returns:
        A JSON string representation of the model.
    """
    return self.__pydantic_serializer__.to_json(
        self,
        indent=indent,
        include=include,
        exclude=exclude,
        by_alias=by_alias,
        exclude_unset=exclude_unset,
        exclude_defaults=exclude_defaults,
        exclude_none=exclude_none,
        round_trip=round_trip,
        warnings=warnings,
    ).decode()

model_json_schema classmethod

model_json_schema(
    by_alias: bool = True,
    ref_template: str = DEFAULT_REF_TEMPLATE,
    schema_generator: type[
        GenerateJsonSchema
    ] = GenerateJsonSchema,
    mode: JsonSchemaMode = "validation",
) -> dict[str, Any]

Generates a JSON schema for a model class.

Parameters:

Name Type Description Default
by_alias bool

Whether to use attribute aliases or not.

True
ref_template str

The reference template.

DEFAULT_REF_TEMPLATE
schema_generator type[GenerateJsonSchema]

To override the logic used to generate the JSON schema, as a subclass of GenerateJsonSchema with your desired modifications

GenerateJsonSchema
mode JsonSchemaMode

The mode in which to generate the schema.

'validation'

Returns:

Type Description
dict[str, Any]

The JSON schema for the given model class.

Source code in .venv/lib/python3.12/site-packages/pydantic/main.py
@classmethod
def model_json_schema(
    cls,
    by_alias: bool = True,
    ref_template: str = DEFAULT_REF_TEMPLATE,
    schema_generator: type[GenerateJsonSchema] = GenerateJsonSchema,
    mode: JsonSchemaMode = 'validation',
) -> dict[str, Any]:
    """Generates a JSON schema for a model class.

    Args:
        by_alias: Whether to use attribute aliases or not.
        ref_template: The reference template.
        schema_generator: To override the logic used to generate the JSON schema, as a subclass of
            `GenerateJsonSchema` with your desired modifications
        mode: The mode in which to generate the schema.

    Returns:
        The JSON schema for the given model class.
    """
    return model_json_schema(
        cls, by_alias=by_alias, ref_template=ref_template, schema_generator=schema_generator, mode=mode
    )

model_parametrized_name classmethod

model_parametrized_name(
    params: tuple[type[Any], ...],
) -> str

Compute the class name for parametrizations of generic classes.

This method can be overridden to achieve a custom naming scheme for generic BaseModels.

Parameters:

Name Type Description Default
params tuple[type[Any], ...]

Tuple of types of the class. Given a generic class Model with 2 type variables and a concrete model Model[str, int], the value (str, int) would be passed to params.

required

Returns:

Type Description
str

String representing the new class where params are passed to cls as type variables.

Raises:

Type Description
TypeError

Raised when trying to generate concrete names for non-generic models.

Source code in .venv/lib/python3.12/site-packages/pydantic/main.py
@classmethod
def model_parametrized_name(cls, params: tuple[type[Any], ...]) -> str:
    """Compute the class name for parametrizations of generic classes.

    This method can be overridden to achieve a custom naming scheme for generic BaseModels.

    Args:
        params: Tuple of types of the class. Given a generic class
            `Model` with 2 type variables and a concrete model `Model[str, int]`,
            the value `(str, int)` would be passed to `params`.

    Returns:
        String representing the new class where `params` are passed to `cls` as type variables.

    Raises:
        TypeError: Raised when trying to generate concrete names for non-generic models.
    """
    if not issubclass(cls, typing.Generic):
        raise TypeError('Concrete names should only be generated for generic models.')

    # Any strings received should represent forward references, so we handle them specially below.
    # If we eventually move toward wrapping them in a ForwardRef in __class_getitem__ in the future,
    # we may be able to remove this special case.
    param_names = [param if isinstance(param, str) else _repr.display_as_type(param) for param in params]
    params_component = ', '.join(param_names)
    return f'{cls.__name__}[{params_component}]'

model_post_init

model_post_init(__context: Any) -> None

Override this method to perform additional initialization after __init__ and model_construct. This is useful if you want to do some validation that requires the entire model to be initialized.

Source code in .venv/lib/python3.12/site-packages/pydantic/main.py
def model_post_init(self, __context: Any) -> None:
    """Override this method to perform additional initialization after `__init__` and `model_construct`.
    This is useful if you want to do some validation that requires the entire model to be initialized.
    """
    pass

model_rebuild classmethod

model_rebuild(
    *,
    force: bool = False,
    raise_errors: bool = True,
    _parent_namespace_depth: int = 2,
    _types_namespace: dict[str, Any] | None = None,
) -> bool | None

Try to rebuild the pydantic-core schema for the model.

This may be necessary when one of the annotations is a ForwardRef which could not be resolved during the initial attempt to build the schema, and automatic rebuilding fails.

Parameters:

Name Type Description Default
force bool

Whether to force the rebuilding of the model schema, defaults to False.

False
raise_errors bool

Whether to raise errors, defaults to True.

True
_parent_namespace_depth int

The depth level of the parent namespace, defaults to 2.

2
_types_namespace dict[str, Any] | None

The types namespace, defaults to None.

None

Returns:

Type Description
bool | None

Returns None if the schema is already "complete" and rebuilding was not required.

bool | None

If rebuilding was required, returns True if rebuilding was successful, otherwise False.

Source code in .venv/lib/python3.12/site-packages/pydantic/main.py
@classmethod
def model_rebuild(
    cls,
    *,
    force: bool = False,
    raise_errors: bool = True,
    _parent_namespace_depth: int = 2,
    _types_namespace: dict[str, Any] | None = None,
) -> bool | None:
    """Try to rebuild the pydantic-core schema for the model.

    This may be necessary when one of the annotations is a ForwardRef which could not be resolved during
    the initial attempt to build the schema, and automatic rebuilding fails.

    Args:
        force: Whether to force the rebuilding of the model schema, defaults to `False`.
        raise_errors: Whether to raise errors, defaults to `True`.
        _parent_namespace_depth: The depth level of the parent namespace, defaults to 2.
        _types_namespace: The types namespace, defaults to `None`.

    Returns:
        Returns `None` if the schema is already "complete" and rebuilding was not required.
        If rebuilding _was_ required, returns `True` if rebuilding was successful, otherwise `False`.
    """
    if not force and cls.__pydantic_complete__:
        return None
    else:
        if '__pydantic_core_schema__' in cls.__dict__:
            delattr(cls, '__pydantic_core_schema__')  # delete cached value to ensure full rebuild happens
        if _types_namespace is not None:
            types_namespace: dict[str, Any] | None = _types_namespace.copy()
        else:
            if _parent_namespace_depth > 0:
                frame_parent_ns = _typing_extra.parent_frame_namespace(parent_depth=_parent_namespace_depth) or {}
                cls_parent_ns = (
                    _model_construction.unpack_lenient_weakvaluedict(cls.__pydantic_parent_namespace__) or {}
                )
                types_namespace = {**cls_parent_ns, **frame_parent_ns}
                cls.__pydantic_parent_namespace__ = _model_construction.build_lenient_weakvaluedict(types_namespace)
            else:
                types_namespace = _model_construction.unpack_lenient_weakvaluedict(
                    cls.__pydantic_parent_namespace__
                )

            types_namespace = _typing_extra.get_cls_types_namespace(cls, types_namespace)

        # manually override defer_build so complete_model_class doesn't skip building the model again
        config = {**cls.model_config, 'defer_build': False}
        return _model_construction.complete_model_class(
            cls,
            cls.__name__,
            _config.ConfigWrapper(config, check=False),
            raise_errors=raise_errors,
            types_namespace=types_namespace,
        )

model_validate classmethod

model_validate(
    obj: Any,
    *,
    strict: bool | None = None,
    from_attributes: bool | None = None,
    context: dict[str, Any] | None = None,
) -> Model

Validate a pydantic model instance.

Parameters:

Name Type Description Default
obj Any

The object to validate.

required
strict bool | None

Whether to enforce types strictly.

None
from_attributes bool | None

Whether to extract data from object attributes.

None
context dict[str, Any] | None

Additional context to pass to the validator.

None

Raises:

Type Description
ValidationError

If the object could not be validated.

Returns:

Type Description
Model

The validated model instance.

Source code in .venv/lib/python3.12/site-packages/pydantic/main.py
@classmethod
def model_validate(
    cls: type[Model],
    obj: Any,
    *,
    strict: bool | None = None,
    from_attributes: bool | None = None,
    context: dict[str, Any] | None = None,
) -> Model:
    """Validate a pydantic model instance.

    Args:
        obj: The object to validate.
        strict: Whether to enforce types strictly.
        from_attributes: Whether to extract data from object attributes.
        context: Additional context to pass to the validator.

    Raises:
        ValidationError: If the object could not be validated.

    Returns:
        The validated model instance.
    """
    # `__tracebackhide__` tells pytest and some other tools to omit this function from tracebacks
    __tracebackhide__ = True
    return cls.__pydantic_validator__.validate_python(
        obj, strict=strict, from_attributes=from_attributes, context=context
    )

model_validate_json classmethod

model_validate_json(
    json_data: str | bytes | bytearray,
    *,
    strict: bool | None = None,
    context: dict[str, Any] | None = None,
) -> Model

Usage docs: https://docs.pydantic.dev/2.6/concepts/json/#json-parsing

Validate the given JSON data against the Pydantic model.

Parameters:

Name Type Description Default
json_data str | bytes | bytearray

The JSON data to validate.

required
strict bool | None

Whether to enforce types strictly.

None
context dict[str, Any] | None

Extra variables to pass to the validator.

None

Returns:

Type Description
Model

The validated Pydantic model.

Raises:

Type Description
ValueError

If json_data is not a JSON string.

Source code in .venv/lib/python3.12/site-packages/pydantic/main.py
@classmethod
def model_validate_json(
    cls: type[Model],
    json_data: str | bytes | bytearray,
    *,
    strict: bool | None = None,
    context: dict[str, Any] | None = None,
) -> Model:
    """Usage docs: https://docs.pydantic.dev/2.6/concepts/json/#json-parsing

    Validate the given JSON data against the Pydantic model.

    Args:
        json_data: The JSON data to validate.
        strict: Whether to enforce types strictly.
        context: Extra variables to pass to the validator.

    Returns:
        The validated Pydantic model.

    Raises:
        ValueError: If `json_data` is not a JSON string.
    """
    # `__tracebackhide__` tells pytest and some other tools to omit this function from tracebacks
    __tracebackhide__ = True
    return cls.__pydantic_validator__.validate_json(json_data, strict=strict, context=context)

model_validate_strings classmethod

model_validate_strings(
    obj: Any,
    *,
    strict: bool | None = None,
    context: dict[str, Any] | None = None,
) -> Model

Validate the given object contains string data against the Pydantic model.

Parameters:

Name Type Description Default
obj Any

The object contains string data to validate.

required
strict bool | None

Whether to enforce types strictly.

None
context dict[str, Any] | None

Extra variables to pass to the validator.

None

Returns:

Type Description
Model

The validated Pydantic model.

Source code in .venv/lib/python3.12/site-packages/pydantic/main.py
@classmethod
def model_validate_strings(
    cls: type[Model],
    obj: Any,
    *,
    strict: bool | None = None,
    context: dict[str, Any] | None = None,
) -> Model:
    """Validate the given object contains string data against the Pydantic model.

    Args:
        obj: The object contains string data to validate.
        strict: Whether to enforce types strictly.
        context: Extra variables to pass to the validator.

    Returns:
        The validated Pydantic model.
    """
    # `__tracebackhide__` tells pytest and some other tools to omit this function from tracebacks
    __tracebackhide__ = True
    return cls.__pydantic_validator__.validate_strings(obj, strict=strict, context=context)

copy

copy(
    *,
    include: AbstractSetIntStr
    | MappingIntStrAny
    | None = None,
    exclude: AbstractSetIntStr
    | MappingIntStrAny
    | None = None,
    update: Dict[str, Any] | None = None,
    deep: bool = False,
) -> Model

Returns a copy of the model.

Deprecated

This method is now deprecated; use model_copy instead.

If you need include or exclude, use:

data = self.model_dump(include=include, exclude=exclude, round_trip=True)
data = {**data, **(update or {})}
copied = self.model_validate(data)

Parameters:

Name Type Description Default
include AbstractSetIntStr | MappingIntStrAny | None

Optional set or mapping specifying which fields to include in the copied model.

None
exclude AbstractSetIntStr | MappingIntStrAny | None

Optional set or mapping specifying which fields to exclude in the copied model.

None
update Dict[str, Any] | None

Optional dictionary of field-value pairs to override field values in the copied model.

None
deep bool

If True, the values of fields that are Pydantic models will be deep-copied.

False

Returns:

Type Description
Model

A copy of the model with included, excluded and updated fields as specified.

Source code in .venv/lib/python3.12/site-packages/pydantic/main.py
@typing_extensions.deprecated(
    'The `copy` method is deprecated; use `model_copy` instead. '
    'See the docstring of `BaseModel.copy` for details about how to handle `include` and `exclude`.',
    category=None,
)
def copy(
    self: Model,
    *,
    include: AbstractSetIntStr | MappingIntStrAny | None = None,
    exclude: AbstractSetIntStr | MappingIntStrAny | None = None,
    update: typing.Dict[str, Any] | None = None,  # noqa UP006
    deep: bool = False,
) -> Model:  # pragma: no cover
    """Returns a copy of the model.

    !!! warning "Deprecated"
        This method is now deprecated; use `model_copy` instead.

    If you need `include` or `exclude`, use:

    ```py
    data = self.model_dump(include=include, exclude=exclude, round_trip=True)
    data = {**data, **(update or {})}
    copied = self.model_validate(data)
    ```

    Args:
        include: Optional set or mapping specifying which fields to include in the copied model.
        exclude: Optional set or mapping specifying which fields to exclude in the copied model.
        update: Optional dictionary of field-value pairs to override field values in the copied model.
        deep: If True, the values of fields that are Pydantic models will be deep-copied.

    Returns:
        A copy of the model with included, excluded and updated fields as specified.
    """
    warnings.warn(
        'The `copy` method is deprecated; use `model_copy` instead. '
        'See the docstring of `BaseModel.copy` for details about how to handle `include` and `exclude`.',
        category=PydanticDeprecatedSince20,
    )
    from .deprecated import copy_internals

    values = dict(
        copy_internals._iter(
            self, to_dict=False, by_alias=False, include=include, exclude=exclude, exclude_unset=False
        ),
        **(update or {}),
    )
    if self.__pydantic_private__ is None:
        private = None
    else:
        private = {k: v for k, v in self.__pydantic_private__.items() if v is not PydanticUndefined}

    if self.__pydantic_extra__ is None:
        extra: dict[str, Any] | None = None
    else:
        extra = self.__pydantic_extra__.copy()
        for k in list(self.__pydantic_extra__):
            if k not in values:  # k was in the exclude
                extra.pop(k)
        for k in list(values):
            if k in self.__pydantic_extra__:  # k must have come from extra
                extra[k] = values.pop(k)

    # new `__pydantic_fields_set__` can have unset optional fields with a set value in `update` kwarg
    if update:
        fields_set = self.__pydantic_fields_set__ | update.keys()
    else:
        fields_set = set(self.__pydantic_fields_set__)

    # removing excluded fields from `__pydantic_fields_set__`
    if exclude:
        fields_set -= set(exclude)

    return copy_internals._copy_and_set_values(self, values, fields_set, extra, private, deep=deep)

HTTPBearer

HTTPBearer(
    *,
    bearerFormat: Annotated[
        Optional[str], Doc("Bearer token format.")
    ] = None,
    scheme_name: Annotated[
        Optional[str],
        Doc(
            "\n                Security scheme name.\n\n                It will be included in the generated OpenAPI (e.g. visible at `/docs`).\n                "
        ),
    ] = None,
    description: Annotated[
        Optional[str],
        Doc(
            "\n                Security scheme description.\n\n                It will be included in the generated OpenAPI (e.g. visible at `/docs`).\n                "
        ),
    ] = None,
    auto_error: Annotated[
        bool,
        Doc(
            "\n                By default, if the HTTP Bearer token not provided (in an\n                `Authorization` header), `HTTPBearer` will automatically cancel the\n                request and send the client an error.\n\n                If `auto_error` is set to `False`, when the HTTP Bearer token\n                is not available, instead of erroring out, the dependency result will\n                be `None`.\n\n                This is useful when you want to have optional authentication.\n\n                It is also useful when you want to have authentication that can be\n                provided in one of multiple optional ways (for example, in an HTTP\n                Bearer token or in a cookie).\n                "
        ),
    ] = True,
)

Bases: HTTPBase

HTTP Bearer token authentication.

Usage

Create an instance object and use that object as the dependency in Depends().

The dependency result will be an HTTPAuthorizationCredentials object containing the scheme and the credentials.

Example
from typing import Annotated

from fastapi import Depends, FastAPI
from fastapi.security import HTTPAuthorizationCredentials, HTTPBearer

app = FastAPI()

security = HTTPBearer()


@app.get("/users/me")
def read_current_user(
    credentials: Annotated[HTTPAuthorizationCredentials, Depends(security)]
):
    return {"scheme": credentials.scheme, "credentials": credentials.credentials}
Source code in .venv/lib/python3.12/site-packages/fastapi/security/http.py
def __init__(
    self,
    *,
    bearerFormat: Annotated[Optional[str], Doc("Bearer token format.")] = None,
    scheme_name: Annotated[
        Optional[str],
        Doc(
            """
            Security scheme name.

            It will be included in the generated OpenAPI (e.g. visible at `/docs`).
            """
        ),
    ] = None,
    description: Annotated[
        Optional[str],
        Doc(
            """
            Security scheme description.

            It will be included in the generated OpenAPI (e.g. visible at `/docs`).
            """
        ),
    ] = None,
    auto_error: Annotated[
        bool,
        Doc(
            """
            By default, if the HTTP Bearer token not provided (in an
            `Authorization` header), `HTTPBearer` will automatically cancel the
            request and send the client an error.

            If `auto_error` is set to `False`, when the HTTP Bearer token
            is not available, instead of erroring out, the dependency result will
            be `None`.

            This is useful when you want to have optional authentication.

            It is also useful when you want to have authentication that can be
            provided in one of multiple optional ways (for example, in an HTTP
            Bearer token or in a cookie).
            """
        ),
    ] = True,
):
    self.model = HTTPBearerModel(bearerFormat=bearerFormat, description=description)
    self.scheme_name = scheme_name or self.__class__.__name__
    self.auto_error = auto_error

HTTPDigest

HTTPDigest(
    *,
    scheme_name: Annotated[
        Optional[str],
        Doc(
            "\n                Security scheme name.\n\n                It will be included in the generated OpenAPI (e.g. visible at `/docs`).\n                "
        ),
    ] = None,
    description: Annotated[
        Optional[str],
        Doc(
            "\n                Security scheme description.\n\n                It will be included in the generated OpenAPI (e.g. visible at `/docs`).\n                "
        ),
    ] = None,
    auto_error: Annotated[
        bool,
        Doc(
            "\n                By default, if the HTTP Digest not provided, `HTTPDigest` will\n                automatically cancel the request and send the client an error.\n\n                If `auto_error` is set to `False`, when the HTTP Digest is not\n                available, instead of erroring out, the dependency result will\n                be `None`.\n\n                This is useful when you want to have optional authentication.\n\n                It is also useful when you want to have authentication that can be\n                provided in one of multiple optional ways (for example, in HTTP\n                Digest or in a cookie).\n                "
        ),
    ] = True,
)

Bases: HTTPBase

HTTP Digest authentication.

Usage

Create an instance object and use that object as the dependency in Depends().

The dependency result will be an HTTPAuthorizationCredentials object containing the scheme and the credentials.

Example
from typing import Annotated

from fastapi import Depends, FastAPI
from fastapi.security import HTTPAuthorizationCredentials, HTTPDigest

app = FastAPI()

security = HTTPDigest()


@app.get("/users/me")
def read_current_user(
    credentials: Annotated[HTTPAuthorizationCredentials, Depends(security)]
):
    return {"scheme": credentials.scheme, "credentials": credentials.credentials}
Source code in .venv/lib/python3.12/site-packages/fastapi/security/http.py
def __init__(
    self,
    *,
    scheme_name: Annotated[
        Optional[str],
        Doc(
            """
            Security scheme name.

            It will be included in the generated OpenAPI (e.g. visible at `/docs`).
            """
        ),
    ] = None,
    description: Annotated[
        Optional[str],
        Doc(
            """
            Security scheme description.

            It will be included in the generated OpenAPI (e.g. visible at `/docs`).
            """
        ),
    ] = None,
    auto_error: Annotated[
        bool,
        Doc(
            """
            By default, if the HTTP Digest not provided, `HTTPDigest` will
            automatically cancel the request and send the client an error.

            If `auto_error` is set to `False`, when the HTTP Digest is not
            available, instead of erroring out, the dependency result will
            be `None`.

            This is useful when you want to have optional authentication.

            It is also useful when you want to have authentication that can be
            provided in one of multiple optional ways (for example, in HTTP
            Digest or in a cookie).
            """
        ),
    ] = True,
):
    self.model = HTTPBaseModel(scheme="digest", description=description)
    self.scheme_name = scheme_name or self.__class__.__name__
    self.auto_error = auto_error

OAuth2

OAuth2(
    *,
    flows: Annotated[
        Union[OAuthFlows, Dict[str, Dict[str, Any]]],
        Doc(
            "\n                The dictionary of OAuth2 flows.\n                "
        ),
    ] = OAuthFlows(),
    scheme_name: Annotated[
        Optional[str],
        Doc(
            "\n                Security scheme name.\n\n                It will be included in the generated OpenAPI (e.g. visible at `/docs`).\n                "
        ),
    ] = None,
    description: Annotated[
        Optional[str],
        Doc(
            "\n                Security scheme description.\n\n                It will be included in the generated OpenAPI (e.g. visible at `/docs`).\n                "
        ),
    ] = None,
    auto_error: Annotated[
        bool,
        Doc(
            "\n                By default, if no HTTP Authorization header is provided, required for\n                OAuth2 authentication, it will automatically cancel the request and\n                send the client an error.\n\n                If `auto_error` is set to `False`, when the HTTP Authorization header\n                is not available, instead of erroring out, the dependency result will\n                be `None`.\n\n                This is useful when you want to have optional authentication.\n\n                It is also useful when you want to have authentication that can be\n                provided in one of multiple optional ways (for example, with OAuth2\n                or in a cookie).\n                "
        ),
    ] = True,
)

Bases: SecurityBase

This is the base class for OAuth2 authentication, an instance of it would be used as a dependency. All other OAuth2 classes inherit from it and customize it for each OAuth2 flow.

You normally would not create a new class inheriting from it but use one of the existing subclasses, and maybe compose them if you want to support multiple flows.

Read more about it in the FastAPI docs for Security.

Source code in .venv/lib/python3.12/site-packages/fastapi/security/oauth2.py
def __init__(
    self,
    *,
    flows: Annotated[
        Union[OAuthFlowsModel, Dict[str, Dict[str, Any]]],
        Doc(
            """
            The dictionary of OAuth2 flows.
            """
        ),
    ] = OAuthFlowsModel(),
    scheme_name: Annotated[
        Optional[str],
        Doc(
            """
            Security scheme name.

            It will be included in the generated OpenAPI (e.g. visible at `/docs`).
            """
        ),
    ] = None,
    description: Annotated[
        Optional[str],
        Doc(
            """
            Security scheme description.

            It will be included in the generated OpenAPI (e.g. visible at `/docs`).
            """
        ),
    ] = None,
    auto_error: Annotated[
        bool,
        Doc(
            """
            By default, if no HTTP Authorization header is provided, required for
            OAuth2 authentication, it will automatically cancel the request and
            send the client an error.

            If `auto_error` is set to `False`, when the HTTP Authorization header
            is not available, instead of erroring out, the dependency result will
            be `None`.

            This is useful when you want to have optional authentication.

            It is also useful when you want to have authentication that can be
            provided in one of multiple optional ways (for example, with OAuth2
            or in a cookie).
            """
        ),
    ] = True,
):
    self.model = OAuth2Model(
        flows=cast(OAuthFlowsModel, flows), description=description
    )
    self.scheme_name = scheme_name or self.__class__.__name__
    self.auto_error = auto_error

OAuth2AuthorizationCodeBearer

OAuth2AuthorizationCodeBearer(
    authorizationUrl: str,
    tokenUrl: Annotated[
        str,
        Doc(
            "\n                The URL to obtain the OAuth2 token.\n                "
        ),
    ],
    refreshUrl: Annotated[
        Optional[str],
        Doc(
            "\n                The URL to refresh the token and obtain a new one.\n                "
        ),
    ] = None,
    scheme_name: Annotated[
        Optional[str],
        Doc(
            "\n                Security scheme name.\n\n                It will be included in the generated OpenAPI (e.g. visible at `/docs`).\n                "
        ),
    ] = None,
    scopes: Annotated[
        Optional[Dict[str, str]],
        Doc(
            "\n                The OAuth2 scopes that would be required by the *path operations* that\n                use this dependency.\n                "
        ),
    ] = None,
    description: Annotated[
        Optional[str],
        Doc(
            "\n                Security scheme description.\n\n                It will be included in the generated OpenAPI (e.g. visible at `/docs`).\n                "
        ),
    ] = None,
    auto_error: Annotated[
        bool,
        Doc(
            "\n                By default, if no HTTP Auhtorization header is provided, required for\n                OAuth2 authentication, it will automatically cancel the request and\n                send the client an error.\n\n                If `auto_error` is set to `False`, when the HTTP Authorization header\n                is not available, instead of erroring out, the dependency result will\n                be `None`.\n\n                This is useful when you want to have optional authentication.\n\n                It is also useful when you want to have authentication that can be\n                provided in one of multiple optional ways (for example, with OAuth2\n                or in a cookie).\n                "
        ),
    ] = True,
)

Bases: OAuth2

OAuth2 flow for authentication using a bearer token obtained with an OAuth2 code flow. An instance of it would be used as a dependency.

Source code in .venv/lib/python3.12/site-packages/fastapi/security/oauth2.py
def __init__(
    self,
    authorizationUrl: str,
    tokenUrl: Annotated[
        str,
        Doc(
            """
            The URL to obtain the OAuth2 token.
            """
        ),
    ],
    refreshUrl: Annotated[
        Optional[str],
        Doc(
            """
            The URL to refresh the token and obtain a new one.
            """
        ),
    ] = None,
    scheme_name: Annotated[
        Optional[str],
        Doc(
            """
            Security scheme name.

            It will be included in the generated OpenAPI (e.g. visible at `/docs`).
            """
        ),
    ] = None,
    scopes: Annotated[
        Optional[Dict[str, str]],
        Doc(
            """
            The OAuth2 scopes that would be required by the *path operations* that
            use this dependency.
            """
        ),
    ] = None,
    description: Annotated[
        Optional[str],
        Doc(
            """
            Security scheme description.

            It will be included in the generated OpenAPI (e.g. visible at `/docs`).
            """
        ),
    ] = None,
    auto_error: Annotated[
        bool,
        Doc(
            """
            By default, if no HTTP Auhtorization header is provided, required for
            OAuth2 authentication, it will automatically cancel the request and
            send the client an error.

            If `auto_error` is set to `False`, when the HTTP Authorization header
            is not available, instead of erroring out, the dependency result will
            be `None`.

            This is useful when you want to have optional authentication.

            It is also useful when you want to have authentication that can be
            provided in one of multiple optional ways (for example, with OAuth2
            or in a cookie).
            """
        ),
    ] = True,
):
    if not scopes:
        scopes = {}
    flows = OAuthFlowsModel(
        authorizationCode=cast(
            Any,
            {
                "authorizationUrl": authorizationUrl,
                "tokenUrl": tokenUrl,
                "refreshUrl": refreshUrl,
                "scopes": scopes,
            },
        )
    )
    super().__init__(
        flows=flows,
        scheme_name=scheme_name,
        description=description,
        auto_error=auto_error,
    )

OAuth2PasswordBearer

OAuth2PasswordBearer(
    tokenUrl: Annotated[
        str,
        Doc(
            "\n                The URL to obtain the OAuth2 token. This would be the *path operation*\n                that has `OAuth2PasswordRequestForm` as a dependency.\n                "
        ),
    ],
    scheme_name: Annotated[
        Optional[str],
        Doc(
            "\n                Security scheme name.\n\n                It will be included in the generated OpenAPI (e.g. visible at `/docs`).\n                "
        ),
    ] = None,
    scopes: Annotated[
        Optional[Dict[str, str]],
        Doc(
            "\n                The OAuth2 scopes that would be required by the *path operations* that\n                use this dependency.\n                "
        ),
    ] = None,
    description: Annotated[
        Optional[str],
        Doc(
            "\n                Security scheme description.\n\n                It will be included in the generated OpenAPI (e.g. visible at `/docs`).\n                "
        ),
    ] = None,
    auto_error: Annotated[
        bool,
        Doc(
            "\n                By default, if no HTTP Auhtorization header is provided, required for\n                OAuth2 authentication, it will automatically cancel the request and\n                send the client an error.\n\n                If `auto_error` is set to `False`, when the HTTP Authorization header\n                is not available, instead of erroring out, the dependency result will\n                be `None`.\n\n                This is useful when you want to have optional authentication.\n\n                It is also useful when you want to have authentication that can be\n                provided in one of multiple optional ways (for example, with OAuth2\n                or in a cookie).\n                "
        ),
    ] = True,
)

Bases: OAuth2

OAuth2 flow for authentication using a bearer token obtained with a password. An instance of it would be used as a dependency.

Read more about it in the FastAPI docs for Simple OAuth2 with Password and Bearer.

Source code in .venv/lib/python3.12/site-packages/fastapi/security/oauth2.py
def __init__(
    self,
    tokenUrl: Annotated[
        str,
        Doc(
            """
            The URL to obtain the OAuth2 token. This would be the *path operation*
            that has `OAuth2PasswordRequestForm` as a dependency.
            """
        ),
    ],
    scheme_name: Annotated[
        Optional[str],
        Doc(
            """
            Security scheme name.

            It will be included in the generated OpenAPI (e.g. visible at `/docs`).
            """
        ),
    ] = None,
    scopes: Annotated[
        Optional[Dict[str, str]],
        Doc(
            """
            The OAuth2 scopes that would be required by the *path operations* that
            use this dependency.
            """
        ),
    ] = None,
    description: Annotated[
        Optional[str],
        Doc(
            """
            Security scheme description.

            It will be included in the generated OpenAPI (e.g. visible at `/docs`).
            """
        ),
    ] = None,
    auto_error: Annotated[
        bool,
        Doc(
            """
            By default, if no HTTP Auhtorization header is provided, required for
            OAuth2 authentication, it will automatically cancel the request and
            send the client an error.

            If `auto_error` is set to `False`, when the HTTP Authorization header
            is not available, instead of erroring out, the dependency result will
            be `None`.

            This is useful when you want to have optional authentication.

            It is also useful when you want to have authentication that can be
            provided in one of multiple optional ways (for example, with OAuth2
            or in a cookie).
            """
        ),
    ] = True,
):
    if not scopes:
        scopes = {}
    flows = OAuthFlowsModel(
        password=cast(Any, {"tokenUrl": tokenUrl, "scopes": scopes})
    )
    super().__init__(
        flows=flows,
        scheme_name=scheme_name,
        description=description,
        auto_error=auto_error,
    )

OAuth2PasswordRequestForm

OAuth2PasswordRequestForm(
    *,
    grant_type: Annotated[
        Union[str, None],
        Form(pattern=password),
        Doc(
            '\n                The OAuth2 spec says it is required and MUST be the fixed string\n                "password". Nevertheless, this dependency class is permissive and\n                allows not passing it. If you want to enforce it, use instead the\n                `OAuth2PasswordRequestFormStrict` dependency.\n                '
        ),
    ] = None,
    username: Annotated[
        str,
        Form(),
        Doc(
            "\n                `username` string. The OAuth2 spec requires the exact field name\n                `username`.\n                "
        ),
    ],
    password: Annotated[
        str,
        Form(),
        Doc(
            '\n                `password` string. The OAuth2 spec requires the exact field name\n                `password".\n                '
        ),
    ],
    scope: Annotated[
        str,
        Form(),
        Doc(
            '\n                A single string with actually several scopes separated by spaces. Each\n                scope is also a string.\n\n                For example, a single string with:\n\n                ```python\n                "items:read items:write users:read profile openid"\n                ````\n\n                would represent the scopes:\n\n                * `items:read`\n                * `items:write`\n                * `users:read`\n                * `profile`\n                * `openid`\n                '
        ),
    ] = "",
    client_id: Annotated[
        Union[str, None],
        Form(),
        Doc(
            "\n                If there's a `client_id`, it can be sent as part of the form fields.\n                But the OAuth2 specification recommends sending the `client_id` and\n                `client_secret` (if any) using HTTP Basic auth.\n                "
        ),
    ] = None,
    client_secret: Annotated[
        Union[str, None],
        Form(),
        Doc(
            "\n                If there's a `client_password` (and a `client_id`), they can be sent\n                as part of the form fields. But the OAuth2 specification recommends\n                sending the `client_id` and `client_secret` (if any) using HTTP Basic\n                auth.\n                "
        ),
    ] = None,
)

This is a dependency class to collect the username and password as form data for an OAuth2 password flow.

The OAuth2 specification dictates that for a password flow the data should be collected using form data (instead of JSON) and that it should have the specific fields username and password.

All the initialization parameters are extracted from the request.

Read more about it in the FastAPI docs for Simple OAuth2 with Password and Bearer.

Example
from typing import Annotated

from fastapi import Depends, FastAPI
from fastapi.security import OAuth2PasswordRequestForm

app = FastAPI()


@app.post("/login")
def login(form_data: Annotated[OAuth2PasswordRequestForm, Depends()]):
    data = {}
    data["scopes"] = []
    for scope in form_data.scopes:
        data["scopes"].append(scope)
    if form_data.client_id:
        data["client_id"] = form_data.client_id
    if form_data.client_secret:
        data["client_secret"] = form_data.client_secret
    return data

Note that for OAuth2 the scope items:read is a single scope in an opaque string. You could have custom internal logic to separate it by colon caracters (:) or similar, and get the two parts items and read. Many applications do that to group and organize permisions, you could do it as well in your application, just know that that it is application specific, it's not part of the specification.

Source code in .venv/lib/python3.12/site-packages/fastapi/security/oauth2.py
def __init__(
    self,
    *,
    grant_type: Annotated[
        Union[str, None],
        Form(pattern="password"),
        Doc(
            """
            The OAuth2 spec says it is required and MUST be the fixed string
            "password". Nevertheless, this dependency class is permissive and
            allows not passing it. If you want to enforce it, use instead the
            `OAuth2PasswordRequestFormStrict` dependency.
            """
        ),
    ] = None,
    username: Annotated[
        str,
        Form(),
        Doc(
            """
            `username` string. The OAuth2 spec requires the exact field name
            `username`.
            """
        ),
    ],
    password: Annotated[
        str,
        Form(),
        Doc(
            """
            `password` string. The OAuth2 spec requires the exact field name
            `password".
            """
        ),
    ],
    scope: Annotated[
        str,
        Form(),
        Doc(
            """
            A single string with actually several scopes separated by spaces. Each
            scope is also a string.

            For example, a single string with:

            ```python
            "items:read items:write users:read profile openid"
            ````

            would represent the scopes:

            * `items:read`
            * `items:write`
            * `users:read`
            * `profile`
            * `openid`
            """
        ),
    ] = "",
    client_id: Annotated[
        Union[str, None],
        Form(),
        Doc(
            """
            If there's a `client_id`, it can be sent as part of the form fields.
            But the OAuth2 specification recommends sending the `client_id` and
            `client_secret` (if any) using HTTP Basic auth.
            """
        ),
    ] = None,
    client_secret: Annotated[
        Union[str, None],
        Form(),
        Doc(
            """
            If there's a `client_password` (and a `client_id`), they can be sent
            as part of the form fields. But the OAuth2 specification recommends
            sending the `client_id` and `client_secret` (if any) using HTTP Basic
            auth.
            """
        ),
    ] = None,
):
    self.grant_type = grant_type
    self.username = username
    self.password = password
    self.scopes = scope.split()
    self.client_id = client_id
    self.client_secret = client_secret

OAuth2PasswordRequestFormStrict

OAuth2PasswordRequestFormStrict(
    grant_type: Annotated[
        str,
        Form(pattern=password),
        Doc(
            '\n                The OAuth2 spec says it is required and MUST be the fixed string\n                "password". This dependency is strict about it. If you want to be\n                permissive, use instead the `OAuth2PasswordRequestForm` dependency\n                class.\n                '
        ),
    ],
    username: Annotated[
        str,
        Form(),
        Doc(
            "\n                `username` string. The OAuth2 spec requires the exact field name\n                `username`.\n                "
        ),
    ],
    password: Annotated[
        str,
        Form(),
        Doc(
            '\n                `password` string. The OAuth2 spec requires the exact field name\n                `password".\n                '
        ),
    ],
    scope: Annotated[
        str,
        Form(),
        Doc(
            '\n                A single string with actually several scopes separated by spaces. Each\n                scope is also a string.\n\n                For example, a single string with:\n\n                ```python\n                "items:read items:write users:read profile openid"\n                ````\n\n                would represent the scopes:\n\n                * `items:read`\n                * `items:write`\n                * `users:read`\n                * `profile`\n                * `openid`\n                '
        ),
    ] = "",
    client_id: Annotated[
        Union[str, None],
        Form(),
        Doc(
            "\n                If there's a `client_id`, it can be sent as part of the form fields.\n                But the OAuth2 specification recommends sending the `client_id` and\n                `client_secret` (if any) using HTTP Basic auth.\n                "
        ),
    ] = None,
    client_secret: Annotated[
        Union[str, None],
        Form(),
        Doc(
            "\n                If there's a `client_password` (and a `client_id`), they can be sent\n                as part of the form fields. But the OAuth2 specification recommends\n                sending the `client_id` and `client_secret` (if any) using HTTP Basic\n                auth.\n                "
        ),
    ] = None,
)

Bases: OAuth2PasswordRequestForm

This is a dependency class to collect the username and password as form data for an OAuth2 password flow.

The OAuth2 specification dictates that for a password flow the data should be collected using form data (instead of JSON) and that it should have the specific fields username and password.

All the initialization parameters are extracted from the request.

The only difference between OAuth2PasswordRequestFormStrict and OAuth2PasswordRequestForm is that OAuth2PasswordRequestFormStrict requires the client to send the form field grant_type with the value "password", which is required in the OAuth2 specification (it seems that for no particular reason), while for OAuth2PasswordRequestForm grant_type is optional.

Read more about it in the FastAPI docs for Simple OAuth2 with Password and Bearer.

Example
from typing import Annotated

from fastapi import Depends, FastAPI
from fastapi.security import OAuth2PasswordRequestForm

app = FastAPI()


@app.post("/login")
def login(form_data: Annotated[OAuth2PasswordRequestFormStrict, Depends()]):
    data = {}
    data["scopes"] = []
    for scope in form_data.scopes:
        data["scopes"].append(scope)
    if form_data.client_id:
        data["client_id"] = form_data.client_id
    if form_data.client_secret:
        data["client_secret"] = form_data.client_secret
    return data

Note that for OAuth2 the scope items:read is a single scope in an opaque string. You could have custom internal logic to separate it by colon caracters (:) or similar, and get the two parts items and read. Many applications do that to group and organize permisions, you could do it as well in your application, just know that that it is application specific, it's not part of the specification.

the OAuth2 spec says it is required and MUST be the fixed string "password".

This dependency is strict about it. If you want to be permissive, use instead the OAuth2PasswordRequestForm dependency class.

username: username string. The OAuth2 spec requires the exact field name "username". password: password string. The OAuth2 spec requires the exact field name "password". scope: Optional string. Several scopes (each one a string) separated by spaces. E.g. "items:read items:write users:read profile openid" client_id: optional string. OAuth2 recommends sending the client_id and client_secret (if any) using HTTP Basic auth, as: client_id:client_secret client_secret: optional string. OAuth2 recommends sending the client_id and client_secret (if any) using HTTP Basic auth, as: client_id:client_secret

Source code in .venv/lib/python3.12/site-packages/fastapi/security/oauth2.py
def __init__(
    self,
    grant_type: Annotated[
        str,
        Form(pattern="password"),
        Doc(
            """
            The OAuth2 spec says it is required and MUST be the fixed string
            "password". This dependency is strict about it. If you want to be
            permissive, use instead the `OAuth2PasswordRequestForm` dependency
            class.
            """
        ),
    ],
    username: Annotated[
        str,
        Form(),
        Doc(
            """
            `username` string. The OAuth2 spec requires the exact field name
            `username`.
            """
        ),
    ],
    password: Annotated[
        str,
        Form(),
        Doc(
            """
            `password` string. The OAuth2 spec requires the exact field name
            `password".
            """
        ),
    ],
    scope: Annotated[
        str,
        Form(),
        Doc(
            """
            A single string with actually several scopes separated by spaces. Each
            scope is also a string.

            For example, a single string with:

            ```python
            "items:read items:write users:read profile openid"
            ````

            would represent the scopes:

            * `items:read`
            * `items:write`
            * `users:read`
            * `profile`
            * `openid`
            """
        ),
    ] = "",
    client_id: Annotated[
        Union[str, None],
        Form(),
        Doc(
            """
            If there's a `client_id`, it can be sent as part of the form fields.
            But the OAuth2 specification recommends sending the `client_id` and
            `client_secret` (if any) using HTTP Basic auth.
            """
        ),
    ] = None,
    client_secret: Annotated[
        Union[str, None],
        Form(),
        Doc(
            """
            If there's a `client_password` (and a `client_id`), they can be sent
            as part of the form fields. But the OAuth2 specification recommends
            sending the `client_id` and `client_secret` (if any) using HTTP Basic
            auth.
            """
        ),
    ] = None,
):
    super().__init__(
        grant_type=grant_type,
        username=username,
        password=password,
        scope=scope,
        client_id=client_id,
        client_secret=client_secret,
    )

OpenIdConnect

OpenIdConnect(
    *,
    openIdConnectUrl: Annotated[
        str,
        Doc(
            "\n            The OpenID Connect URL.\n            "
        ),
    ],
    scheme_name: Annotated[
        Optional[str],
        Doc(
            "\n                Security scheme name.\n\n                It will be included in the generated OpenAPI (e.g. visible at `/docs`).\n                "
        ),
    ] = None,
    description: Annotated[
        Optional[str],
        Doc(
            "\n                Security scheme description.\n\n                It will be included in the generated OpenAPI (e.g. visible at `/docs`).\n                "
        ),
    ] = None,
    auto_error: Annotated[
        bool,
        Doc(
            "\n                By default, if no HTTP Auhtorization header is provided, required for\n                OpenID Connect authentication, it will automatically cancel the request\n                and send the client an error.\n\n                If `auto_error` is set to `False`, when the HTTP Authorization header\n                is not available, instead of erroring out, the dependency result will\n                be `None`.\n\n                This is useful when you want to have optional authentication.\n\n                It is also useful when you want to have authentication that can be\n                provided in one of multiple optional ways (for example, with OpenID\n                Connect or in a cookie).\n                "
        ),
    ] = True,
)

Bases: SecurityBase

OpenID Connect authentication class. An instance of it would be used as a dependency.

Source code in .venv/lib/python3.12/site-packages/fastapi/security/open_id_connect_url.py
def __init__(
    self,
    *,
    openIdConnectUrl: Annotated[
        str,
        Doc(
            """
        The OpenID Connect URL.
        """
        ),
    ],
    scheme_name: Annotated[
        Optional[str],
        Doc(
            """
            Security scheme name.

            It will be included in the generated OpenAPI (e.g. visible at `/docs`).
            """
        ),
    ] = None,
    description: Annotated[
        Optional[str],
        Doc(
            """
            Security scheme description.

            It will be included in the generated OpenAPI (e.g. visible at `/docs`).
            """
        ),
    ] = None,
    auto_error: Annotated[
        bool,
        Doc(
            """
            By default, if no HTTP Auhtorization header is provided, required for
            OpenID Connect authentication, it will automatically cancel the request
            and send the client an error.

            If `auto_error` is set to `False`, when the HTTP Authorization header
            is not available, instead of erroring out, the dependency result will
            be `None`.

            This is useful when you want to have optional authentication.

            It is also useful when you want to have authentication that can be
            provided in one of multiple optional ways (for example, with OpenID
            Connect or in a cookie).
            """
        ),
    ] = True,
):
    self.model = OpenIdConnectModel(
        openIdConnectUrl=openIdConnectUrl, description=description
    )
    self.scheme_name = scheme_name or self.__class__.__name__
    self.auto_error = auto_error

SecurityScopes

SecurityScopes(
    scopes: Annotated[
        Optional[List[str]],
        Doc(
            "\n                This will be filled by FastAPI.\n                "
        ),
    ] = None,
)

This is a special class that you can define in a parameter in a dependency to obtain the OAuth2 scopes required by all the dependencies in the same chain.

This way, multiple dependencies can have different scopes, even when used in the same path operation. And with this, you can access all the scopes required in all those dependencies in a single place.

Read more about it in the FastAPI docs for OAuth2 scopes.

Source code in .venv/lib/python3.12/site-packages/fastapi/security/oauth2.py
def __init__(
    self,
    scopes: Annotated[
        Optional[List[str]],
        Doc(
            """
            This will be filled by FastAPI.
            """
        ),
    ] = None,
):
    self.scopes: Annotated[
        List[str],
        Doc(
            """
            The list of all the scopes required by dependencies.
            """
        ),
    ] = scopes or []
    self.scope_str: Annotated[
        str,
        Doc(
            """
            All the scopes required by all the dependencies in a single string
            separated by spaces, as defined in the OAuth2 specification.
            """
        ),
    ] = " ".join(self.scopes)