Skills DirectorySkills Directory
SkillsLearnSecurityCategoriesDocsCommunityBlog
Sign InSubmit Skill
Skills Directory

Security-tested agent skills for Claude, coding agents, and AI workflows.

Directory

  • Browse Skills
  • All Skills A–Z
  • Claude Skills
  • Claude Code Skills
  • Agent Skills
  • Categories
  • Authors
  • Submit a Skill

Learn

  • Learn Hub
  • Install Claude Skills
  • Write SKILL.md
  • Skills vs MCP
  • Directories Compared

Security

  • Security
  • Methodology
  • Secure Claude Skills
  • Security Badges

Company

  • About
  • Community
  • Blog
  • API Docs
  • Advertise

2026 Skills Directory. All rights reserved.

ProTermsPrivacyRefunds
Back to skills

Build Production Python Apis

ASecurity

Build fast, production-ready Python APIs with type hints, validation, and async support.

19 stars
0 votes
0 copies
1 views
Added 9/19/2026
ai-agentspythongosqlfastapitestinggitapidatabasesecuritydocumentation

Works with

cliapi

Security Analysis

A100/100

Scanned 9/19/2026

Install to Claude Code

$npx -y skills add rondoflow/rondoflow --skill build-production-python-apis --agent claude-code

Installs into .claude/skills of the current project.

Are you the author of Build Production Python Apis?

Add the live security badge to your README — it updates automatically with every re-scan.

Security grade badge for Build Production Python Apis
[![Security: A — Skills Directory](https://www.skillsdirectory.com/api/skills/rondoflow-build-production-python-apis/badge)](https://www.skillsdirectory.com/skills/rondoflow-build-production-python-apis)

More formats (shields.io, HTML) on the badges page.

Download with Pro
Files
SKILL.md
---
name: build-production-python-apis
description: "Build fast, production-ready Python APIs with type hints, validation, and async support."
category: "Development"
author: community
version: "1.0.0"
icon: code
---

# FastAPI Patterns

## Async Traps
- Mixing sync database drivers (psycopg2, PyMySQL) in async endpoints blocks the event loop — use async drivers (asyncpg, aiomysql) or run sync code in `run_in_executor`
- `time.sleep()` in async endpoints blocks everything — use `await asyncio.sleep()` instead
- CPU-bound work in async endpoints starves other requests — offload to `ProcessPoolExecutor` or background workers
- Async endpoints calling sync functions that do I/O still block — the entire call chain must be async

## Pydantic Validation
- Default values in models become shared mutable state: `items: list = []` shares the same list across requests — use `Field(default_factory=list)`
- `Optional[str]` doesn't make a field optional in the request — add `= None` or use `Field(default=None)`
- Pydantic v2 uses `model_validate()` not `parse_obj()`, and `model_dump()` not `.dict()` — v1 methods are deprecated
- Use `Annotated[str, Field(min_length=1)]` for reusable validated types instead of repeating constraints

## Dependency Injection
- Dependencies run on every request by default — use `lru_cache` on expensive dependencies or cache in app.state for singletons
- `Depends()` without an argument reuses the type hint as the dependency — clean but can confuse readers
- Nested dependencies form a DAG — if A depends on B and C, and both B and C depend on D, D runs once (cached per-request)
- `yield` dependencies for cleanup (DB sessions, file handles) — code after yield runs even if the endpoint raises

## Lifespan and Startup
- `@app.on_event("startup")` is deprecated — use `lifespan` async context manager
- Store shared resources (DB pool, HTTP client) in `app.state` during lifespan, not as global variables
- Lifespan runs once per worker process — with 4 Uvicorn workers you get 4 DB pools

```python
from contextlib import asynccontextmanager
@asynccontextmanager
async def lifespan(app):
    app.state.db = await create_pool()
    yield
    await app.state.db.close()
app = FastAPI(lifespan=lifespan)
```

## Request/Response
- Return `dict` from endpoints, not Pydantic models directly — FastAPI handles serialization and it's faster
- Use `status_code=201` on POST endpoints returning created resources — 200 is the default but semantically wrong
- `Response` with `media_type="text/plain"` for non-JSON responses — returning a string still gets JSON-encoded otherwise
- Set `response_model_exclude_unset=True` to omit None fields from response — cleaner API output

## Error Handling
- `raise HTTPException(status_code=404)` — don't return Response objects for errors, it bypasses middleware
- Custom exception handlers with `@app.exception_handler(CustomError)` — but remember they don't catch HTTPException
- Use `detail=` for user-facing messages, log the actual error separately — don't leak stack traces

## Background Tasks
- `BackgroundTasks` runs after the response is sent but still in the same process — not suitable for long-running jobs
- Tasks execute sequentially in order added — don't assume parallelism
- If a background task fails, the client never knows — add your own error handling and alerting

## Security
- `OAuth2PasswordBearer` is for documentation only — it doesn't validate tokens, you must implement that in the dependency
- CORS middleware must come after exception handlers in middleware order — or errors won't have CORS headers
- `Depends(get_current_user)` in path operation, not in router — dependencies on routers affect all routes including health checks

## Testing
- `TestClient` runs sync even for async endpoints — use `httpx.AsyncClient` with `ASGITransport` for true async testing
- Override dependencies with `app.dependency_overrides[get_db] = mock_db` — cleaner than monkeypatching
- `TestClient` context manager ensures lifespan runs — without `with TestClient(app) as client:` startup/shutdown hooks don't fire

Attribution

rondoflowrondoflow
View sourceMore from rondoflow →
SSkills DirectorySkills Directory

Ship a skill? Prove it's safe.

Free 120-pattern security scan, letter grade, and an embeddable README badge.

Submit a skill

Is this your skill, or is something wrong with this listing? Request removal or report an issue. Author removals are honored within 72 hours.

Comments (0)

No comments yet. Be the first to comment!

SSkills DirectorySkills Directory

Ship a skill? Prove it's safe.

Free 120-pattern security scan, letter grade, and an embeddable README badge.

Submit a skill

Related Skills

Caveman

Ultra-compressed communication mode that cuts output tokens while keeping technical accuracy. Levels: lite, full, ultra and the wenyan variants. Use for /caveman, "caveman mode", "talk like caveman", "be brief" or "less tokens".

1074701 votes

Hyperplan

Adversarial multi-agent planning skill. Self-orchestrates 5 hostile category members (unspecified-low, unspecified-high, deep, ultrabrain, artistry) via team-mode for ruthless cross-critique debate, distills only the defensible insights, then MANDATORILY hands the distilled insight bundle to the `plan` agent for executable plan formalization. Use when planning needs maximum rigor and surfacing of weak assumptions, blind spots, and over-engineering. Triggers: 'hyperplan', 'hpp', '/hyperplan', ...

693621 votes

Mcp Code Execution

Routes multi-tool workflows through MCP servers for large datasets and pipelines. Use when Bash tool overhead is limiting throughput on data-heavy tasks.

3351 votes

catchup

Recovers the conversation and failed tool calls of a previous Codex, Claude Code, Antigravity, Cline, Copilot CLI, Cursor, DeepSeek Harness, Kimi, OpenCode, Pi Agent, or ZCode session. Use when the user says "catch up", "what did the last session do", "get me up to speed", "I switched agents", asks to recover/summarize a previous session before continuing, or asks to diagnose or report a catchup failure. Do NOT use for the current conversation, git history, or any non-agent log.

691 votes

math-skill

A comprehensive mathematical reasoning skill for AI assistants — handles arithmetic to research-level problems with rigorous step-by-step reasoning, systematic verification, and transparent uncertainty handling

381 votes
View all in ai-agents →