fastapi
FastAPI modern Python web framework. Covers routing, Pydantic models, dependency injection, and async support. Use when building Python APIs. USE WHEN: user mentions "fastapi", "pydantic", "async python api", "python rest api", asks about "dependency injection python", "python openapi", "python swagger", "async endpoints", "python api validation", "fastapi middleware" DO NOT USE FOR: Django apps - use `django` instead, Flask apps - use `flask` instead, synchronous Python APIs without type hints, GraphQL-only APIs
What this skill does
# FastAPI Core Knowledge
> **Full Reference**: See [advanced.md](advanced.md) for WebSocket integration including connection management, authentication, room management, Pydantic message protocols, heartbeat, Redis pub/sub scaling, and background tasks.
> **Deep Knowledge**: Use `mcp__documentation__fetch_docs` with technology: `fastapi` for comprehensive documentation.
## Basic Setup
```python
from fastapi import FastAPI, HTTPException, Depends
from pydantic import BaseModel, EmailStr
app = FastAPI(title="My API")
class UserCreate(BaseModel):
name: str
email: EmailStr
class User(UserCreate):
id: int
class Config:
from_attributes = True
```
## Route Patterns
```python
@app.get("/users", response_model=list[User])
async def get_users(skip: int = 0, limit: int = 100):
return await db.users.find_many(skip=skip, limit=limit)
@app.get("/users/{user_id}", response_model=User)
async def get_user(user_id: int):
user = await db.users.find(user_id)
if not user:
raise HTTPException(status_code=404, detail="User not found")
return user
@app.post("/users", response_model=User, status_code=201)
async def create_user(user: UserCreate):
return await db.users.create(user.model_dump())
```
## Dependency Injection
```python
async def get_db():
db = SessionLocal()
try:
yield db
finally:
db.close()
async def get_current_user(token: str = Depends(oauth2_scheme)):
user = await verify_token(token)
if not user:
raise HTTPException(status_code=401, detail="Invalid token")
return user
@app.get("/me", response_model=User)
async def get_me(user: User = Depends(get_current_user)):
return user
```
## Key Features
- Auto OpenAPI/Swagger docs at `/docs`
- Pydantic validation
- Async support
- Type hints everywhere
## When NOT to Use This Skill
- **Django projects** - Django has its own ORM, admin, templates
- **Flask microservices** - Flask is lighter without type validation overhead
- **Synchronous WSGI apps** - FastAPI is async-first
- **Legacy Python 2.x** - FastAPI requires Python 3.7+
- **Non-REST APIs** - Use dedicated GraphQL or gRPC frameworks
## Anti-Patterns
| Anti-Pattern | Why It's Bad | Solution |
|--------------|--------------|----------|
| `def` instead of `async def` | Blocks event loop | Use `async def` for I/O operations |
| Missing `response_model` | No output validation | Always specify `response_model` |
| Sync database calls | Blocks workers | Use async drivers (asyncpg, motor) |
| Global state without locks | Race conditions | Use `asyncio.Lock` or `Depends()` |
| Raising exceptions without HTTPException | Generic 500 errors | Use `HTTPException` with status codes |
| No input validation | Security vulnerabilities | Use Pydantic models with validators |
## Quick Troubleshooting
| Problem | Diagnosis | Fix |
|---------|-----------|-----|
| "RuntimeError: no running event loop" | Calling async from sync code | Use `await` or `asyncio.run()` |
| Validation errors not clear | Missing field descriptions | Add `Field(description=...)` |
| Slow response times | Sync database calls | Switch to async SQLAlchemy |
| CORS errors in browser | Missing middleware | Add `CORSMiddleware` |
| Dependency not injected | Wrong import or syntax | Check `Depends()` syntax |
## Production Readiness
### Security Configuration
```python
from fastapi.middleware.cors import CORSMiddleware
from slowapi import Limiter
app = FastAPI(
title="My API",
docs_url="/docs" if os.getenv("ENV") != "production" else None,
)
limiter = Limiter(key_func=get_remote_address)
app.state.limiter = limiter
app.add_middleware(
CORSMiddleware,
allow_origins=os.getenv("ALLOWED_ORIGINS", "").split(","),
allow_credentials=True,
allow_methods=["GET", "POST", "PUT", "DELETE", "PATCH"],
allow_headers=["*"],
)
```
### Health Checks
```python
@app.get("/health")
async def health():
return {"status": "healthy"}
@app.get("/ready")
async def readiness(db: Session = Depends(get_db)):
try:
db.execute("SELECT 1")
return {"status": "ready", "database": "connected"}
except Exception:
return JSONResponse(status_code=503, content={"status": "not ready"})
```
### Graceful Shutdown
```python
from contextlib import asynccontextmanager
@asynccontextmanager
async def lifespan(app: FastAPI):
await database.connect()
yield
await database.disconnect()
app = FastAPI(lifespan=lifespan)
```
### Monitoring Metrics
| Metric | Alert Threshold |
|--------|-----------------|
| Request latency p99 | > 500ms |
| Error rate (5xx) | > 1% |
| Memory usage | > 80% |
| Worker utilization | > 90% |
### Checklist
- [ ] CORS properly configured
- [ ] Rate limiting enabled
- [ ] Security headers middleware
- [ ] Pydantic validation on all inputs
- [ ] Health/readiness/liveness endpoints
- [ ] Structured logging (JSON format)
- [ ] Global exception handler
- [ ] Secrets via environment variables
- [ ] Docs disabled in production
- [ ] Gunicorn with multiple workers
- [ ] Graceful shutdown handling
## Reference Documentation
- [Pydantic Models](quick-ref/pydantic.md)
- [Dependencies](quick-ref/dependencies.md)
Related in Backend & APIs
jfrog
IncludedInteract with the JFrog Platform via the JFrog CLI and REST/GraphQL APIs. Use this skill when the user wants to manage Artifactory repositories, upload or download artifacts, manage builds, configure permissions, manage users and groups, work with access tokens, configure JFrog CLI servers, search artifacts, manage properties, set up replication, manage JFrog Projects, run security audits or scans, look up CVE details, query exposures scan results from JFrog Advanced Security, manage release bundles and lifecycle operations, aggregate or export platform data, or perform any JFrog Platform administration task. Also use when the user mentions jf, jfrog, artifactory, xray, distribution, evidence, apptrust, onemodel, graphql, workers, mission control, curation, advanced security, exposures, or any JFrog product name.
cupynumeric-migration-readiness
IncludedPre-migration readiness assessor for porting NumPy to cuPyNumeric. Use BEFORE substantial porting work begins when the user asks whether code will scale on GPU, whether they should migrate to cuPyNumeric, which NumPy patterns transfer cleanly, what must be refactored before porting, or mentions pre-port assessment, scaling analysis, or refactor planning. Inspect the user's source code, look up NumPy usage, cross-reference the cuPyNumeric API support manifest, and distinguish distributed-scaling-friendly patterns from blockers such as unsupported APIs, scalar synchronization, host round-trips, Python/object-heavy control flow, shape/data-dependent branching, and in-place mutation hazards. Produce a verdict of READY, LIGHT REFACTOR, SIGNIFICANT REFACTOR, or NOT RECOMMENDED, with concrete refactor pointers.
alibabacloud-data-agent-skill
IncludedInvoke Alibaba Cloud Apsara Data Agent for Analytics via CLI to perform natural language-driven data analysis on enterprise databases. Data Agent for Analytics is an intelligent data analysis agent developed by Alibaba Cloud Database team for enterprise users. It automatically completes requirement analysis, data understanding, analysis insights, and report generation based on natural language descriptions. This tool supports: discovering data resources (instances/databases/tables) managed in DMS, initiating query or deep analysis sessions, real-time progress tracking, and retrieving analysis conclusions and generated reports. Use this Skill when users need to query databases, analyze data trends, generate data reports, ask questions in natural language, or mention "Data Agent", "data analysis", "database query", "SQL analysis", "data insights".
token-optimizer
IncludedReduce OpenClaw token usage and API costs through smart model routing, heartbeat optimization, budget tracking, and native 2026.2.15 features (session pruning, bootstrap size limits, cache TTL alignment). Use when token costs are high, API rate limits are being hit, or hosting multiple agents at scale. The 4 executable scripts (context_optimizer, model_router, heartbeat_optimizer, token_tracker) are local-only — no network requests, no subprocess calls, no system modifications. Reference files (PROVIDERS.md, config-patches.json) document optional multi-provider strategies that require external API keys and network access if you choose to use them. See SECURITY.md for full breakdown.
resend-cli
IncludedUse this skill when the task is specifically about operating Resend from an AI agent, terminal session, or CI job via the official resend CLI: installing/authenticating the CLI, sending/listing/updating/cancelling emails, batch sends, domains and DNS, webhooks and local listeners, inbound receiving, contacts, topics, segments, broadcasts, templates, API keys, profiles, or debugging Resend CLI/API failures. Trigger on mentions of Resend CLI, `resend`, `resend doctor`, `resend emails send`, `resend domains`, `resend webhooks listen`, `resend emails receiving`, or agent-friendly terminal automation.
alibabacloud-odps-maxframe-coding
IncludedUse this skill for MaxFrame SDK development and documentation navigation on Alibaba Cloud MaxCompute (ODPS). Helps answer MaxFrame API, concept, official example, and supported pandas API questions; create data processing programs; read/write MaxCompute tables; debug jobs (remote or local); and build custom DPE runtime images. Trigger when users mention MaxFrame, MaxCompute with MaxFrame, ODPS table processing, DPE runtime, MaxFrame docs/examples, DataFrame/Tensor operations, or GPU runtime setup. Works for both English and Chinese queries about Alibaba Cloud data processing with MaxFrame.