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.
#FastAPIPythonBackendExpertSkill##WhatThisSkillEnablesClaudecanbuildproduction-readyRESTAPIsusingFastAPI,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+ (3.11+ 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 routers2. Define Pydantic models for Post3. Implement all 5 CRUD endpoints4. Add automatic validation5. Include OpenAPI docs at /docs6. Add error handling for 404s7. 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 engine2. Create database models with relationships3. Implement dependency injection for sessions4. Add async CRUD operations5. Include connection pooling config6. Set up Alembic for migrations7. 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 passlib2. Create JWT token generation/validation3. Add OAuth2 password bearer scheme4. Build auth dependencies for routes5. Implement refresh token rotation6. Add role-based access decorators7. 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 endpoint2. Validate CSV format with Pydantic3. Launch background task4. Add progress tracking with Redis5. Implement webhook callback6. Handle errors gracefully7. Return task ID for status checks## Tips for Best Results1. **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()`forauth,databasesessions,pagination,etc.Thiskeepsendpointscleanandtestable.5.**StatusCodesMatter**:UseproperHTTPstatuscodes:201forcreated,204fordeleted,404fornotfound,422forvalidationerrors.6.**OpenAPICustomization**:Adddescriptions,examples,andtagstoendpointsforbetterautomaticdocumentation.##CommonWorkflows###E-CommerceAPI```"Build FastAPI e-commerce backend:1. Products: CRUD with search, filtering, pagination2. Cart: session-based with Redis, add/remove items, calculate totals3. Orders: create order, payment processing, order history4. Auth: JWT-based customer accounts with OAuth25. Admin: protected endpoints for inventory management6. Webhooks: Stripe payment notifications7. Database: PostgreSQL with async SQLAlchemy8. Background tasks: order confirmation emails"```###Real-TimeAnalyticsAPI```"Create FastAPI analytics dashboard backend:1. Ingest endpoint: accept events via POST with Pydantic validation2. Time-series storage: TimescaleDB for event data3. Aggregation endpoints: metrics by day/week/month4. WebSocket: real-time updates for live dashboard5. Caching: Redis for frequently-accessed metrics6. Rate limiting: per-API-key limits with middleware7. Export: CSV/JSON download of filtered data8. Admin API: user management, API key generation"```###Multi-TenantSaaSAPI```"Build multi-tenant SaaS API with FastAPI:1. Tenant isolation: subdomain-based routing2. Database: separate schemas per tenant in PostgreSQL3. Auth: tenant-scoped JWT tokens4. Billing: usage tracking, quota enforcement5. API versioning: /v1/, /v2/ with deprecation notices6. Rate limiting: per-tenant quotas7. Webhooks: tenant-configurable event notifications8. Admin: tenant provisioning, feature flags"```###GraphQL+RESTHybrid```"Create FastAPI app with both REST and GraphQL:1. REST endpoints: CRUD operations with OpenAPI docs2. GraphQL: Strawberry integration for complex queries3. DataLoader: batching and caching for N+1 queries4. Auth: shared JWT validation across REST/GraphQL5. Subscriptions: WebSocket support for real-time data6. File uploads: multipart form data handling7. Error handling: unified error format8. Testing: pytest fixtures for both APIs"```##Troubleshooting**Issue:**"Pydantic validation errors not showing custom messages"**Solution:**AddField()withdescription:`email: str = Field(..., description='Valid email required')`.Use@validatordecoratorforcomplexrules.CheckPydanticV2migrationifusingFastAPI0.100+.**Issue:**"Async endpoints slower than sync"**Solution:**OnlyuseasyncforI/Ooperations(database,HTTPcalls).CPU-boundtasksshouldusesyncfunctions.Ensuredatabasedriversupportsasync(asyncpg,aiomysql).Checkconnectionpoolsettings.**Issue:**"CORS errors in browser"**Solution:**AddCORSMiddlewarewithcorrectorigins:`app.add_middleware(CORSMiddleware, allow_origins=['http://localhost:3000'], 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 413 error"**Solution:** Increase max upload size in uvicorn: `uvicorn.run(app, limit_concurrency=100, limit_max_requests=1000, timeout_keep_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)
Ask Claude: 'Create a FastAPI application for [your use case]'
Claude generates routes, models, and documentation
Run with: uvicorn main:app --reload
Use Cases
Common scenarios and applications
REST API backends with automatic documentation
Microservices with async database operations
Real-time APIs with WebSocket support
Troubleshooting
Common issues and solutions
Pydantic validation not showing custom messages
Use Field() with description parameter. Check Pydantic V2 migration if using FastAPI 0.100+. Add @validator decorators for complex validation rules.
Async endpoints performing slower than sync
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.
CORS errors blocking frontend requests
Add CORSMiddleware with correct allow_origins. Don't use wildcard ('*') in production. Include allow_credentials=True for cookies. Restart uvicorn after middleware changes.
Usage Examples
Practical code examples demonstrating common use cases and implementation patterns
Basic FastAPI Application
basic-fastapi-application.py
python
fromfastapiimportFastAPI,HTTPExceptionfrompydanticimportBaseModel,FieldfromtypingimportListapp=FastAPI(title="Blog API",version="1.0.0")#PydanticmodelsclassPostCreate(BaseModel):title:str=Field(...,min_length=1,max_length=200)content:str=Field(...,min_length=1)published:bool=FalseclassPost(PostCreate):id:intclassConfig:from_attributes=True#In-memorystorage(usedatabaseinproduction)posts_db:List[Post]=[]post_id_counter=1@app.get("/posts",response_model=List[Post],tags=["posts"])asyncdeflist_posts():"""Get all blog posts"""returnposts_db@app.post("/posts",response_model=Post,status_code=201,tags=["posts"])asyncdefcreate_post(post:PostCreate):"""Create a new blog post"""globalpost_id_counternew_post=Post(id=post_id_counter,**post.dict())posts_db.append(new_post)post_id_counter+=1returnnew_post@app.get("/posts/{post_id}",response_model=Post,tags=["posts"])asyncdefget_post(post_id:int):"""Get a single post by ID"""forpostinposts_db:ifpost.id==post_id:returnpostraiseHTTPException(status_code=404,detail="Post not found")@app.delete("/posts/{post_id}",status_code=204,tags=["posts"])asyncdefdelete_post(post_id:int):"""Delete a post by ID"""fori,postinenumerate(posts_db):ifpost.id==post_id:posts_db.pop(i)returnraiseHTTPException(status_code=404,detail="Post not found")#Runwith:uvicornmain:app--reload#Docsat:http://localhost:8000/docs
Database Integration with SQLAlchemy
database-integration-with-sqlalchemy.py
python
fromfastapiimportFastAPI,Depends,HTTPExceptionfromsqlalchemy.ext.asyncioimportAsyncSession,create_async_engine,async_sessionmakerfromsqlalchemy.ormimportDeclarativeBase,Mapped,mapped_columnfromsqlalchemyimportselectfrompydanticimportBaseModel#DatabasesetupDATABASE_URL="postgresql+asyncpg://user:pass@localhost/dbname"engine=create_async_engine(DATABASE_URL,echo=True)AsyncSessionLocal=async_sessionmaker(engine,expire_on_commit=False)classBase(DeclarativeBase):passclassUser(Base):__tablename__="users"id:Mapped[int]=mapped_column(primary_key=True)email:Mapped[str]=mapped_column(unique=True,index=True)name:Mapped[str]#PydanticschemasclassUserCreate(BaseModel):email:strname:strclassUserResponse(BaseModel):id:intemail:strname:strclassConfig:from_attributes=Trueapp=FastAPI()#Dependencyinjectionfordatabasesessionasyncdefget_db():asyncwithAsyncSessionLocal()assession:yieldsession@app.post("/users",response_model=UserResponse,status_code=201)asyncdefcreate_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)awaitdb.commit()awaitdb.refresh(db_user)returndb_user@app.get("/users/{user_id}",response_model=UserResponse)asyncdefget_user(user_id:int,db:AsyncSession=Depends(get_db)):"""Get user by ID"""result=awaitdb.execute(select(User).where(User.id==user_id))user=result.scalar_one_or_none()ifnotuser:raiseHTTPException(status_code=404,detail="User not found")returnuser
JWT Authentication
jwt-authentication.py
python
fromfastapiimportFastAPI,Depends,HTTPException,statusfromfastapi.securityimportOAuth2PasswordBearer,OAuth2PasswordRequestFormfromjoseimportJWTError,jwtfrompasslib.contextimportCryptContextfrompydanticimportBaseModelfromdatetimeimportdatetime,timedeltafromtypingimportOptionalSECRET_KEY="your-secret-key-here"#UseenvironmentvariableinproductionALGORITHM="HS256"ACCESS_TOKEN_EXPIRE_MINUTES=30app=FastAPI()pwd_context=CryptContext(schemes=["bcrypt"],deprecated="auto")oauth2_scheme=OAuth2PasswordBearer(tokenUrl="token")#PydanticmodelsclassToken(BaseModel):access_token:strtoken_type:strclassUser(BaseModel):username:stremail:strdisabled:Optional[bool]=None#Fakeuserdatabase(userealdatabaseinproduction)fake_users_db={"johndoe":{"username":"johndoe","email":"john@example.com","hashed_password":pwd_context.hash("secret"),"disabled":False,}}defcreate_access_token(data:dict,expires_delta:Optional[timedelta]=None):to_encode=data.copy()expire=datetime.utcnow()+(expires_deltaortimedelta(minutes=15))to_encode.update({"exp":expire})returnjwt.encode(to_encode,SECRET_KEY,algorithm=ALGORITHM)asyncdefget_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")ifusernameisNone:raisecredentials_exceptionexceptJWTError:raisecredentials_exceptionuser=fake_users_db.get(username)ifuserisNone:raisecredentials_exceptionreturnUser(**user)@app.post("/token",response_model=Token)asyncdeflogin(form_data:OAuth2PasswordRequestForm=Depends()):user=fake_users_db.get(form_data.username)ifnotuserornotpwd_context.verify(form_data.password,user["hashed_password"]):raiseHTTPException(status_code=400,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)asyncdefread_users_me(current_user:User=Depends(get_current_user)):"""Protected endpoint - requires authentication"""returncurrent_user
Reviews (0)
Loading reviews...
Get the latest Claude resources
Weekly roundup of the best Claude agents, tools, and guides.