# FastAPI Production Rules

> Agent skill for production-grade FastAPI: layering, transactions, multi-tenancy, auth, SQLAlchemy async, ArdiQ background tasks, testing and deployment.

FastAPI Production Rules is a free AI agent skill on Agensi by tay, in APIs & Backend. It loads into your AI agent through the Agensi MCP server, always in its latest approved version.

- Price: Free
- Creator: [tay](https://www.agensi.io/creators/tay)
- Category: [APIs & Backend](https://www.agensi.io/skills/apis-backend)
- Uses: 2
- Version: 1.0
- Last updated: 2026-10-05
- Security: scan passed (2026-10-05); every new listing is also reviewed by a person
- Listing: https://www.agensi.io/skills/fastapi-production-rules
- Tags: api, fastapi, sqlalchemy, pydantic, postgresql, backend-development

## About this skill

### FastAPI Production Rules

A set of conventions, patterns, and hard rules for building production-grade FastAPI projects.

#### Structure

```
SKILL.md                               # all rules, short examples, checklists
references/
├── toolchain.md                       # uv, ruff, ty, pyproject.toml, CI
├── app-setup.md                       # settings, app factory, lifespan, middleware, CORS, OpenAPI
├── errors-and-responses.md            # exceptions, handlers, response wrappers, schemas, pagination
├── database.md                        # SQLAlchemy async, models, transactions, locking, Alembic
├── auth-and-security.md               # passwords, JWT, refresh tokens, magic links, roles, rate limits, uploads
├── logging-and-observability.md       # structlog, request context, Sentry, OpenTelemetry, health checks
├── background-tasks.md                # ArdiQ tasks, idempotency, retries, cron, outbox
├── api-patterns.md                    # idempotency keys, webhooks, streaming, outbound HTTP, SSRF, caching, audit
├── testing.md                         # testcontainers, fixtures, tenant-isolation and architecture tests
├── deployment.md                      # Dockerfile, uvicorn, migrations in the pipeline, probes
└── crud-example.md                    # a complete domain: model → schemas → service → router → tests
```

#### What it covers

- Toolchain: uv, ruff (including FastAPI-specific rules), ty, CI
- Project structure and app factory with lifespan
- Router → Service → Model separation
- One transaction per use case
- Dependency injection with `Annotated`
- Custom exceptions and one error format for every error
- Typed response wrappers and correct status codes
- Pydantic v2 schemas that prevent mass assignment
- Offset and cursor pagination with stable ordering
- Multi-tenancy and IDOR prevention
- SQLAlchemy 2.0 async: sessions, explicit loading, integrity, locking
- Zero-downtime Alembic migrations
- Configuration with pydantic-settings
- Structured logging with structlog and request IDs
- Auth: argon2, JWT, rotating refresh tokens with reuse detection, magic links
- Role-based authorization
- Rate limiting
- HTTP security: CORS, security headers, SSRF
- File upload validation
- Background tasks with ArdiQ: idempotency, retries, priorities, cron, transactional outbox
- Idempotency keys and webhooks
- Native SSE and JSON Lines streaming (FastAPI ≥ 0.135)
- Testing with real Postgres, tenant-isolation and architecture tests
- Health checks, Sentry, OpenTelemetry
- Docker and deployment
- Naming conventions
- FastAPI gotchas
- Security and code review checklists

#### Stack

Examples use PostgreSQL + SQLAlchemy 2.0 async + Pydantic v2 + [ArdiQ](https://ardiq.bytay.dev) + Redis, but every principle applies to any ORM or task queue.

#### Related

[How I structure FastAPI projects in production — and why](https://bytay.dev/blog/how-i-structure-fastapi-projects) — the post explaining the reasoning behind these rules.

[The Python Toolchain I Use in Production: uv, ruff, and ty](https://bytay.dev/blog/python-toolchain-uv-ruff-ty/) - another post explaining why i use all the astral stack (uv, ruff and ty)

## Requires

- Node.js
- Python
- pip-audit
- uv (Python tool runner)

## Known limitations

Targets Python 3.13+, async SQLAlchemy, and Pydantic v2. Uses PostgreSQL and ArdiQ rather than SQLite or Celery.

## How to use this skill

1. Connect your AI agent to Agensi once: add the MCP server https://mcp.agensi.io/mcp/auth and sign in with your Agensi account (OAuth, no API key). Steps for Claude, ChatGPT, Claude Code, Codex, Cursor, VS Code and other agents: https://www.agensi.io/docs/mcp-setup
2. Ask your agent: "Use the FastAPI Production Rules skill from Agensi" and describe your task.
3. Your agent loads the skill from Agensi when it needs it. Nothing is downloaded.

## Frequently asked questions

### What specific production challenges does this skill address for FastAPI developers?

This skill provides a comprehensive framework of production-grade conventions and patterns, covering everything from multi-tenancy and transactional integrity to ArdiQ background tasks and zero-downtime migrations.

### Which AI agents are compatible with the Fastapi Production Rules?

The skill is designed to work with any modern LLM-based agent capable of processing Markdown-based rule sets and code references, allowing the agent to generate, refactor, or audit code according to these strict standards.

### What specific files and documentation are included in the purchase?

You will receive a complete SKILL.md file containing the core rules and checklists, along with a suite of detailed reference documents covering the full stack from database architecture to deployment.

### Do I have to use the specific stack mentioned in the description to benefit from these rules?

While the examples utilize a high-performance stack (SQLAlchemy 2.0, Pydantic v2, ArdiQ, and PostgreSQL), the underlying architectural principles and security patterns are adaptable to other ORMs or task queues.

### Does this skill include guidance on handling multi-tenant architectures and security?

Yes, the skill includes specialized patterns for multi-tenancy and IDOR prevention, ensuring your agent builds applications that maintain strict data isolation between users.

### How do I integrate these rules into my current AI agent workflow?

Setup is straightforward: you provide the SKILL.md and reference directory to your AI agent's knowledge base or context window, enabling it to immediately apply these 'hard rules' to your project.

---

Source: [Agensi](https://www.agensi.io), the marketplace of skills for AI agents. Any MCP-compatible agent (Claude, ChatGPT, Claude Code, Codex, Cursor, VS Code and more) connects at https://mcp.agensi.io/mcp/auth and signs in with an Agensi account; setup for every agent: https://www.agensi.io/docs/mcp-setup. Append .md to any skill, guide or docs address on agensi.io for its markdown version.
