Fastapi Expert

Automate and integrate FastAPI expert development for high-performance Python APIs

FastAPI Expert is a community skill for building high-performance APIs with FastAPI, covering route definition, request validation, dependency injection, async database access, and OpenAPI documentation for modern Python web services.

What Is This?

Overview

FastAPI Expert provides patterns for developing production-grade APIs using the FastAPI framework. It covers route definition with path and query parameter typing for automatic request validation, Pydantic model schemas for request body parsing and response serialization, dependency injection for database sessions, authentication, and shared logic, async endpoint handlers with SQLAlchemy async sessions for non-blocking database access, and middleware configuration for CORS, rate limiting, and request logging. The skill enables developers to build type-safe APIs that generate interactive OpenAPI documentation automatically from Python type annotations.

Who Should Use This

This skill serves Python developers building REST APIs who need automatic validation and documentation, backend engineers designing async microservices with high concurrency requirements, and teams migrating from Flask or Django REST Framework to FastAPI.

Why Use It?

Problems It Solves

Manual request validation requires repetitive boilerplate code that is error-prone and inconsistent across endpoints. Building API documentation separately from code leads to outdated specs that diverge from actual behavior. Managing database connections and authentication state across endpoints needs a structured injection pattern. Handling concurrent requests efficiently requires async support throughout the request lifecycle.

Core Highlights

Pydantic schemas validate requests and serialize responses with automatic error messages. Dependency injection system manages database sessions and auth state per request. Async support handles concurrent requests without blocking on IO operations. OpenAPI docs are generated automatically from type annotations and docstrings.

How to Use It?

Basic Usage

from fastapi import FastAPI, HTTPException
from pydantic import BaseModel, Field
from datetime import datetime

app = FastAPI(title="Task API")

class TaskCreate(BaseModel):
    title: str = Field(
        min_length=1, max_length=200)
    description: str = ""
    priority: int = Field(
        default=1, ge=1, le=5)

class TaskResponse(BaseModel):
    id: int
    title: str
    description: str
    priority: int
    created_at: datetime

    model_config = {"from_attributes": True}

tasks_db: list[dict] = []

@app.post("/tasks",
          response_model=TaskResponse,
          status_code=201)
async def create_task(task: TaskCreate):
    record = {
        "id": len(tasks_db) + 1,
        "title": task.title,
        "description": task.description,
        "priority": task.priority,
        "created_at": datetime.now()}
    tasks_db.append(record)
    return record

@app.get("/tasks/{task_id}",
         response_model=TaskResponse)
async def get_task(task_id: int):
    for task in tasks_db:
        if task["id"] == task_id:
            return task
    raise HTTPException(
        status_code=404,
        detail="Task not found")

Real-World Examples

from fastapi import Depends, Query
from sqlalchemy.ext.asyncio import (
    AsyncSession, create_async_engine,
    async_sessionmaker)
from sqlalchemy import select

engine = create_async_engine(
    "postgresql+asyncpg://user:pass@db/app")
SessionLocal = async_sessionmaker(engine)

async def get_db():
    async with SessionLocal() as session:
        yield session

@app.get("/tasks",
         response_model=list[TaskResponse])
async def list_tasks(
        db: AsyncSession = Depends(get_db),
        skip: int = Query(default=0, ge=0),
        limit: int = Query(
            default=20, ge=1, le=100),
        priority: int | None = None):
    query = select(Task)
    if priority is not None:
        query = query.where(
            Task.priority == priority)
    query = query.offset(skip).limit(limit)
    result = await db.execute(query)
    return result.scalars().all()

@app.put("/tasks/{task_id}",
         response_model=TaskResponse)
async def update_task(
        task_id: int,
        task_data: TaskCreate,
        db: AsyncSession = Depends(get_db)):
    result = await db.execute(
        select(Task).where(
            Task.id == task_id))
    task = result.scalar_one_or_none()
    if not task:
        raise HTTPException(404)
    task.title = task_data.title
    task.description = task_data.description
    task.priority = task_data.priority
    await db.commit()
    await db.refresh(task)
    return task

Advanced Tips

Use response_model_exclude to omit sensitive fields from responses without creating separate schemas. Chain dependencies to build reusable auth and permission checks that compose across endpoint groups. Configure lifespan handlers for startup and shutdown events to manage connection pools and background task initialization.

When to Use It?

Use Cases

Build a microservice API with async database access and automatic request validation from Pydantic models. Create an API gateway that aggregates responses from multiple backend services with concurrent requests. Implement a real-time data ingestion service that handles high-throughput POST requests with background task processing.

Related Topics

Python async programming, Pydantic data validation, SQLAlchemy async ORM, OpenAPI specification, and REST API design.

Important Notes

Requirements

Python 3.9 or later with FastAPI and Uvicorn installed. Pydantic v2 for model validation. An async database driver such as asyncpg for PostgreSQL if using async database access.

Usage Recommendations

Do: define separate Pydantic models for request input and response output to control exposed fields precisely. Use dependency injection for database sessions rather than creating connections inside endpoint functions. Write async test clients using httpx for testing async endpoints.

Don't: mix sync and async database calls within the same application without understanding the threading implications. Return database model instances directly without a response schema that controls serialized fields. Skip input validation by accepting raw dict parameters instead of typed Pydantic models.

Limitations

FastAPI async benefits require an async-compatible database driver and ORM layer. Background tasks run in the same process and are not suitable for long-running jobs that need dedicated workers. The dependency injection system does not support circular dependencies between providers.