gitmyhub

fastapi-best-practices

★ 18k updated 1mo ago

FastAPI Best Practices and Conventions we used at our startup

An opinionated, battle-tested guide to structuring and building production FastAPI services, covering project layout, async patterns, Pydantic validation, database migrations, and linting, based on real startup experience.

PythonFastAPIPydanticAlembicruffsetup: easycomplexity 2/5

This repository is an opinionated guide to building production-ready web services with FastAPI. FastAPI is a Python framework for creating web APIs, and this guide collects the lessons the author and their team learned from running real systems at their startup over several years. It is not a tutorial that teaches FastAPI from scratch; it is a checklist of conventions you can copy or adapt.

The guide is organised by topic. It opens with a suggested project structure inspired by Netflix's Dispatch project, where each business domain (auth, posts, aws, and so on) lives in its own folder inside a top-level src directory, with consistent file names for routers, Pydantic schemas, database models, dependencies, services, configs and exceptions. It then explains the difference between async and sync routes, and shows what happens if you accidentally do a blocking operation inside an async route — the whole server stops handling requests until that operation finishes. Other sections cover how to use Pydantic for validation and settings, how to write reusable dependencies, REST conventions, when to use FastAPI's BackgroundTasks versus a real task queue, database naming conventions and Alembic migrations, treating SQL as the source of truth before Pydantic, and adopting the ruff linter.

Someone would actually use this if they are starting a new FastAPI codebase and want a sensible default structure, or if their existing project has grown messy and they want patterns to lean on. There is also an AGENTS.md companion file with the same rules in a terse format aimed at AI coding agents. The full README is longer than what was provided.

Where it fits