FastAPI Async API Builder: Pydantic V2, SQLAlchemy, JWT
Production FastAPI endpoints, Pydantic V2 models, async SQLAlchemy sessions, and JWT auth, plus fixes for event-loop and session bugs.
Before & after
Same prompt, same agent — the only difference is the skill.
FastAPI is a great framework for building APIs in Python. You'll want to set up a basic FastAPI app with some endpoints. For authentication, you should use JWT tokens. You'll need to create Pydantic models to define your request and response schemas. For database operations, you should use an async-compatible library like SQLAlchemy with async mode. You might want to add error handling and validation to your endpoints. OpenAPI documentation is automatically generated by FastAPI, which is helpful. You should test your endpoints to make sure they work correctly. It's also good to think about deployment and how you'll run the API in production. Would you like help with any specific part of setting up the API?
FASTAPI ENDPOINT: /api/v1/tasks (with JWT + Async DB)
PYDANTIC MODELS
class TaskCreate(BaseModel):
title: str (min_length=1, max_length=255)
description: Optional(str) = None
priority: Literal['low', 'medium', 'high']
class TaskResponse(BaseModel):
id: int
title: str
created_at: datetime
model_config = ConfigDict(from_attributes=True)
ENDPOINT DEFINITION
@app.post('/api/v1/tasks', response_model=TaskResponse, status_code=201)
async def create_task(
task: TaskCreate,
current_user: User = Depends(get_current_user),
db: AsyncSession = Depends(get_db)
) -> TaskResponse:
db_task = Task(title=task.title, user_id=current_user.id)
db.add(db_task)
await db.commit()
await db.refresh(db_task)
return db_task
ASYNC DATABASE SETUP
engine = create_async_engine('postgresql+asyncpg://user:pass@localhost/db')
async_session = sessionmaker(engine, class_=AsyncSession, expire_on_commit=False)
async def get_db():
async with async_session() as session:
yield session
JWT AUTHENTICATION
SECRET_KEY = 'your-secret-key'
ALGORITHM = 'HS256'
def create_access_token(data: dict, expires_delta: timedelta):
to_encode = data.copy()
to_encode.update({'exp': datetime.utcnow() + expires_delta})
return jwt.encode(to_encode, SECRET_KEY, algorithm=ALGORITHM)
ERROR HANDLING
@app.exception_handler(ValueError)
async def value_error_handler(request: Request, exc: ValueError):
return JSONResponse(status_code=400, content={'detail': str(exc)})
OPENAPI DOCUMENTATION (auto-generated)
Visible at: /docs (Swagger UI)
Includes: All endpoints, schemas, auth requirements
Export: /openapi.json for client code generationAbout this skill
Your FastAPI app freezes under load, throws MissingGreenlet the moment you touch a relationship, or quietly returns hashed_password in a JSON response. Generic answers mix Pydantic V1 and V2 syntax, put blocking calls inside async def, and share one database session across requests. This skill writes and reviews FastAPI code the way an experienced backend engineer does, and checks each route for the specific bugs that only appear in production.
What it does
- Picks
async defordeffor each route and dependency based on what it calls, so sync drivers and SDKs never block the event loop - Sets up async SQLAlchemy 2.0 correctly: one engine created in lifespan, a session per request through a
yielddependency,expire_on_commit=False, and eager loading that preventsMissingGreenlet - Writes separate Pydantic V2 Create, Update, and Read schemas with
from_attributes,field_validator, andexclude_unsetPATCH handling, so internal fields cannot leak into responses - Builds OAuth2 bearer and JWT auth as reusable
Annotateddependencies, with a pinned algorithm list, expiry checks, correct 401 vs 403 vs 404 choices, and a working approach to logout - Builds WebSocket endpoints with browser-compatible auth, disconnect handling, and a stated plan for broadcasting across multiple workers
- Reviews pasted routes and returns findings ordered by severity, each with the exact fix
What you get
Working code in the size the request needs: a single route, a full feature slice (schemas, dependency, router, test), or a ranked review of your code. Assumptions are stated up front, and the questions that matter come at the end.
Best for
Python backend developers building or maintaining FastAPI services on Postgres or MySQL, especially teams moving from Pydantic V1 or sync SQLAlchemy, or tracking down load and session bugs.
SKILL.md preview
---
name: fastapi-async-api-builder
description: Builds and debugs FastAPI services with Pydantic V2 schemas, async SQLAlchemy 2.0 sessions, JWT auth wired through dependencies, and WebSockets. Every route is checked for event-loop blocking, session lifetime bugs, and response-model leaks. Use when the user says "add a FastAPI endpoint", "set up async SQLAlchemy with FastAPI", "add JWT auth to my API", "migrate my schemas to Pydantic V2", "my FastAPI app freezes under load", "I keep getting MissingGreenlet", "my endpoint returns the password hash", or "review this FastAPI route".
---
# FastAPI Async API Builder: Pydantic V2, SQLAlchemy, JWT
… (sign up to view the full skill)More development skills
View all Development skills →Production Go: Concurrency, Services & Profiling
Production Go code with leak-free goroutines, context-correct services, wrapped errors, and pprof-driven performance fixes.
Backend Feature Build Plan
Builds one backend feature through gates: confirmed requirements, one-screen design, small tested slices, and a deploy/rollback handoff.
Consistent, Safe Application Logging
Adds structured, correlated logs with useful severity, safe fields, bounded volume, and targeted verification.
Reliable WebSocket Messaging and Scaling
Build WebSocket and Socket.IO systems with authorized rooms, reconnect recovery, bounded queues, and multi-node presence.