Skip to content

FastAPI Conventions

  • Python strings/multilines using doublequotes.
  • Enum class property names uppercase, but string values lowercase.
  • DB collection names plural, lowercase snake case.
  • DB document field names lowercase, plural for lists.
  • DB document field names end with _at if datetime, _date if date, _time if time.
  • Methods returning boolean output prefixed with is_.
  • Pydantic root schemas that correspond to db document schemas inherit from SomethingModel, otherwise from SomethingSchema.
  • Schema and model class names singular unless inappropriate.
  • Pydantic schemas use list instead of set for field types to ensure consistent ordering for pagination and consistency.
  • Schemas corresponding to CRU operations or simple actions on a resource are named as SomethingCreate, SomethingRetrieve and SomethingUpdate, respectively. Exceptions can be made where appropriate.
  • Application modules named after entities should be in plural, unless inappropriate.
  • One repository per DB collection, unless it makes sense to group them in a module.
  • Repository methods named after actions, without corresponding resourse name, unless a repository is used for multiple resources.
  • Repository classes named as SomethingsRepository.
  • service shortened to svc and service dependency to SvcDep.
  • Module service classes always named Service. Only a single service class for one module is allowed.
  • For any function with a dependency injection, non-optional dependencies (annotated with Depends()) should come before other keyword arguments.
  • Modules should be imported using absolute import for clarity, unless it breaks something.
  • Use datetime.now(timezone.utc) instead of local datetime or datetime.utcnow().

Generic structure of a module (folder):

  • init.py – module initialization.
  • config.py – module-specific configs (class Config(BaseSettings): ...).
  • constants.py – constants and enums not appropriate for the module config.
  • dependencies – SvcDep and other things with FastAPI dependencies.
  • models.py – app models (correspond to DB table/file) and necessary schemas for models with complex fields.
  • repository – repository-level logic, i.e. database queries. Repositories inherit from the base class BaseRepository[T].
  • router.py – routes and routers.
  • schemas.py – schemas defining data input and output formats for endpoints.
  • service.py – service-level logic. Defined as a general class Service: ....
  • utils.py – module-specific utility functions.

Example

For a samble FastAPI project, check april-hub-general-api (Postgres) or april-robots-general-api (Mongo).