# FastAPI Python Backend Expert Build high-performance async REST APIs with FastAPI, Python's fastest-growing web framework. Automatic OpenAPI docs, type validation with Pydantic, and async/await support. --- ## Metadata **Title:** FastAPI Python Backend Expert **Category:** skills **Author:** JSONbored **Added:** October 2025 **Tags:** fastapi, python, api, async, pydantic **URL:** https://claudepro.directory/skills/fastapi-python-backend ## Overview Build high-performance async REST APIs with FastAPI, Python's fastest-growing web framework. Automatic OpenAPI docs, type validation with Pydantic, and async/await support. ## Content FASTAPI PYTHON BACKEND EXPERT SKILL WHAT THIS SKILL ENABLES Claude can build production-ready REST APIs using FastAPI, Python's fastest web framework with automatic OpenAPI documentation and async support. FastAPI combines Python 3.9+ type hints with Pydantic validation for type-safe APIs that rival Node.js performance. With automatic interactive docs, dependency injection, and async/await, FastAPI eliminates boilerplate while maintaining enterprise-grade reliability. PREREQUISITES Required: • Claude Pro subscription or Claude Code CLI • Python 3.9+ (+ recommended for best performance) • pip or poetry package manager • Basic Python knowledge What Claude handles automatically: • Writing FastAPI route handlers with type hints • Creating Pydantic models for request/response validation • Adding automatic OpenAPI/Swagger documentation • Implementing async endpoints for I/O-bound operations • Setting up dependency injection for auth/database • Handling errors with custom exception handlers • Adding middleware for CORS, logging, rate limiting • Structuring large applications with routers HOW TO USE THIS SKILL Basic CRUD API Prompt: "Create a FastAPI CRUD API for blog posts with: GET /posts (list), POST /posts (create), GET /posts/{id} (get one), PUT /posts/{id} (update), DELETE /posts/{id} (delete). Use Pydantic for validation." Claude will: 1) Create FastAPI app with routers 2) Define Pydantic models for Post 3) Implement all 5 CRUD endpoints 4) Add automatic validation 5) Include OpenAPI docs at /docs 6) Add error handling for 404s 7) Return proper HTTP status codes Database Integration with SQLAlchemy Prompt: "Build FastAPI app with PostgreSQL using SQLAlchemy ORM. Include: user authentication, database models for users/posts, async queries, connection pooling, and migrations with Alembic." Claude will: 1) Set up async SQLAlchemy engine 2) Create database models with relationships 3) Implement dependency injection for sessions 4) Add async CRUD operations 5) Include connection pooling config 6) Set up Alembic for migrations 7) Add authentication dependencies Authentication & Authorization Prompt: "Create FastAPI auth system with JWT tokens. Include: user registration, login, password hashing with bcrypt, protected routes with dependencies, refresh tokens, and role-based access control." Claude will: 1) Implement password hashing with passlib 2) Create JWT token generation/validation 3) Add OAuth2 password bearer scheme 4) Build auth dependencies for routes 5) Implement refresh token rotation 6) Add role-based access decorators 7) Include user registration/login endpoints Async Background Tasks Prompt: "Build FastAPI endpoint that processes uploaded CSV file in background. Include: file upload validation, background task with progress tracking, webhook notification on completion, and error handling." Claude will: 1) Create file upload endpoint 2) Validate CSV format with Pydantic 3) Launch background task 4) Add progress tracking with Redis 5) Implement webhook callback 6) Handle errors gracefully 7) Return task ID for status checks TIPS FOR BEST RESULTS 1) Use Type Hints Everywhere: FastAPI relies on Python type hints for automatic validation and docs. Always specify return types and use Optional[T] for nullable fields. 2) Async for I/O-Bound: Use async def for endpoints that do database queries, API calls, or file operations. FastAPI handles concurrency automatically. 3) Pydantic for Validation: Create Pydantic models for request bodies. Never parse JSON manually - let Pydantic handle validation and serialization. 4) Dependency Injection: Use FastAPI's Depends() for auth, database sessions, pagination, etc. This keeps endpoints clean and testable. 5) Status Codes Matter: Use proper HTTP status codes: for created, for deleted, for not found, for validation errors. 6) OpenAPI Customization: Add descriptions, examples, and tags to endpoints for better automatic documentation. COMMON WORKFLOWS E-Commerce API "Build FastAPI e-commerce backend: 1. Products: CRUD with search, filtering, pagination 2. Cart: session-based with Redis, add/remove items, calculate totals 3. Orders: create order, payment processing, order history 4. Auth: JWT-based customer accounts with OAuth2 5. Admin: protected endpoints for inventory management 6. Webhooks: Stripe payment notifications 7. Database: PostgreSQL with async SQLAlchemy 8. Background tasks: order confirmation emails" Real-Time Analytics API "Create FastAPI analytics dashboard backend: 1. Ingest endpoint: accept events via POST with Pydantic validation 2. Time-series storage: TimescaleDB for event data 3. Aggregation endpoints: metrics by day/week/month 4. WebSocket: real-time updates for live dashboard 5. Caching: Redis for frequently-accessed metrics 6. Rate limiting: per-API-key limits with middleware 7. Export: CSV/JSON download of filtered data 8. Admin API: user management, API key generation" Multi-Tenant SaaS API "Build multi-tenant SaaS API with FastAPI: 1. Tenant isolation: subdomain-based routing 2. Database: separate schemas per tenant in PostgreSQL 3. Auth: tenant-scoped JWT tokens 4. Billing: usage tracking, quota enforcement 5. API versioning: /v1/, /v2/ with deprecation notices 6. Rate limiting: per-tenant quotas 7. Webhooks: tenant-configurable event notifications 8. Admin: tenant provisioning, feature flags" GraphQL + REST Hybrid "Create FastAPI app with both REST and GraphQL: 1. REST endpoints: CRUD operations with OpenAPI docs 2. GraphQL: Strawberry integration for complex queries 3. DataLoader: batching and caching for N+1 queries 4. Auth: shared JWT validation across REST/GraphQL 5. Subscriptions: WebSocket support for real-time data 6. File uploads: multipart form data handling 7. Error handling: unified error format 8. Testing: pytest fixtures for both APIs" TROUBLESHOOTING Issue: "Pydantic validation errors not showing custom messages" Solution: Add Field() with description: email: str = Field(..., description='Valid email required'). Use @validator decorator for complex rules. Check Pydantic V2 migration if using FastAPI +. Issue: "Async endpoints slower than sync" Solution: Only use async for I/O operations (database, HTTP calls). CPU-bound tasks should use sync functions. Ensure database driver supports async (asyncpg, aiomysql). Check connection pool settings. Issue: "CORS errors in browser" Solution: Add CORSMiddleware with correct origins: app.addmiddleware(CORSMiddleware, alloworigins=['http://localhost:'], allow_credentials=True). Don't use wildcard in production. Issue: "Dependency injection not working" Solution: Ensure dependencies return values, not None. Use Depends() in function signature, not inside function body. Check dependency order - dependencies can depend on other dependencies. Issue: "File uploads failing with error" Solution: Increase max upload size in uvicorn: uvicorn.run(app, limitconcurrency=, limitmaxrequests=, timeoutkeep_alive=30). For large files, use streaming with UploadFile. LEARN MORE • FastAPI Official Documentation (https://fastapi.tiangolo.com/) • FastAPI GitHub Repository (https://github.com/fastapi/fastapi) • Pydantic V2 Documentation (https://docs.pydantic.dev/) • SQLAlchemy Async Tutorial (https://docs.sqlalchemy.org/en/20/orm/extensions/asyncio.html) • FastAPI Full Stack Template (https://github.com/fastapi/full-stack-fastapi-template) • FastAPI Best Practices (https://github.com/zhanymkanov/fastapi-best-practices) KEY FEATURES ? Automatic OpenAPI/Swagger documentation generation ? Native async/await support for high concurrency ? Pydantic integration for request/response validation ? Dependency injection system for clean architecture REQUIREMENTS ? Python 3.9+ ? fastapi ^ ? uvicorn[standard] ^ ? pydantic ^ INSTALLATION CLAUDE DESKTOP: 1) Install FastAPI: pip install fastapi uvicorn[standard] 2) Ask Claude: 'Create a FastAPI application for [your use case]' 3) Claude generates routes, models, and documentation 4) Run with: uvicorn main:app --reload CLAUDE CODE: 1) pip install fastapi uvicorn[standard] pydantic sqlalchemy 2) Create project structure: app/main.py, app/models/, app/routes/ 3) Run development server: uvicorn app.main:app --reload --host 4) Access docs at http://localhost:/docs USE CASES ? REST API backends with automatic documentation ? Microservices with async database operations ? Real-time APIs with WebSocket support TROUBLESHOOTING 1) Pydantic validation not showing custom messages Solution: Use Field() with description parameter. Check Pydantic V2 migration if using FastAPI +. Add @validator decorators for complex validation rules. 2) Async endpoints performing slower than sync Solution: Only use async for I/O-bound operations (database, API calls). Ensure async database driver (asyncpg, aiomysql). Check connection pool configuration. CPU-bound tasks should use sync. 3) CORS errors blocking frontend requests Solution: Add CORSMiddleware with correct alloworigins. Don't use wildcard ('*') in production. Include allowcredentials=True for cookies. Restart uvicorn after middleware changes. USAGE EXAMPLES 1) Basic FastAPI Application Language: python Code: from fastapi import FastAPI, HTTPException from pydantic import BaseModel, Field from typing import List app = FastAPI(title="Blog API", version="") # Pydantic models class PostCreate(BaseModel): title: str = Field(..., min_length=1, max_length=) content: str = Field(..., min_length=1) published: bool = False class Post(PostCreate): id: int class Config: from_attributes = True # In-memory storage (use database in production) posts_db: List[Post] = [] post_id_counter = 1 @app.get("/posts", response_model=List[Post], tags=["posts"]) async def list_posts(): """Get all blog posts""" return posts_db @app.post("/posts", response_model=Post, status_code=, tags=["posts"]) async def create_post(post: PostCreate): """Create a new blog post""" global post_id_counter new_post = Post(id=post_id_counter, **post.dict()) posts_db.append(new_post) post_id_counter += 1 return new_post @app.get("/posts/{post_id}", response_model=Post, tags=["posts"]) async def get_post(post_id: int): """Get a single post by ID""" for post in posts_db: if post.id == post_id: return post raise HTTPException(status_code=, detail="Post not found") @app.delete("/posts/{post_id}", status_code=, tags=["posts"]) async def delete_post(post_id: int): """Delete a post by ID""" for i, post in enumerate(posts_db): if post.id == post_id: posts_db.pop(i) return raise HTTPException(status_code=, detail="Post not found") # Run with: uvicorn main:app --reload # Docs at: http://localhost:/docs 2) Database Integration with SQLAlchemy Language: python Code: from fastapi import FastAPI, Depends, HTTPException from sqlalchemy.ext.asyncio import AsyncSession, create_async_engine, async_sessionmaker from sqlalchemy.orm import DeclarativeBase, Mapped, mapped_column from sqlalchemy import select from pydantic import BaseModel # Database setup DATABASE_URL = "postgresql+asyncpg://user:pass@localhost/dbname" engine = create_async_engine(DATABASE_URL, echo=True) AsyncSessionLocal = async_sessionmaker(engine, expire_on_commit=False) class Base(DeclarativeBase): pass class User(Base): __tablename__ = "users" id: Mapped[int] = mapped_column(primary_key=True) email: Mapped[str] = mapped_column(unique=True, index=True) name: Mapped[str] # Pydantic schemas class UserCreate(BaseModel): email: str name: str class UserResponse(BaseModel): id: int email: str name: str class Config: from_attributes = True app = FastAPI() # Dependency injection for database session async def get_db(): async with AsyncSessionLocal() as session: yield session @app.post("/users", response_model=UserResponse, status_code=) async def create_user( user: UserCreate, db: AsyncSession = Depends(get_db) ): """Create a new user""" db_user = User(email=user.email, name=user.name) db.add(db_user) await db.commit() await db.refresh(db_user) return db_user @app.get("/users/{user_id}", response_model=UserResponse) async def get_user( user_id: int, db: AsyncSession = Depends(get_db) ): """Get user by ID""" result = await db.execute(select(User).where(User.id == user_id)) user = result.scalar_one_or_none() if not user: raise HTTPException(status_code=, detail="User not found") return user 3) JWT Authentication Language: python Code: from fastapi import FastAPI, Depends, HTTPException, status from fastapi.security import OAuth2PasswordBearer, OAuth2PasswordRequestForm from jose import JWTError, jwt from passlib.context import CryptContext from pydantic import BaseModel from datetime import datetime, timedelta from typing import Optional SECRET_KEY = "your-secret-key-here" # Use environment variable in production ALGORITHM = "HS256" ACCESS_TOKEN_EXPIRE_MINUTES = 30 app = FastAPI() pwd_context = CryptContext(schemes=["bcrypt"], deprecated="auto") oauth2_scheme = OAuth2PasswordBearer(tokenUrl="token") # Pydantic models class Token(BaseModel): access_token: str token_type: str class User(BaseModel): username: str email: str disabled: Optional[bool] = None # Fake user database (use real database in production) fake_users_db = { "johndoe": { "username": "johndoe", "email": "john@example.com", "hashed_password": pwd_context.hash("secret"), "disabled": False, } } def create_access_token(data: dict, expires_delta: Optional[timedelta] = None): to_encode = data.copy() expire = datetime.utcnow() + (expires_delta or timedelta(minutes=15)) to_encode.update({"exp": expire}) return jwt.encode(to_encode, SECRET_KEY, algorithm=ALGORITHM) async def get_current_user(token: str = Depends(oauth2_scheme)): credentials_exception = HTTPException( status_code=status.HTTP_401_UNAUTHORIZED, detail="Could not validate credentials", headers={"WWW-Authenticate": "Bearer"}, ) try: payload = jwt.decode(token, SECRET_KEY, algorithms=[ALGORITHM]) username: str = payload.get("sub") if username is None: raise credentials_exception except JWTError: raise credentials_exception user = fake_users_db.get(username) if user is None: raise credentials_exception return User(**user) @app.post("/token", response_model=Token) async def login(form_data: OAuth2PasswordRequestForm = Depends()): user = fake_users_db.get(form_data.username) if not user or not pwd_context.verify(form_data.password, user["hashed_password"]): raise HTTPException(status_code=, detail="Incorrect username or password") access_token = create_access_token( data={"sub": user["username"]}, expires_delta=timedelta(minutes=ACCESS_TOKEN_EXPIRE_MINUTES) ) return {"access_token": access_token, "token_type": "bearer"} @app.get("/users/me", response_model=User) async def read_users_me(current_user: User = Depends(get_current_user)): """Protected endpoint - requires authentication""" return current_user TECHNICAL DETAILS Documentation: https://fastapi.tiangolo.com/ --- Source: Claude Pro Directory Website: https://claudepro.directory URL: https://claudepro.directory/skills/fastapi-python-backend This content is optimized for Large Language Models (LLMs). For full formatting and interactive features, visit the website.