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
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
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
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:
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
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
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_fields_set
property
model_construct
classmethod
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 |
Source code in .venv/lib/python3.12/site-packages/pydantic/main.py
model_copy
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 |
False
|
Returns:
Type | Description |
---|---|
Model
|
New model instance. |
Source code in .venv/lib/python3.12/site-packages/pydantic/main.py
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 |
'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 |
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
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 |
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
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
|
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
model_parametrized_name
classmethod
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
|
required |
Returns:
Type | Description |
---|---|
str
|
String representing the new class where |
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
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
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
|
raise_errors
|
bool
|
Whether to raise errors, defaults to |
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
|
Returns:
Type | Description |
---|---|
bool | None
|
Returns |
bool | None
|
If rebuilding was required, returns |
Source code in .venv/lib/python3.12/site-packages/pydantic/main.py
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
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 |
Source code in .venv/lib/python3.12/site-packages/pydantic/main.py
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
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
1184 1185 1186 1187 1188 1189 1190 1191 1192 1193 1194 1195 1196 1197 1198 1199 1200 1201 1202 1203 1204 1205 1206 1207 1208 1209 1210 1211 1212 1213 1214 1215 1216 1217 1218 1219 1220 1221 1222 1223 1224 1225 1226 1227 1228 1229 1230 1231 1232 1233 1234 1235 1236 1237 1238 1239 1240 1241 1242 1243 1244 1245 1246 1247 1248 1249 1250 1251 1252 1253 1254 1255 1256 1257 1258 |
|
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
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
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
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_fields_set
property
model_construct
classmethod
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 |
Source code in .venv/lib/python3.12/site-packages/pydantic/main.py
model_copy
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 |
False
|
Returns:
Type | Description |
---|---|
Model
|
New model instance. |
Source code in .venv/lib/python3.12/site-packages/pydantic/main.py
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 |
'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 |
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
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 |
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
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
|
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
model_parametrized_name
classmethod
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
|
required |
Returns:
Type | Description |
---|---|
str
|
String representing the new class where |
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
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
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
|
raise_errors
|
bool
|
Whether to raise errors, defaults to |
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
|
Returns:
Type | Description |
---|---|
bool | None
|
Returns |
bool | None
|
If rebuilding was required, returns |
Source code in .venv/lib/python3.12/site-packages/pydantic/main.py
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
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 |
Source code in .venv/lib/python3.12/site-packages/pydantic/main.py
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
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
1184 1185 1186 1187 1188 1189 1190 1191 1192 1193 1194 1195 1196 1197 1198 1199 1200 1201 1202 1203 1204 1205 1206 1207 1208 1209 1210 1211 1212 1213 1214 1215 1216 1217 1218 1219 1220 1221 1222 1223 1224 1225 1226 1227 1228 1229 1230 1231 1232 1233 1234 1235 1236 1237 1238 1239 1240 1241 1242 1243 1244 1245 1246 1247 1248 1249 1250 1251 1252 1253 1254 1255 1256 1257 1258 |
|
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
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
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
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
494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 |
|
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
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
61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 |
|
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
216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 |
|
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
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.