Dependencies¶
FastAPI Batteries comes with some handful dependencies that are common in most FastAPI projects.
File Validator¶
This dependency uses python-magic to accurately determine the file type of the uploaded file.
You can use this validator to:
- Validate the file type (via mime type)
- Validate File Size
from typing import Annotated
from fastapi import Depends, FastAPI, UploadFile
from fastapi_batteries.fastapi.deps import FileValidator
from fastapi_batteries.utils.size import mb_to_bytes
app = FastAPI()
img_validator_upto_1mb = FileValidator(
max_size_bytes=mb_to_bytes(1),
allowed_mime_types=["image/jpeg", "image/png", "image/svg+xml", "image/webp"],
)
pdf_validator_upto_5mb = FileValidator(max_size_bytes=mb_to_bytes(5), allowed_mime_types=["application/pdf"])
@app.post("/upload/")
async def upload_file(file: Annotated[UploadFile, Depends(img_validator_upto_1mb)]): ...
Pagination Query Params¶
FastAPI allows using Pydantic model as query parameter model.
Thanks to that you can have reusable pagination query parameters. This is minimal but faster and when you pair it with our CRUD helper it becomes more powerful.
from typing import Annotated
from fastapi import FastAPI, Query
from fastapi_batteries.pydantic.schemas import PaginationOffsetLimit, PaginationPageSize
app = FastAPI()
@app.get("/items/")
async def get_items_page_size_pagination(pagination: Annotated[PaginationPageSize, Query()]):
return pagination
@app.get("/products/")
async def get_products_offset_limit_pagination(pagination: Annotated[PaginationOffsetLimit, Query()]):
return pagination
Using with other query params¶
When you use Pydantic model schema along with other query params you'll get Pydantic model schema in request body which is wrong:
from typing import Annotated
from fastapi import FastAPI, Query
from fastapi_batteries.pydantic.schemas import PaginationPageSize
app = FastAPI()
@app.get("/items/")
async def get_items_page_size_pagination(
pagination: Annotated[PaginationPageSize, Query()],
q: str = "",
):
return {"q": q, "pagination": pagination}
This is limitation (or bug) from FastAPI. There's already open issue and related discussions for this. However, we've nice workaround for this.
We just have to replace Query()
with Depends()
and it'll work as expected:
- pagination: Annotated[PaginationPageSize, Query()],
+ pagination: Annotated[PaginationPageSize, Depends()],
from typing import Annotated
from fastapi import Depends, FastAPI
from fastapi_batteries.pydantic.schemas import PaginationPageSize
app = FastAPI()
@app.get("/items/")
async def get_items_page_size_pagination(
pagination: Annotated[PaginationPageSize, Depends()],
q: str = "",
):
return {"q": q, "pagination": pagination}