Skip to content

sanketwagh147/fastapi_base

Repository files navigation

FastAPI Backend Template

Async-first FastAPI starter for services that need structured configuration, pooled I/O, consistent error payloads, and predictable local setup.

This repository is a base template, not a finished product. It gives you the application shell, config system, HTTP and database plumbing, logging, route discovery, and test scaffolding. Domain models, migrations, and real authentication are still yours to add.

What ships

  • FastAPI app with lifespan-based startup and shutdown
  • Async SQLAlchemy engine and session management
  • Shared httpx.AsyncClient pool
  • Route auto-discovery from app/routes
  • Centralized exception handlers with JSON error responses
  • Pydantic settings and secret-backed configuration helpers
  • Structured logging with request correlation IDs
  • Docker, Docker Compose, Makefile, Ruff, MyPy, and pytest setup

Project layout

fastapi-backend/
├── app/
│   ├── core/                 # config, auth, DB, logging, route discovery
│   ├── env_files/            # shipped env files and local secret template
│   ├── models/               # shared SQLAlchemy base and mixins
│   ├── repository/           # repository implementations
│   ├── routes/               # auto-discovered APIRouter modules
│   ├── schemas/              # shared schema helpers
│   ├── main.py               # FastAPI entrypoint
│   └── main_config.py        # Pydantic settings models and cached instances
├── tests/
├── Dockerfile
├── docker-compose.yml
├── Makefile
└── pyproject.toml

Quick start

Requirements

  • Python 3.11+
  • uv

Install dependencies

uv sync --extra dev

Alternative:

make dev

Prepare local secrets

cp app/env_files/.secrets_local.example app/env_files/.secrets_local

Update app/env_files/.secrets_local with your local credentials.

Start Postgres locally

docker compose up -d postgres

Run the API

make run

The application starts through python -m app.main so the custom logging setup stays active.

Endpoints

  • GET /api/
  • GET /api/health
  • GET /api/health/ready
  • GET /api/auth-examples/me
  • GET /api/auth-examples/me/active
  • GET /api/auth-examples/admin-only
  • GET /api/auth-examples/editor-or-admin

OpenAPI docs are exposed at http://localhost:8000/docs and http://localhost:8000/redoc by default.

The auth example routes are wired for dependency composition only. They intentionally return 401 until you replace app/core/auth.py with real token validation or override the dependency in tests.

Configuration

Configuration lives in app/main_config.py and is loaded through Pydantic settings.

  • Shipped env files: app/env_files/.env_base and app/env_files/.env_local
  • For other environments, create app/env_files/.env_<env> or provide values through environment variables
  • Environment variables override file values
  • Environment-specific files override the shared base file
  • Secret-backed fields resolve through app/core/secrets.py and can load from .secrets_<env> or environment variables, depending on the configured secret loader

Key config groups:

  • Settings: process-level host, port, reload, workers, environment
  • FastAPIConfig: docs URLs, root path, FastAPI debug flag
  • DatabaseConfig: async SQLAlchemy URL and pool tuning
  • CORSConfig: allowed origins, methods, headers, credentials
  • LoggingConfig: log format and per-library levels
  • JWTConfig: placeholder JWT settings for future auth work

Guardrails already in place:

  • FASTAPI_DEBUG is rejected in production
  • Default CORS methods and headers are explicit instead of wildcarded
  • The auth dependency fails closed until a real backend is implemented

Runtime flow

  • app/main.py configures logging before creating the FastAPI app
  • app/core/lifespan.py initializes the database pool and shared HTTP client on startup, then disposes both on shutdown
  • app/core/route_discovery.py imports every non-private Python module under app/routes and includes any exported router
  • app/core/exceptions/handlers.py normalizes app errors, validation failures, and unexpected exceptions into a shared JSON shape

Validation

make check

Equivalent direct commands:

ruff check app tests
mypy app
pytest -q

Docker

Run the local stack:

docker compose up --build

The image also starts the app through python -m app.main so the runtime configuration and logging behavior stay consistent.

Extend this template

  1. Add domain models under app/models
  2. Add repositories under app/repository
  3. Add route modules under app/routes
  4. Replace the placeholder auth dependency with real JWT validation
  5. Add service-specific tests beyond the shared exception and config coverage
  6. Add migrations, CI, and observability pieces for your environment

Not included by default

  • Alembic migrations
  • Real authentication and token issuance
  • Background jobs or queue integrations
  • Metrics and tracing exporters
  • Caching or message broker integrations

License

MIT

About

A modern, async-first FastAPI template designed for building scalable REST APIs with strong typing, database connection pooling, and clean architecture patterns. This template provides a solid foundation for microservices and monolithic applications alike.

Resources

Stars

Watchers

Forks

Releases

No releases published

Packages

 
 
 

Contributors