FastAPI Contrib Documentation Overview
FastAPI Contrib Documentation Overview
Release 0.2.11
Lev Rubel
1 FastAPI Contrib 1
1.1 Features . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 1
1.2 Roadmap . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 1
1.3 Installation . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 2
1.4 Usage . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 2
1.5 Auto-creation of MongoDB indexes . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 6
1.6 Credits . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 7
2 Installation 9
2.1 Stable release . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 9
2.2 From sources . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 9
4 fastapi_contrib 17
4.1 fastapi_contrib package . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 17
5 Contributing 37
5.1 Types of Contributions . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 37
5.2 Get Started! . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 38
5.3 Pull Request Guidelines . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 39
5.4 Tips . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 39
5.5 Deploying . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 39
6 Credits 41
6.1 Development Lead . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 41
6.2 Contributors . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 41
Index 47
i
ii
CHAPTER
ONE
FASTAPI CONTRIB
1.1 Features
1.2 Roadmap
1
FastAPI Contrib Documentation, Release 0.2.11
1.3 Installation
To install everything:
1.4 Usage
app = FastAPI()
class SomeSerializer(ModelSerializer):
class Meta:
model = SomeModel
@[Link]("/")
async def list(pagination: Pagination = Depends()):
filter_kwargs = {}
return await [Link](
serializer_class=SomeSerializer, **filter_kwargs
)
Subclass this pagination to define custom default & maximum values for offset & limit:
class CustomPagination(Pagination):
default_offset = 90
(continues on next page)
app = FastAPI()
@app.on_event('startup')
async def startup():
app.add_middleware(StateRequestIDMiddleware)
app = FastAPI()
@app.on_event('startup')
async def startup():
app.add_middleware(AuthenticationMiddleware, backend=AuthBackend())
class TeapotUserAgentPermission(BasePermission):
app = FastAPI()
@[Link](
"/teapot/",
dependencies=[Depends(
PermissionsDependency([TeapotUserAgentPermission]))]
)
async def teapot() -> dict:
return {"teapot": True}
app = FastAPI()
(continues on next page)
1.4. Usage 3
FastAPI Contrib Documentation, Release 0.2.11
@app.on_event('startup')
async def startup():
setup_exception_handlers(app)
If you want to correctly handle scenario when request is an empty body (IMPORTANT: non-multipart):
app = FastAPI()
[Link].route_class = ValidationErrorLoggingRoute
Or if you use multiple routes for handling different namespaces (IMPORTANT: non-multipart):
app = FastAPI()
my_router = APIRouter(route_class=ValidationErrorLoggingRoute)
app = FastAPI()
@[Link]("/", response_class=UJSONResponse)
async def root():
return {"a": "b"}
Or specify it as default response class for the whole app (FastAPI >= 0.39.0):
app = FastAPI(default_response_class=UJSONResponse)
To setup Jaeger tracer and enable Middleware that captures every request in opentracing span:
app = FastAPI()
@app.on_event('startup')
async def startup():
setup_opentracing(app)
app.add_middleware(OpentracingMiddleware)
app = FastAPI()
@app.on_event('startup')
async def startup():
setup_mongodb(app)
class MyModel(MongoDBModel):
additional_field1: str
optional_field2: int = 42
class Meta:
collection = "mymodel_collection"
mymodel = MyModel(additional_field1="value")
[Link]()
class MyTimeStampedModel(MongoDBTimeStampedModel):
class Meta:
collection = "timestamped_collection"
mymodel = MyTimeStampedModel()
[Link]()
Use serializers and their response models to correctly show Schemas and convert from JSON/dict to models and back:
1.4. Usage 5
FastAPI Contrib Documentation, Release 0.2.11
class SomeModel(MongoDBModel):
field1: str
@[Link]
class SomeSerializer(Serializer):
read_only1: str = "const"
write_only2: int
not_visible: str = "42"
class Meta:
model = SomeModel
exclude = {"not_visible"}
write_only_fields = {"write_only2"}
read_only_fields = {"read_only1"}
@[Link]("/", response_model=SomeSerializer.response_model)
async def root(serializer: SomeSerializer):
model_instance = await [Link]()
return model_instance.dict()
-- project_root/
-- apps/
-- app1/
-- [Link] (with MongoDBModel inside with indices declared)
-- app2/
-- [Link] (with MongoDBModel inside with indices declared)
Based on this, your name of the folder with all the apps would be “apps”. This is the default name for
fastapi_contrib package to pick up your structure automatically. You can change that by setting ENV variable CON-
TRIB_APPS_FOLDER_NAME (by the way, all the setting of this package are overridable via ENV vars with CON-
TRIB_ prefix before them).
You also need to tell fastapi_contrib which apps to look into for your models. This is controlled by CONTRIB_APPS
ENV variable, which is list of str names of the apps with models. In the example above, this would be CON-
TRIB_APPS=[“app1”,”app2”].
app = FastAPI()
@app.on_event("startup")
async def startup():
setup_mongodb(app)
await create_indexes()
This will scan all the specified CONTRIB_APPS in the CONTRIB_APPS_FOLDER_NAME for models, that are sub-
classed from either MongoDBModel or MongoDBTimeStampedModel and create indices for any of them that has
Meta class with indexes attribute:
[Link]:
import pymongo
from fastapi_contrib.[Link] import MongoDBTimeStampedModel
class MyModel(MongoDBTimeStampedModel):
class Meta:
collection = "mymodel"
indexes = [
[Link](...),
[Link](...),
]
This would not create duplicate indices because it relies on pymongo and motor to do all the job.
1.6 Credits
This package was created with Cookiecutter and the audreyr/cookiecutter-pypackage project template.
1.6. Credits 7
FastAPI Contrib Documentation, Release 0.2.11
TWO
INSTALLATION
To install everything:
This is the preferred method to install FastAPI Contrib, as it will always install the most recent stable release.
If you don’t have pip installed, this Python installation guide can guide you through the process.
The sources for FastAPI Contrib can be downloaded from the Github repo.
You can either clone the public repository:
9
FastAPI Contrib Documentation, Release 0.2.11
Once you have a copy of the source, you can install it with:
$ python [Link] install
app = FastAPI()
class SomeSerializer(ModelSerializer):
class Meta:
model = SomeModel
@[Link]("/")
async def list(pagination: Pagination = Depends()):
filter_kwargs = {}
return await [Link](
serializer_class=SomeSerializer, **filter_kwargs
)
Subclass this pagination to define custom default & maximum values for offset & limit:
class CustomPagination(Pagination):
default_offset = 90
default_limit = 1
max_offset = 100
max_limit = 2000
app = FastAPI()
@app.on_event('startup')
async def startup():
app.add_middleware(StateRequestIDMiddleware)
app = FastAPI()
@app.on_event('startup')
(continues on next page)
10 Chapter 2. Installation
FastAPI Contrib Documentation, Release 0.2.11
class TeapotUserAgentPermission(BasePermission):
app = FastAPI()
@[Link](
"/teapot/",
dependencies=[Depends(
PermissionsDependency([TeapotUserAgentPermission]))]
)
async def teapot() -> dict:
return {"teapot": True}
app = FastAPI()
@app.on_event('startup')
async def startup():
setup_exception_handlers(app)
If you want to correctly handle scenario when request is an empty body (IMPORTANT: non-multipart):
app = FastAPI()
[Link].route_class = ValidationErrorLoggingRoute
Or if you use multiple routes for handling different namespaces (IMPORTANT: non-multipart):
app = FastAPI()
my_router = APIRouter(route_class=ValidationErrorLoggingRoute)
app = FastAPI()
@[Link]("/", response_class=UJSONResponse)
async def root():
return {"a": "b"}
Or specify it as default response class for the whole app (FastAPI >= 0.39.0):
app = FastAPI(default_response_class=UJSONResponse)
To setup Jaeger tracer and enable Middleware that captures every request in opentracing span:
app = FastAPI()
@app.on_event('startup')
async def startup():
setup_opentracing(app)
app.add_middleware(AuthenticationMiddleware)
app = FastAPI()
@app.on_event('startup')
async def startup():
setup_mongodb(app)
class MyModel(MongoDBModel):
additional_field1: str
optional_field2: int = 42
class Meta:
collection = "mymodel_collection"
mymodel = MyModel(additional_field1="value")
[Link]()
(continues on next page)
12 Chapter 2. Installation
FastAPI Contrib Documentation, Release 0.2.11
class MyTimeStampedModel(MongoDBTimeStampedModel):
class Meta:
collection = "timestamped_collection"
mymodel = MyTimeStampedModel()
[Link]()
Use serializers and their response models to correctly show Schemas and convert from JSON/dict to models and back:
app = FastAPI()
class SomeModel(MongoDBModel):
field1: str
@[Link]
class SomeSerializer(Serializer):
read_only1: str = "const"
write_only2: int
not_visible: str = "42"
class Meta:
model = SomeModel
exclude = {"not_visible"}
write_only_fields = {"write_only2"}
read_only_fields = {"read_only1"}
@[Link]("/", response_model=SomeSerializer.response_model)
async def root(serializer: SomeSerializer):
(continues on next page)
14 Chapter 2. Installation
CHAPTER
THREE
-- project_root/
-- apps/
-- app1/
-- [Link] (with MongoDBModel inside with indices declared)
-- app2/
-- [Link] (with MongoDBModel inside with indices declared)
Based on this, your name of the folder with all the apps would be “apps”. This is the default name for
fastapi_contrib package to pick up your structure automatically. You can change that by setting ENV variable CON-
TRIB_APPS_FOLDER_NAME (by the way, all the setting of this package are overridable via ENV vars with CON-
TRIB_ prefix before them).
You also need to tell fastapi_contrib which apps to look into for your models. This is controlled by CONTRIB_APPS
ENV variable, which is list of str names of the apps with models. In the example above, this would be CON-
TRIB_APPS=[“app1”,”app2”].
Just use create_indexes function after setting up mongodb:
app = FastAPI()
@app.on_event("startup")
async def startup():
setup_mongodb(app)
await create_indexes()
This will scan all the specified CONTRIB_APPS in the CONTRIB_APPS_FOLDER_NAME for models, that are sub-
classed from either MongoDBModel or MongoDBTimeStampedModel and create indices for any of them that has
Meta class with indexes attribute:
[Link]:
import pymongo
from fastapi_contrib.[Link] import MongoDBTimeStampedModel
class MyModel(MongoDBTimeStampedModel):
15
FastAPI Contrib Documentation, Release 0.2.11
This would not create duplicate indices because it relies on pymongo and motor to do all the job.
FOUR
FASTAPI_CONTRIB
4.1.1 Subpackages
fastapi_contrib.auth package
Submodules
fastapi_contrib.[Link] module
class fastapi_contrib.[Link]
Bases: [Link]
Own Auth Backend based on Starlette’s AuthenticationBackend.
Use instance of this class as backend argument to add_middleware func:
app = FastAPI()
@app.on_event('startup')
async def startup():
app.add_middleware(AuthenticationMiddleware, backend=AuthBackend())
17
FastAPI Contrib Documentation, Release 0.2.11
fastapi_contrib.[Link] module
class fastapi_contrib.[Link](app:
Callable[[MutableMapping[str,
Any], Callable[],
Awaitable[MutableMapping[str,
Any]]],
Callable[[MutableMapping[str,
Any]], Awaitable[None]]],
Awaitable[None]], backend:
star-
[Link],
on_error: Op-
tional[Callable[[[Link]
star-
[Link]],
[Link]]] =
None)
Bases: [Link]
Own Authentication Middleware based on Starlette’s default one.
Use instance of this class as a first argument to add_middleware func:
app = FastAPI()
@app.on_event('startup')
async def startup():
app.add_middleware(AuthenticationMiddleware, backend=AuthBackend())
fastapi_contrib.[Link] module
18 Chapter 4. fastapi_contrib
FastAPI Contrib Documentation, Release 0.2.11
fastapi_contrib.[Link] module
app = FastAPI()
@[Link](
"/user/",
dependencies=[Depends(PermissionsDependency([IsAuthenticated]))]
)
async def user(request: Request) -> dict:
return [Link]["user"].dict()
error_code = 401
error_msg = 'Not authenticated.'
has_required_permissions(request: [Link]) → bool
status_code = 401
fastapi_contrib.[Link] module
class fastapi_contrib.[Link]
Bases: fastapi_contrib.[Link]
Serializer for the default Token model. Use it if you use default model.
class Meta
Bases: object
exclude = {'user_id'}
model
alias of fastapi_contrib.[Link]
Module contents
fastapi_contrib.common package
Submodules
fastapi_contrib.[Link] module
class fastapi_contrib.[Link](app:
Callable[[MutableMapping[str,
Any], Callable[], Await-
able[MutableMapping[str,
Any]]],
Callable[[MutableMapping[str,
Any]], Awaitable[None]]],
Awaitable[None]], dispatch:
Op-
tional[Callable[[[Link],
Callable[[[Link]],
Await-
able[[Link]]]],
Await-
able[[Link]]]]
= None)
Bases: [Link]
Middleware to store Request ID headers value inside request’s state object.
Use this class as a first argument to add_middleware func:
app = FastAPI()
@app.on_event('startup')
async def startup():
app.add_middleware(StateRequestIDMiddleware)
20 Chapter 4. fastapi_contrib
FastAPI Contrib Documentation, Release 0.2.11
fastapi_contrib.[Link] module
app = FastAPI()
@[Link]("/", response_class=UJSONResponse)
async def root():
return {"a": "b"}
fastapi_contrib.[Link] module
fastapi_contrib.[Link].async_timing(func)
Decorator for logging timing of async functions. Used in this library internally for tracking DB functions per-
formance.
Parameters func – function to be decorated
Returns wrapped function
fastapi_contrib.[Link].get_current_app() → [Link]
Retrieves FastAPI app instance from the path, specified in project’s conf. :return: FastAPI app
fastapi_contrib.[Link].get_logger() → Any
Gets logger that will be used throughout this whole library. First it finds and imports the logger, then if it can be
configured using loguru-compatible config, it does so.
Returns desired logger (pre-configured if loguru)
fastapi_contrib.[Link].get_now() → [Link]
Retrieves now function from the path, specified in project’s conf. :return: datetime of “now”
fastapi_contrib.[Link].get_timezone()
Retrieves timezone name from settings and tries to create tzinfo from it. :return: tzinfo object
fastapi_contrib.[Link].resolve_dotted_path(path: str) → Any
Retrieves attribute (var, function, class, etc.) from module by dotted path
Module contents
fastapi_contrib.db package
Submodules
fastapi_contrib.[Link] module
class fastapi_contrib.[Link]
Bases: object
Singleton client for interacting with MongoDB. Operates mostly using models, specified when making DB
queries.
Implements only part of internal motor methods, but can be populated more
Please don’t use it directly, use fastapi_contrib.[Link].get_db_client.
async count(model: fastapi_contrib.[Link], session:
Optional[pymongo.client_session.ClientSession] = None, **kwargs) → int
async delete(model: fastapi_contrib.[Link], session:
Optional[pymongo.client_session.ClientSession] = None, **kwargs) →
[Link]
async get(model: fastapi_contrib.[Link], session:
Optional[pymongo.client_session.ClientSession] = None, **kwargs) → dict
get_collection(collection_name: str) → [Link]
async insert(model: fastapi_contrib.[Link], session:
Optional[pymongo.client_session.ClientSession] = None, include=None, exclude=None) →
[Link]
list(model: fastapi_contrib.[Link], session:
Optional[pymongo.client_session.ClientSession] = None, _offset: int = 0, _limit: int = 0, _sort:
Optional[list] = None, **kwargs) → [Link]
async update_many(model: fastapi_contrib.[Link], filter_kwargs: dict, session:
Optional[pymongo.client_session.ClientSession] = None, **kwargs) →
[Link]
async update_one(model: fastapi_contrib.[Link], filter_kwargs: dict, session:
Optional[pymongo.client_session.ClientSession] = None, **kwargs) →
[Link]
22 Chapter 4. fastapi_contrib
FastAPI Contrib Documentation, Release 0.2.11
fastapi_contrib.[Link] module
class MyModel(MongoDBModel):
additional_field1: str
optional_field2: int = 42
class Meta:
collection = "mymodel_collection"
mymodel = MyModel(additional_field1="value")
[Link]()
class Config
Bases: object
anystr_strip_whitespace = True
async classmethod count(**kwargs) → int
async classmethod create_indexes() → Optional[List[str]]
async classmethod delete(**kwargs) → [Link]
async classmethod get(**kwargs) → Optional[fastapi_contrib.[Link]]
classmethod get_db_collection() → str
id: int
async classmethod list(raw=True, _limit=0, _offset=0, _sort=None, **kwargs)
async save(include: set = None, exclude: set = None, rewrite_fields: dict = None) → int
classmethod set_id(v, values, **kwargs) → int
If id is supplied (ex. from DB) then use it, otherwise generate new.
async classmethod update_many(filter_kwargs: dict, **kwargs) → [Link]
async classmethod update_one(filter_kwargs: dict, **kwargs) → [Link]
class fastapi_contrib.[Link](*, id: int = None, created:
[Link] = None)
Bases: fastapi_contrib.[Link]
TimeStampedModel to use when you need to have created field, populated at your model creation time.
Use it as follows:
class MyTimeStampedModel(MongoDBTimeStampedModel):
mymodel = MyTimeStampedModel()
[Link]()
created: [Link]
classmethod set_created_now(v: [Link]) → [Link]
If created is supplied (ex. from DB) -> use it, otherwise generate new.
class fastapi_contrib.[Link]
Bases: object
fastapi_contrib.[Link] module
fastapi_contrib.[Link] module
app = FastAPI()
@app.on_event('startup')
async def startup():
setup_mongodb(app)
24 Chapter 4. fastapi_contrib
FastAPI Contrib Documentation, Release 0.2.11
Returns None
Module contents
fastapi_contrib.serializers package
Submodules
fastapi_contrib.[Link] module
class fastapi_contrib.[Link]
Bases: [Link]
exclude: set = {}
model: fastapi_contrib.[Link] = None
read_only_fields: set = {}
write_only_fields: set = {}
class fastapi_contrib.[Link]
Bases: fastapi_contrib.[Link]
Left as a proxy for correct naming until we figure out how to inherit all the specific to model-handling methods
and fields directly in here.
class fastapi_contrib.[Link]
Bases: [Link]
Base Serializer class.
Almost ALWAYS should be used in conjunction with fastapi_contrib.[Link] decorator to cor-
rectly handle inherited model fields and OpenAPI Schema generation with response_model.
Responsible for sanitizing data & converting JSON to & from MongoDBModel.
Contains supplemental function, related to MongoDBModel, mostly proxied to corresponding functions inside
model (ex. save, update)
Heavily uses Meta class for fine-tuning input & output. Main fields are:
• exclude - set of fields that are excluded when serializing to dict and sanitizing list of dicts
• model - class of the MongoDBModel to use, inherits fields from it
• write_only_fields - set of fields that can be accepted in request, but excluded when serializing to
dict
• read_only_fields - set of fields that cannot be accepted in request, but included when serializing
to dict
Example usage:
app = FastAPI()
class SomeModel(MongoDBModel):
field1: str
@[Link]
class SomeSerializer(Serializer):
read_only1: str = "const"
write_only2: int
not_visible: str = "42"
class Meta:
model = SomeModel
exclude = {"not_visible"}
write_only_fields = {"write_only2"}
read_only_fields = {"read_only1"}
@[Link]("/", response_model=SomeSerializer.response_model)
async def root(serializer: SomeSerializer):
model_instance = await [Link]()
return model_instance.dict()
class Meta
Bases: fastapi_contrib.[Link]
dict(*args, **kwargs) → dict
Removes excluded fields based on Meta and kwargs :return: dict of serializer data fields
classmethod sanitize_list(iterable: Iterable) → List[dict]
Sanitize list of rows that comes from DB to not include exclude set.
Parameters iterable – sequence of dicts with model fields (from rows in DB)
Returns list of cleaned, without excluded, dicts with model rows
async save(include: Optional[set] = None, exclude: Optional[set] = None, rewrite_fields: Optional[dict] =
None) → fastapi_contrib.[Link]
If we have model attribute in Meta, it populates model with data and saves it in DB, returning instance of
model.
Parameters
• rewrite_fields – dict of fields with values that override any other values for these fields
right before inserting into DB. This is useful when you need to set some value explicitly
based on request (e.g. user or token).
• include – fields to include from model in DB insert command
• exclude – fields to exclude from model in DB insert command
Returns model (MongoDBModel) that was saved
26 Chapter 4. fastapi_contrib
FastAPI Contrib Documentation, Release 0.2.11
fastapi_contrib.[Link] module
fastapi_contrib.[Link] module
class fastapi_contrib.[Link](value)
Bases: int, [Link]
Defines modes in which fields of decorated serializer should be generated.
REQUEST = 1
RESPONSE = 2
fastapi_contrib.[Link].gen_model(cls: Type, mode:
fastapi_contrib.[Link])
Generate [Link] based on fields in Serializer class, its Meta class and possible Model class.
Parameters
• cls – serializer class (could be modelserializer or regular one)
• mode – field generation mode
Returns newly generated BaseModel from fields in Model & Serializer
Module contents
fastapi_contrib.tracing package
Submodules
fastapi_contrib.[Link] module
class fastapi_contrib.[Link](app:
Callable[[MutableMapping[str,
Any], Callable[],
Awaitable[MutableMapping[str,
Any]]],
Callable[[MutableMapping[str,
Any]], Awaitable[None]]],
Awaitable[None]], dispatch: Op-
tional[Callable[[[Link],
Callable[[[Link]],
Await-
able[[Link]]]],
Await-
able[[Link]]]]
= None)
Bases: [Link]
static before_request(request: [Link], tracer)
Gather various info about the request and start new span with the data.
async dispatch(request: [Link], call_next: Any) → [Link]
Store span in some [Link] storage using Tracer.scope_manager, using the returned Scope as Context
Manager to ensure Span will be cleared and (in this case) [Link]() be called.
Parameters
• request – Starlette’s Request object
• call_next – Next callable Middleware in chain or final view
Returns Starlette’s Response object
fastapi_contrib.[Link] module
fastapi_contrib.[Link].setup_opentracing(app)
Helper function to setup opentracing with Jaeger client during setup. Use during app startup as follows:
app = FastAPI()
@app.on_event('startup')
async def startup():
setup_opentracing(app)
28 Chapter 4. fastapi_contrib
FastAPI Contrib Documentation, Release 0.2.11
Module contents
4.1.2 Submodules
• apps – List of app names. For now only needed to detect models inside them and generate
indexes upon startup (see: create_indexes)
• apps_folder_name – Name of the folders which contains dirs with apps.
class Config
Bases: object
env_prefix = 'CONTRIB_'
secrets_dir = None
TZ: str
apps: List[str]
apps_folder_name: str
debug_timing: bool
fastapi_app: str
jaeger_host: str
jaeger_port: int
jaeger_sampler_rate: float
jaeger_sampler_type: str
log_level: str
logger: str
mongodb_dbname: str
mongodb_dsn: str
mongodb_id_generator: str
mongodb_max_pool_size: int
mongodb_min_pool_size: int
now_function: str
request_id_header: str
service_name: str
token_generator: str
token_model: str
trace_id_header: str
user_model: str
30 Chapter 4. fastapi_contrib
FastAPI Contrib Documentation, Release 0.2.11
async fastapi_contrib.exception_handlers.http_exception_handler(request:
[Link], exc:
star-
[Link])
→
fastapi_contrib.[Link]
Parameters
• request – Starlette Request instance
• exc – StarletteHTTPException instance
Returns UJSONResponse with newly formatted error data
app = FastAPI()
@app.on_event('startup')
async def startup():
setup_exception_handlers(app)
Parameters
• request – Starlette Request instance
• exc – StarletteHTTPException instance
Returns UJSONResponse with newly formatted error data
32 Chapter 4. fastapi_contrib
FastAPI Contrib Documentation, Release 0.2.11
app = FastAPI()
class SomeSerializer(ModelSerializer):
class Meta:
model = SomeModel
@[Link]("/")
async def list(pagination: Pagination = Depends()):
filter_kwargs = {}
return await [Link](
serializer_class=SomeSerializer, **filter_kwargs
)
Subclass this pagination to define custom default & maximum values for offset & limit:
class CustomPagination(Pagination):
default_offset = 90
default_limit = 1
max_offset = 100`
max_limit = 2000
Parameters
• request – starlette Request object
• offset – query param of how many records to skip
• limit – query param of how many records to show
default_limit = 100
default_offset = 0
async get_count(**kwargs) → int
Retrieves counts for query list, filtered by kwargs.
Parameters kwargs – filters that are proxied in db query
Returns number of found records
async get_list(_sort=None, **kwargs) → list
Retrieves actual list of records. It comes raw, which means it retrieves dict from DB, instead of making
conversion for every object in list into Model.
Parameters
• serializer_class – needed to get Model & sanitize list from DB
• kwargs – filters that are proxied in db query
Returns dict that should be returned as a response
class TeapotUserAgentPermission(BasePermission):
error_code = 403
34 Chapter 4. fastapi_contrib
FastAPI Contrib Documentation, Release 0.2.11
error_msg = 'Forbidden.'
abstract has_required_permissions(request: [Link]) → bool
status_code = 403
class fastapi_contrib.[Link](permissions_classes: list)
Bases: object
Permission dependency that is used to define and check all the permission classes from one place inside route
definition.
Use it as an argument to FastAPI’s Depends as follows:
app = FastAPI()
@[Link](
"/teapot/",
dependencies=[Depends(
PermissionsDependency([TeapotUserAgentPermission]))]
)
async def teapot() -> dict:
return {"teapot": True}
36 Chapter 4. fastapi_contrib
CHAPTER
FIVE
CONTRIBUTING
Contributions are welcome, and they are greatly appreciated! Every little bit helps, and credit will always be given.
You can contribute in many ways:
Look through the GitHub issues for bugs. Anything tagged with “bug” and “help wanted” is open to whoever wants to
implement it.
Look through the GitHub issues for features. Anything tagged with “enhancement” and “help wanted” is open to
whoever wants to implement it.
FastAPI Contrib could always use more documentation, whether as part of the official FastAPI Contrib docs, in doc-
strings, or even on the web in blog posts, articles, and such.
37
FastAPI Contrib Documentation, Release 0.2.11
3. Install your local copy into a virtualenv. Assuming you have virtualenvwrapper installed, this is how you set up
your fork for local development:
$ mkvirtualenv fastapi_contrib
$ cd fastapi_contrib/
$ python [Link] develop
To get flake8 and tox, just pip install them into your virtualenv.
6. Commit your changes and push your branch to GitHub:
$ git add .
$ git commit -m "Your detailed description of your changes."
$ git push origin name-of-your-bugfix-or-feature
38 Chapter 5. Contributing
FastAPI Contrib Documentation, Release 0.2.11
Before you submit a pull request, check that it meets these guidelines:
1. The pull request should include tests.
2. If the pull request adds functionality, the docs should be updated. Put your new functionality into a function with
a docstring, and add the feature to the list in [Link].
3. The pull request should work for Python 3.7, 3.8, 3.9. Check [Link]
pull_requests and make sure that the tests pass for all supported Python versions.
5.4 Tips
$ [Link] tests.test_fastapi_contrib
5.5 Deploying
A reminder for the maintainers on how to deploy. Make sure all your changes are committed. Then run:
40 Chapter 5. Contributing
CHAPTER
SIX
CREDITS
6.2 Contributors
• @yarara
• @BumagniyPacket
• @aCLr
• @rsommerard
• @mumtozvalijonov
• @danield137
• @Haider8
41
FastAPI Contrib Documentation, Release 0.2.11
42 Chapter 6. Credits
CHAPTER
SEVEN
• genindex
• modindex
• search
43
FastAPI Contrib Documentation, Release 0.2.11
f
fastapi_contrib, 36
fastapi_contrib.auth, 20
fastapi_contrib.[Link], 17
fastapi_contrib.[Link], 18
fastapi_contrib.[Link], 18
fastapi_contrib.[Link], 19
fastapi_contrib.[Link], 20
fastapi_contrib.common, 22
fastapi_contrib.[Link], 20
fastapi_contrib.[Link], 21
fastapi_contrib.[Link], 21
fastapi_contrib.conf, 29
fastapi_contrib.db, 25
fastapi_contrib.[Link], 22
fastapi_contrib.[Link], 23
fastapi_contrib.[Link], 24
fastapi_contrib.exception_handlers, 31
fastapi_contrib.exceptions, 32
fastapi_contrib.pagination, 33
fastapi_contrib.permissions, 34
fastapi_contrib.routes, 36
fastapi_contrib.serializers, 27
fastapi_contrib.[Link], 25
fastapi_contrib.[Link], 27
fastapi_contrib.[Link], 27
fastapi_contrib.tracing, 29
fastapi_contrib.[Link], 28
fastapi_contrib.[Link], 28
45
FastAPI Contrib Documentation, Release 0.2.11
A D
AbstractMeta (class in debug_timing (fastapi_contrib.[Link] attribute),
fastapi_contrib.[Link]), 25 30
anystr_strip_whitespace default_id_generator() (in module
(fastapi_contrib.[Link] fastapi_contrib.[Link]), 24
attribute), 23 default_limit (fastapi_contrib.[Link]
apps (fastapi_contrib.[Link] attribute), 30 attribute), 33
apps_folder_name (fastapi_contrib.[Link] default_offset (fastapi_contrib.[Link]
attribute), 30 attribute), 33
async_timing() (in module default_on_error() (fastapi_contrib.[Link]
fastapi_contrib.[Link]), 21 static method), 18
AuthBackend (class in fastapi_contrib.[Link]), delete() (fastapi_contrib.[Link]
17 method), 22
authenticate() (fastapi_contrib.[Link] delete() (fastapi_contrib.[Link]
method), 17 class method), 23
AuthenticationMiddleware (class in dict() (fastapi_contrib.[Link]
fastapi_contrib.[Link]), 18 method), 26
dispatch() (fastapi_contrib.[Link]
B method), 20
BadRequestError, 32 dispatch() (fastapi_contrib.[Link]
BasePermission (class in fastapi_contrib.permissions), method), 28
34
E
before_request() (fastapi_contrib.[Link]
static method), 28 env_prefix (fastapi_contrib.[Link]
attribute), 30
C error_code (fastapi_contrib.[Link]
collection (fastapi_contrib.[Link] attribute), 19
attribute), 19 error_code (fastapi_contrib.[Link]
collection (fastapi_contrib.[Link] at- attribute), 34
tribute), 19 error_msg (fastapi_contrib.[Link]
count() (fastapi_contrib.[Link] attribute), 19
method), 22 error_msg (fastapi_contrib.[Link]
count() (fastapi_contrib.[Link] attribute), 34
class method), 23 exclude (fastapi_contrib.[Link]
create_indexes() (fastapi_contrib.[Link] attribute), 20
class method), 23 exclude (fastapi_contrib.[Link]
create_indexes() (in module fastapi_contrib.[Link]), attribute), 25
24 expires (fastapi_contrib.[Link] attribute),
created (fastapi_contrib.[Link] 19
attribute), 24
F
fastapi_app (fastapi_contrib.[Link] attribute),
47
FastAPI Contrib Documentation, Release 0.2.11
30 module, 28
fastapi_contrib fastapi_contrib.[Link]
module, 36 module, 28
fastapi_contrib.auth FieldGenerationMode (class in
module, 20 fastapi_contrib.[Link]), 27
fastapi_contrib.[Link] ForbiddenError, 32
module, 17
fastapi_contrib.[Link] G
module, 18 gen_model() (in module
fastapi_contrib.[Link] fastapi_contrib.[Link]), 27
module, 18 get() (fastapi_contrib.[Link]
fastapi_contrib.[Link] method), 22
module, 19 get() (fastapi_contrib.[Link] class
fastapi_contrib.[Link] method), 23
module, 20 get_collection() (fastapi_contrib.[Link]
fastapi_contrib.common method), 22
module, 22 get_count() (fastapi_contrib.[Link]
fastapi_contrib.[Link] method), 33
module, 20 get_current_app() (in module
fastapi_contrib.[Link] fastapi_contrib.[Link]), 21
module, 21 get_db_client() (in module fastapi_contrib.[Link]),
fastapi_contrib.[Link] 24
module, 21 get_db_collection()
fastapi_contrib.conf (fastapi_contrib.[Link]
module, 29 class method), 23
fastapi_contrib.db get_list() (fastapi_contrib.[Link]
module, 25 method), 33
fastapi_contrib.[Link] get_logger() (in module
module, 22 fastapi_contrib.[Link]), 21
fastapi_contrib.[Link] get_models() (in module fastapi_contrib.[Link]), 24
module, 23 get_next_id() (in module fastapi_contrib.[Link]), 24
fastapi_contrib.[Link] get_next_url() (fastapi_contrib.[Link]
module, 24 method), 34
fastapi_contrib.exception_handlers get_now() (in module fastapi_contrib.[Link]), 21
module, 31 get_previous_url() (fastapi_contrib.[Link]
fastapi_contrib.exceptions method), 34
module, 32 get_route_handler()
fastapi_contrib.pagination (fastapi_contrib.[Link]
module, 33 method), 36
fastapi_contrib.permissions get_timezone() (in module
module, 34 fastapi_contrib.[Link]), 21
fastapi_contrib.routes
module, 36 H
fastapi_contrib.serializers has_required_permissions()
module, 27 (fastapi_contrib.[Link]
fastapi_contrib.[Link] method), 19
module, 25 has_required_permissions()
fastapi_contrib.[Link] (fastapi_contrib.[Link]
module, 27 method), 35
fastapi_contrib.[Link] http_exception_handler() (in module
module, 27 fastapi_contrib.exception_handlers), 31
fastapi_contrib.tracing HTTPException, 32
module, 29
fastapi_contrib.[Link]
48 Index
FastAPI Contrib Documentation, Release 0.2.11
I fastapi_contrib.[Link], 19
id (fastapi_contrib.[Link] at- fastapi_contrib.[Link], 20
tribute), 23 fastapi_contrib.common, 22
indexes (fastapi_contrib.[Link] fastapi_contrib.[Link], 20
attribute), 19 fastapi_contrib.[Link], 21
insert() (fastapi_contrib.[Link] fastapi_contrib.[Link], 21
method), 22 fastapi_contrib.conf, 29
internal_server_error_handler() (in module fastapi_contrib.db, 25
fastapi_contrib.exception_handlers), 31 fastapi_contrib.[Link], 22
InternalServerError, 32 fastapi_contrib.[Link], 23
is_active (fastapi_contrib.[Link] at- fastapi_contrib.[Link], 24
tribute), 19 fastapi_contrib.exception_handlers, 31
IsAuthenticated (class in fastapi_contrib.exceptions, 32
fastapi_contrib.[Link]), 19 fastapi_contrib.pagination, 33
fastapi_contrib.permissions, 34
J fastapi_contrib.routes, 36
fastapi_contrib.serializers, 27
jaeger_host (fastapi_contrib.[Link] attribute),
fastapi_contrib.[Link], 25
30
fastapi_contrib.[Link], 27
jaeger_port (fastapi_contrib.[Link] attribute),
fastapi_contrib.[Link], 27
30
fastapi_contrib.tracing, 29
jaeger_sampler_rate (fastapi_contrib.[Link]
fastapi_contrib.[Link], 28
attribute), 30
fastapi_contrib.[Link], 28
jaeger_sampler_type (fastapi_contrib.[Link]
mongodb_dbname (fastapi_contrib.[Link] at-
attribute), 30
tribute), 30
mongodb_dsn (fastapi_contrib.[Link] attribute),
K 30
key (fastapi_contrib.[Link] attribute), 19 mongodb_id_generator (fastapi_contrib.[Link]
attribute), 30
L mongodb_max_pool_size (fastapi_contrib.[Link]
list() (fastapi_contrib.[Link] attribute), 30
method), 22 mongodb_min_pool_size (fastapi_contrib.[Link]
list() (fastapi_contrib.[Link] attribute), 30
class method), 23 MongoDBClient (class in fastapi_contrib.[Link]), 22
log_level (fastapi_contrib.[Link] attribute), 30 MongoDBModel (class in fastapi_contrib.[Link]), 23
logger (fastapi_contrib.[Link] attribute), 30 [Link] (class in
fastapi_contrib.[Link]), 23
M MongoDBTimeStampedModel (class in
max_limit (fastapi_contrib.[Link] at- fastapi_contrib.[Link]), 23
tribute), 34
max_offset (fastapi_contrib.[Link] at- N
tribute), 34 not_found_error_handler() (in module
model (fastapi_contrib.[Link] fastapi_contrib.exception_handlers), 31
attribute), 20 NotFoundError, 32
model (fastapi_contrib.[Link] NotSet (class in fastapi_contrib.[Link]), 24
attribute), 25 now_function (fastapi_contrib.[Link] attribute),
ModelSerializer (class in 30
fastapi_contrib.[Link]), 25
module O
fastapi_contrib, 36 OpentracingMiddleware (class in
fastapi_contrib.auth, 20 fastapi_contrib.[Link]), 28
fastapi_contrib.[Link], 17
fastapi_contrib.[Link], 18 P
fastapi_contrib.[Link], 18 paginate() (fastapi_contrib.[Link]
Index 49
FastAPI Contrib Documentation, Release 0.2.11
50 Index
FastAPI Contrib Documentation, Release 0.2.11
fastapi_contrib.exception_handlers), 32
ValidationErrorLoggingRoute (class in
fastapi_contrib.routes), 36
W
write_only_fields (fastapi_contrib.[Link]
attribute), 25
Index 51









