FASTAPI
FASTAPI
FASTAPI
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
@app.get("/")
async def list(pagination: Pagination = Depends()):
filter_kwargs = {}
return await pagination.paginate(
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()
@app.get(
"/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()
app.router.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()
@app.get("/", 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")
mymodel.save()
class MyTimeStampedModel(MongoDBTimeStampedModel):
class Meta:
collection = "timestamped_collection"
mymodel = MyTimeStampedModel()
mymodel.save()
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
@openapi.patch
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"}
@app.get("/", response_model=SomeSerializer.response_model)
async def root(serializer: SomeSerializer):
model_instance = await serializer.save()
return model_instance.dict()
-- project_root/
-- apps/
-- app1/
-- models.py (with MongoDBModel inside with indices declared)
-- app2/
-- models.py (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:
models.py:
import pymongo
from fastapi_contrib.db.models import MongoDBTimeStampedModel
class MyModel(MongoDBTimeStampedModel):
class Meta:
collection = "mymodel"
indexes = [
pymongo.IndexModel(...),
pymongo.IndexModel(...),
]
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 setup.py install
app = FastAPI()
class SomeSerializer(ModelSerializer):
class Meta:
model = SomeModel
@app.get("/")
async def list(pagination: Pagination = Depends()):
filter_kwargs = {}
return await pagination.paginate(
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()
@app.get(
"/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()
app.router.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()
@app.get("/", 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")
mymodel.save()
(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()
mymodel.save()
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
@openapi.patch
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"}
@app.get("/", response_model=SomeSerializer.response_model)
async def root(serializer: SomeSerializer):
(continues on next page)
14 Chapter 2. Installation
CHAPTER
THREE
-- project_root/
-- apps/
-- app1/
-- models.py (with MongoDBModel inside with indices declared)
-- app2/
-- models.py (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:
models.py:
import pymongo
from fastapi_contrib.db.models 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.auth.backends module
class fastapi_contrib.auth.backends.AuthBackend
Bases: starlette.authentication.AuthenticationBackend
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.auth.middlewares module
class fastapi_contrib.auth.middlewares.AuthenticationMiddleware(app:
Callable[[MutableMapping[str,
Any], Callable[],
Awaitable[MutableMapping[str,
Any]]],
Callable[[MutableMapping[str,
Any]], Awaitable[None]]],
Awaitable[None]], backend:
star-
lette.authentication.AuthenticationBackend,
on_error: Op-
tional[Callable[[starlette.requests.HTTPConnection
star-
lette.authentication.AuthenticationError],
starlette.responses.Response]] =
None)
Bases: starlette.middleware.authentication.AuthenticationMiddleware
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.auth.models module
18 Chapter 4. fastapi_contrib
FastAPI Contrib Documentation, Release 0.2.11
fastapi_contrib.auth.permissions module
app = FastAPI()
@app.get(
"/user/",
dependencies=[Depends(PermissionsDependency([IsAuthenticated]))]
)
async def user(request: Request) -> dict:
return request.scope["user"].dict()
error_code = 401
error_msg = 'Not authenticated.'
has_required_permissions(request: starlette.requests.Request) → bool
status_code = 401
fastapi_contrib.auth.serializers module
class fastapi_contrib.auth.serializers.TokenSerializer
Bases: fastapi_contrib.serializers.common.ModelSerializer
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.auth.models.Token
Module contents
fastapi_contrib.common package
Submodules
fastapi_contrib.common.middlewares module
class fastapi_contrib.common.middlewares.StateRequestIDMiddleware(app:
Callable[[MutableMapping[str,
Any], Callable[], Await-
able[MutableMapping[str,
Any]]],
Callable[[MutableMapping[str,
Any]], Awaitable[None]]],
Awaitable[None]], dispatch:
Op-
tional[Callable[[starlette.requests.Request,
Callable[[starlette.requests.Request],
Await-
able[starlette.responses.Response]]],
Await-
able[starlette.responses.Response]]]
= None)
Bases: starlette.middleware.base.BaseHTTPMiddleware
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.common.responses module
app = FastAPI()
@app.get("/", response_class=UJSONResponse)
async def root():
return {"a": "b"}
fastapi_contrib.common.utils module
fastapi_contrib.common.utils.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.common.utils.get_current_app() → fastapi.applications.FastAPI
Retrieves FastAPI app instance from the path, specified in project’s conf. :return: FastAPI app
fastapi_contrib.common.utils.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.common.utils.get_now() → datetime.datetime
Retrieves now function from the path, specified in project’s conf. :return: datetime of “now”
fastapi_contrib.common.utils.get_timezone()
Retrieves timezone name from settings and tries to create tzinfo from it. :return: tzinfo object
fastapi_contrib.common.utils.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.db.client module
class fastapi_contrib.db.client.MongoDBClient
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.db.utils.get_db_client.
async count(model: fastapi_contrib.db.models.MongoDBModel, session:
Optional[pymongo.client_session.ClientSession] = None, **kwargs) → int
async delete(model: fastapi_contrib.db.models.MongoDBModel, session:
Optional[pymongo.client_session.ClientSession] = None, **kwargs) →
pymongo.results.DeleteResult
async get(model: fastapi_contrib.db.models.MongoDBModel, session:
Optional[pymongo.client_session.ClientSession] = None, **kwargs) → dict
get_collection(collection_name: str) → pymongo.collection.Collection
async insert(model: fastapi_contrib.db.models.MongoDBModel, session:
Optional[pymongo.client_session.ClientSession] = None, include=None, exclude=None) →
pymongo.results.InsertOneResult
list(model: fastapi_contrib.db.models.MongoDBModel, session:
Optional[pymongo.client_session.ClientSession] = None, _offset: int = 0, _limit: int = 0, _sort:
Optional[list] = None, **kwargs) → pymongo.cursor.Cursor
async update_many(model: fastapi_contrib.db.models.MongoDBModel, filter_kwargs: dict, session:
Optional[pymongo.client_session.ClientSession] = None, **kwargs) →
pymongo.results.UpdateResult
async update_one(model: fastapi_contrib.db.models.MongoDBModel, filter_kwargs: dict, session:
Optional[pymongo.client_session.ClientSession] = None, **kwargs) →
pymongo.results.UpdateResult
22 Chapter 4. fastapi_contrib
FastAPI Contrib Documentation, Release 0.2.11
fastapi_contrib.db.models module
class MyModel(MongoDBModel):
additional_field1: str
optional_field2: int = 42
class Meta:
collection = "mymodel_collection"
mymodel = MyModel(additional_field1="value")
mymodel.save()
class Config
Bases: object
anystr_strip_whitespace = True
async classmethod count(**kwargs) → int
async classmethod create_indexes() → Optional[List[str]]
async classmethod delete(**kwargs) → pymongo.results.DeleteResult
async classmethod get(**kwargs) → Optional[fastapi_contrib.db.models.MongoDBModel]
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) → pymongo.results.UpdateResult
async classmethod update_one(filter_kwargs: dict, **kwargs) → pymongo.results.UpdateResult
class fastapi_contrib.db.models.MongoDBTimeStampedModel(*, id: int = None, created:
datetime.datetime = None)
Bases: fastapi_contrib.db.models.MongoDBModel
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()
mymodel.save()
created: datetime.datetime
classmethod set_created_now(v: datetime.datetime) → datetime.datetime
If created is supplied (ex. from DB) -> use it, otherwise generate new.
class fastapi_contrib.db.models.NotSet
Bases: object
fastapi_contrib.db.serializers module
fastapi_contrib.db.utils 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.serializers.common module
class fastapi_contrib.serializers.common.AbstractMeta
Bases: abc.ABC
exclude: set = {}
model: fastapi_contrib.db.models.MongoDBModel = None
read_only_fields: set = {}
write_only_fields: set = {}
class fastapi_contrib.serializers.common.ModelSerializer
Bases: fastapi_contrib.serializers.common.Serializer
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.serializers.common.Serializer
Bases: pydantic.main.BaseModel
Base Serializer class.
Almost ALWAYS should be used in conjunction with fastapi_contrib.serializers.openapi.patch 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
@openapi.patch
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"}
@app.get("/", response_model=SomeSerializer.response_model)
async def root(serializer: SomeSerializer):
model_instance = await serializer.save()
return model_instance.dict()
class Meta
Bases: fastapi_contrib.serializers.common.AbstractMeta
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.db.models.MongoDBModel
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.serializers.openapi module
fastapi_contrib.serializers.utils module
class fastapi_contrib.serializers.utils.FieldGenerationMode(value)
Bases: int, enum.Enum
Defines modes in which fields of decorated serializer should be generated.
REQUEST = 1
RESPONSE = 2
fastapi_contrib.serializers.utils.gen_model(cls: Type, mode:
fastapi_contrib.serializers.utils.FieldGenerationMode)
Generate pydantic.BaseModel 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.tracing.middlewares module
class fastapi_contrib.tracing.middlewares.OpentracingMiddleware(app:
Callable[[MutableMapping[str,
Any], Callable[],
Awaitable[MutableMapping[str,
Any]]],
Callable[[MutableMapping[str,
Any]], Awaitable[None]]],
Awaitable[None]], dispatch: Op-
tional[Callable[[starlette.requests.Request,
Callable[[starlette.requests.Request],
Await-
able[starlette.responses.Response]]],
Await-
able[starlette.responses.Response]]]
= None)
Bases: starlette.middleware.base.BaseHTTPMiddleware
static before_request(request: starlette.requests.Request, tracer)
Gather various info about the request and start new span with the data.
async dispatch(request: starlette.requests.Request, call_next: Any) → starlette.responses.Response
Store span in some request.state storage using Tracer.scope_manager, using the returned Scope as Context
Manager to ensure Span will be cleared and (in this case) Span.finish() 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.tracing.utils module
fastapi_contrib.tracing.utils.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:
starlette.requests.Request, exc:
star-
lette.exceptions.HTTPException)
→
fastapi_contrib.common.responses.UJSONResponse
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
@app.get("/")
async def list(pagination: Pagination = Depends()):
filter_kwargs = {}
return await pagination.paginate(
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: starlette.requests.Request) → bool
status_code = 403
class fastapi_contrib.permissions.PermissionsDependency(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()
@app.get(
"/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 setup.py 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 README.rst.
3. The pull request should work for Python 3.7, 3.8, 3.9. Check https://travis-ci.org/identixone/fastapi_contrib/
pull_requests and make sure that the tests pass for all supported Python versions.
5.4 Tips
$ py.test 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.auth.backends, 17
fastapi_contrib.auth.middlewares, 18
fastapi_contrib.auth.models, 18
fastapi_contrib.auth.permissions, 19
fastapi_contrib.auth.serializers, 20
fastapi_contrib.common, 22
fastapi_contrib.common.middlewares, 20
fastapi_contrib.common.responses, 21
fastapi_contrib.common.utils, 21
fastapi_contrib.conf, 29
fastapi_contrib.db, 25
fastapi_contrib.db.client, 22
fastapi_contrib.db.models, 23
fastapi_contrib.db.utils, 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.serializers.common, 25
fastapi_contrib.serializers.openapi, 27
fastapi_contrib.serializers.utils, 27
fastapi_contrib.tracing, 29
fastapi_contrib.tracing.middlewares, 28
fastapi_contrib.tracing.utils, 28
45
FastAPI Contrib Documentation, Release 0.2.11
A D
AbstractMeta (class in debug_timing (fastapi_contrib.conf.Settings attribute),
fastapi_contrib.serializers.common), 25 30
anystr_strip_whitespace default_id_generator() (in module
(fastapi_contrib.db.models.MongoDBModel.Config fastapi_contrib.db.utils), 24
attribute), 23 default_limit (fastapi_contrib.pagination.Pagination
apps (fastapi_contrib.conf.Settings attribute), 30 attribute), 33
apps_folder_name (fastapi_contrib.conf.Settings default_offset (fastapi_contrib.pagination.Pagination
attribute), 30 attribute), 33
async_timing() (in module default_on_error() (fastapi_contrib.auth.middlewares.AuthenticationM
fastapi_contrib.common.utils), 21 static method), 18
AuthBackend (class in fastapi_contrib.auth.backends), delete() (fastapi_contrib.db.client.MongoDBClient
17 method), 22
authenticate() (fastapi_contrib.auth.backends.AuthBackend delete() (fastapi_contrib.db.models.MongoDBModel
method), 17 class method), 23
AuthenticationMiddleware (class in dict() (fastapi_contrib.serializers.common.Serializer
fastapi_contrib.auth.middlewares), 18 method), 26
dispatch() (fastapi_contrib.common.middlewares.StateRequestIDMiddlew
B method), 20
BadRequestError, 32 dispatch() (fastapi_contrib.tracing.middlewares.OpentracingMiddleware
BasePermission (class in fastapi_contrib.permissions), method), 28
34
E
before_request() (fastapi_contrib.tracing.middlewares.OpentracingMiddleware
static method), 28 env_prefix (fastapi_contrib.conf.Settings.Config
attribute), 30
C error_code (fastapi_contrib.auth.permissions.IsAuthenticated
collection (fastapi_contrib.auth.models.Token.Meta attribute), 19
attribute), 19 error_code (fastapi_contrib.permissions.BasePermission
collection (fastapi_contrib.auth.models.User.Meta at- attribute), 34
tribute), 19 error_msg (fastapi_contrib.auth.permissions.IsAuthenticated
count() (fastapi_contrib.db.client.MongoDBClient attribute), 19
method), 22 error_msg (fastapi_contrib.permissions.BasePermission
count() (fastapi_contrib.db.models.MongoDBModel attribute), 34
class method), 23 exclude (fastapi_contrib.auth.serializers.TokenSerializer.Meta
create_indexes() (fastapi_contrib.db.models.MongoDBModel attribute), 20
class method), 23 exclude (fastapi_contrib.serializers.common.AbstractMeta
create_indexes() (in module fastapi_contrib.db.utils), attribute), 25
24 expires (fastapi_contrib.auth.models.Token attribute),
created (fastapi_contrib.db.models.MongoDBTimeStampedModel 19
attribute), 24
F
fastapi_app (fastapi_contrib.conf.Settings attribute),
47
FastAPI Contrib Documentation, Release 0.2.11
30 module, 28
fastapi_contrib fastapi_contrib.tracing.utils
module, 36 module, 28
fastapi_contrib.auth FieldGenerationMode (class in
module, 20 fastapi_contrib.serializers.utils), 27
fastapi_contrib.auth.backends ForbiddenError, 32
module, 17
fastapi_contrib.auth.middlewares G
module, 18 gen_model() (in module
fastapi_contrib.auth.models fastapi_contrib.serializers.utils), 27
module, 18 get() (fastapi_contrib.db.client.MongoDBClient
fastapi_contrib.auth.permissions method), 22
module, 19 get() (fastapi_contrib.db.models.MongoDBModel class
fastapi_contrib.auth.serializers method), 23
module, 20 get_collection() (fastapi_contrib.db.client.MongoDBClient
fastapi_contrib.common method), 22
module, 22 get_count() (fastapi_contrib.pagination.Pagination
fastapi_contrib.common.middlewares method), 33
module, 20 get_current_app() (in module
fastapi_contrib.common.responses fastapi_contrib.common.utils), 21
module, 21 get_db_client() (in module fastapi_contrib.db.utils),
fastapi_contrib.common.utils 24
module, 21 get_db_collection()
fastapi_contrib.conf (fastapi_contrib.db.models.MongoDBModel
module, 29 class method), 23
fastapi_contrib.db get_list() (fastapi_contrib.pagination.Pagination
module, 25 method), 33
fastapi_contrib.db.client get_logger() (in module
module, 22 fastapi_contrib.common.utils), 21
fastapi_contrib.db.models get_models() (in module fastapi_contrib.db.utils), 24
module, 23 get_next_id() (in module fastapi_contrib.db.utils), 24
fastapi_contrib.db.utils get_next_url() (fastapi_contrib.pagination.Pagination
module, 24 method), 34
fastapi_contrib.exception_handlers get_now() (in module fastapi_contrib.common.utils), 21
module, 31 get_previous_url() (fastapi_contrib.pagination.Pagination
fastapi_contrib.exceptions method), 34
module, 32 get_route_handler()
fastapi_contrib.pagination (fastapi_contrib.routes.ValidationErrorLoggingRoute
module, 33 method), 36
fastapi_contrib.permissions get_timezone() (in module
module, 34 fastapi_contrib.common.utils), 21
fastapi_contrib.routes
module, 36 H
fastapi_contrib.serializers has_required_permissions()
module, 27 (fastapi_contrib.auth.permissions.IsAuthenticated
fastapi_contrib.serializers.common method), 19
module, 25 has_required_permissions()
fastapi_contrib.serializers.openapi (fastapi_contrib.permissions.BasePermission
module, 27 method), 35
fastapi_contrib.serializers.utils http_exception_handler() (in module
module, 27 fastapi_contrib.exception_handlers), 31
fastapi_contrib.tracing HTTPException, 32
module, 29
fastapi_contrib.tracing.middlewares
48 Index
FastAPI Contrib Documentation, Release 0.2.11
I fastapi_contrib.auth.permissions, 19
id (fastapi_contrib.db.models.MongoDBModel at- fastapi_contrib.auth.serializers, 20
tribute), 23 fastapi_contrib.common, 22
indexes (fastapi_contrib.auth.models.Token.Meta fastapi_contrib.common.middlewares, 20
attribute), 19 fastapi_contrib.common.responses, 21
insert() (fastapi_contrib.db.client.MongoDBClient fastapi_contrib.common.utils, 21
method), 22 fastapi_contrib.conf, 29
internal_server_error_handler() (in module fastapi_contrib.db, 25
fastapi_contrib.exception_handlers), 31 fastapi_contrib.db.client, 22
InternalServerError, 32 fastapi_contrib.db.models, 23
is_active (fastapi_contrib.auth.models.Token at- fastapi_contrib.db.utils, 24
tribute), 19 fastapi_contrib.exception_handlers, 31
IsAuthenticated (class in fastapi_contrib.exceptions, 32
fastapi_contrib.auth.permissions), 19 fastapi_contrib.pagination, 33
fastapi_contrib.permissions, 34
J fastapi_contrib.routes, 36
fastapi_contrib.serializers, 27
jaeger_host (fastapi_contrib.conf.Settings attribute),
fastapi_contrib.serializers.common, 25
30
fastapi_contrib.serializers.openapi, 27
jaeger_port (fastapi_contrib.conf.Settings attribute),
fastapi_contrib.serializers.utils, 27
30
fastapi_contrib.tracing, 29
jaeger_sampler_rate (fastapi_contrib.conf.Settings
fastapi_contrib.tracing.middlewares, 28
attribute), 30
fastapi_contrib.tracing.utils, 28
jaeger_sampler_type (fastapi_contrib.conf.Settings
mongodb_dbname (fastapi_contrib.conf.Settings at-
attribute), 30
tribute), 30
mongodb_dsn (fastapi_contrib.conf.Settings attribute),
K 30
key (fastapi_contrib.auth.models.Token attribute), 19 mongodb_id_generator (fastapi_contrib.conf.Settings
attribute), 30
L mongodb_max_pool_size (fastapi_contrib.conf.Settings
list() (fastapi_contrib.db.client.MongoDBClient attribute), 30
method), 22 mongodb_min_pool_size (fastapi_contrib.conf.Settings
list() (fastapi_contrib.db.models.MongoDBModel attribute), 30
class method), 23 MongoDBClient (class in fastapi_contrib.db.client), 22
log_level (fastapi_contrib.conf.Settings attribute), 30 MongoDBModel (class in fastapi_contrib.db.models), 23
logger (fastapi_contrib.conf.Settings attribute), 30 MongoDBModel.Config (class in
fastapi_contrib.db.models), 23
M MongoDBTimeStampedModel (class in
max_limit (fastapi_contrib.pagination.Pagination at- fastapi_contrib.db.models), 23
tribute), 34
max_offset (fastapi_contrib.pagination.Pagination at- N
tribute), 34 not_found_error_handler() (in module
model (fastapi_contrib.auth.serializers.TokenSerializer.Meta fastapi_contrib.exception_handlers), 31
attribute), 20 NotFoundError, 32
model (fastapi_contrib.serializers.common.AbstractMeta NotSet (class in fastapi_contrib.db.models), 24
attribute), 25 now_function (fastapi_contrib.conf.Settings attribute),
ModelSerializer (class in 30
fastapi_contrib.serializers.common), 25
module O
fastapi_contrib, 36 OpentracingMiddleware (class in
fastapi_contrib.auth, 20 fastapi_contrib.tracing.middlewares), 28
fastapi_contrib.auth.backends, 17
fastapi_contrib.auth.middlewares, 18 P
fastapi_contrib.auth.models, 18 paginate() (fastapi_contrib.pagination.Pagination
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.serializers.common.AbstractMeta
attribute), 25
Index 51