fastapi
Build high-performance Python APIs with FastAPI: routing, Pydantic validation, async, dependency injection, OpenAPI, and testing. Use for any Python backend.
FastAPI
High-performance Python API framework with automatic OpenAPI docs.
Quick Start
pip install fastapi uvicorn
uvicorn main:app --reload
# http://localhost:8000/docs (Swagger UI)When to Use
- REST or async APIs in Python
- Microservices and serverless handlers
- Projects needing validation, typed contracts, and OpenAPI schema
- Async workloads (HTTP clients, WebSockets, background tasks)
Best Practices
Structure
- Organize by feature: `routers/`, `schemas/`, `services/`, `models/`
- Use APIRouter per resource; include them in the app
- Keep business logic in services, not in route handlers
- Put Pydantic schemas in a dedicated module
Validation & Types
- Define request/response models with Pydantic
- Use `Depends` for shared logic (auth, DB sessions)
- Set `response_model` on every endpoint
- Prefer `Annotated` dependencies for clarity
Async
- Use `async def` for I/O-bound endpoints
- Prefer async SQLAlchemy/asyncpg for DB access
- Offload CPU-bound work to a threadpool (`run_in_executor`)
- Avoid blocking calls in the event loop
Dependencies
pip install fastapi uvicorn[standard] pydantic
pip install -D pytest httpx pytest-asyncioExamples
from fastapi import FastAPI, Depends, HTTPException
from pydantic import BaseModel
from typing import Annotated
app = FastAPI(title="Items API")
class Item(BaseModel):
name: str
price: float
class ItemOut(BaseModel):
id: int
name: str
price: float
def get_session():
# injected dependency
yield {"conn": "pool"}
@app.post("/items", response_model=ItemOut, status_code=201)
async def create_item(item: Item, session: Annotated[dict, Depends(get_session)]):
return ItemOut(id=1, **item.model_dump())# Router pattern
from fastapi import APIRouter
router = APIRouter(prefix="/users", tags=["users"])
@router.get("/{user_id}")
async def get_user(user_id: int):
if user_id < 0:
raise HTTPException(status_code=400, detail="Invalid id")
return {"id": user_id}# Async DB with asyncpg
import asyncpg
from fastapi import Depends
async def get_pool():
pool = await asyncpg.create_pool(dsn="postgres://localhost/app")
try:
yield pool
finally:
await pool.close()# Background task
from fastapi import BackgroundTasks
async def send_email(email: str):
pass # send in background
@app.post("/notify")
async def notify(email: str, bg: BackgroundTasks):
bg.add_task(send_email, email)
return {"ok": True}Step-by-Step
1. Scaffold: create `main.py` with the FastAPI app and import routers.
2. Define Pydantic schemas for every request and response model.
3. Write route handlers with `response_model` and correct status codes.
4. Add dependencies (`Depends`) for auth, DB sessions, and settings.
5. Use async handlers and async DB drivers for concurrency.
6. Add exception handlers for consistent error responses.
7. Write tests with `httpx` + `pytest`; override dependencies for isolation.
8. Validate the generated OpenAPI schema in CI; lock your dependencies.
Validation
1. `uvicorn main:app` starts cleanly
2. `/docs` renders schemas with correct types
3. `pytest` passes (unit + integration with TestClient)
4. Invalid input returns 422 with Pydantic details
5. Response models match declared schemas
Troubleshooting
- 422 on valid input: check Pydantic field types vs JSON types.
- Slow async endpoints: look for blocking sync calls in `async def`.
- Circular imports: move schemas to a shared module.
FastAPI (ФастАПИ)
Высокопроизводительный Python-фреймворк для API с автоматической OpenAPI-документацией.
Быстрый старт
pip install fastapi uvicorn
uvicorn main:app --reload
# http://localhost:8000/docs (Swagger UI)Когда использовать
- REST или async API на Python
- Микросервисы и serverless-обработчики
- Проекты, которым нужны валидация, типизированные контракты и OpenAPI-схема
- Async-нагрузки (HTTP-клиенты, WebSockets, фоновые задачи)
Лучшие практики
Структура
- Организуйте по фичам: `routers/`, `schemas/`, `services/`, `models/`
- Используйте APIRouter на ресурс; подключайте их в приложение
- Держите бизнес-логику в сервисах, а не в обработчиках маршрутов
- Выносите Pydantic-схемы в отдельный модуль
Валидация и типы
- Определяйте модели запросов/ответов через Pydantic
- Используйте `Depends` для общей логики (auth, сессии БД)
- Задавайте `response_model` на каждом эндпоинте
- Предпочитайте `Annotated`-зависимости для читаемости
Async
- Используйте `async def` для I/O-bound эндпоинтов
- Для БД предпочитайте async SQLAlchemy/asyncpg
- Выносите CPU-bound работу в threadpool (`run_in_executor`)
- Избегайте блокирующих вызовов в event loop
Зависимости
pip install fastapi uvicorn[standard] pydantic
pip install -D pytest httpx pytest-asyncioПримеры
from fastapi import FastAPI, Depends, HTTPException
from pydantic import BaseModel
from typing import Annotated
app = FastAPI(title="Items API")
class Item(BaseModel):
name: str
price: float
class ItemOut(BaseModel):
id: int
name: str
price: float
def get_session():
# инжектируемая зависимость
yield {"conn": "pool"}
@app.post("/items", response_model=ItemOut, status_code=201)
async def create_item(item: Item, session: Annotated[dict, Depends(get_session)]):
return ItemOut(id=1, **item.model_dump())# Паттерн роутера
from fastapi import APIRouter
router = APIRouter(prefix="/users", tags=["users"])
@router.get("/{user_id}")
async def get_user(user_id: int):
if user_id < 0:
raise HTTPException(status_code=400, detail="Invalid id")
return {"id": user_id}# Async БД через asyncpg
import asyncpg
from fastapi import Depends
async def get_pool():
pool = await asyncpg.create_pool(dsn="postgres://localhost/app")
try:
yield pool
finally:
await pool.close()# Фоновая задача
from fastapi import BackgroundTasks
async def send_email(email: str):
pass # отправка в фоне
@app.post("/notify")
async def notify(email: str, bg: BackgroundTasks):
bg.add_task(send_email, email)
return {"ok": True}Пошаговое руководство
1. Скаффолд: создайте `main.py` с FastAPI-приложением и импортируйте роутеры.
2. Определите Pydantic-схемы для каждой модели запроса и ответа.
3. Пишите обработчики с `response_model` и корректными статус-кодами.
4. Добавьте зависимости (`Depends`) для auth, сессий БД и настроек.
5. Используйте async-обработчики и async-драйверы БД для конкурентности.
6. Добавьте exception handlers для единообразных ошибок.
7. Пишите тесты на `httpx` + `pytest`; переопределяйте зависимости для изоляции.
8. Валидируйте OpenAPI-схему в CI; фиксируйте зависимости.
Валидация
1. `uvicorn main:app` стартует чисто
2. `/docs` отображает схемы с корректными типами
3. `pytest` проходит (юнит + интеграция с TestClient)
4. Невалидный ввод возвращает 422 с деталями Pydantic
5. Модели ответов совпадают с объявленными схемами
Устранение неполадок
- 422 на валидном вводе: проверьте типы полей Pydantic против JSON.
- Медленные async-эндпоинты: ищите блокирующие sync-вызовы в `async def`.
- Циклические импорты: выносите схемы в общий модуль.