FastAPI Boilerplate
Features
- SQlAlchemy session
- Custom user class
- Top-level dependency
- Dependencies for specific permissions
- Celery
SQLAlchemy for asyncio context
Session
from core.db import session
Just import session and use it.
Transaction
To guarantee of transaction, session's autocommit
option is True
.
So you have to use Transaction
class.
from core.db import Transaction, session
@Transaction()
async def create_user(self):
session.add(User(email="[email protected]"))
Usage as decorator.
from core.db import Transaction, session
with Transaction():
session.add(User(email="[email protected]"))
Usage as context manager.
In this case, only one transaction is supported.
Note. Do not use explicit commit()
. Transaction
class automatically do.
Custom user for authentication
from fastapi import Request
@home_router.get("/")
def home(request: Request):
return request.user.id
Note. you have to pass jwt token via header like Authorization: Bearer 1234
Custom user class automatically decodes header token and store user information into request.user
If you want to modify custom user class, you have to update below files.
core/fastapi/schemas/current_user.py
core/fastapi/middlewares/authentication.py
CurrentUser
class CurrentUser(BaseModel):
id: int = None
Simply add more fields based on your needs.
AuthBackend
current_user = CurrentUser()
After line 18, assign values that you added on CurrentUser
.
Top-level dependency
Note. Available from version 0.62 or higher.
Set a callable function when initialize FastAPI() app through dependencies
argument.
Refer Logging
class inside of core/fastapi/dependencies/logging.py
Dependencies for specific permissions
Permissions IsAdmin
and IsAuthenticated
have already been implemented.
from core.fastapi.dependencies import (
PermissionDependency,
IsAdmin,
)
user_router = APIRouter()
@user_router.get(
"",
response_model=List[GetUserListResponseSchema],
response_model_exclude={"id"},
responses={"400": {"model": ExceptionResponseSchema}},
dependencies=[Depends(PermissionDependency([IsAdmin]))], # HERE
)
async def get_user_list(limit: int = 10, prev: int = None):
pass
Insert permission through dependencies
argument.
If you want to make your own permission, inherit BasePermission
and implement has_permission()
function.