HomeBlogFastAPI AI Prompts: Build Production Python APIs 1…
Programming19 min read · May 10, 2026

FastAPI AI Prompts: Build Production Python APIs 10x Faster in 2026

By Promptprepare Team · AI Prompt Experts

Complete AI prompt library for FastAPI developers. Covers project structure, Pydantic v2 models, async SQLAlchemy, OAuth2 JWT authentication, background tasks, pytest testing, Docker deployment, and performance optimization — all production-ready with good vs bad prompt examples.

#FastAPI#Python#Pydantic#SQLAlchemy#AI Coding Prompts#Backend

FastAPI in 2026: The Production-First Python API Framework

FastAPI has become the default choice for Python APIs requiring high performance, automatic OpenAPI documentation, and strong type safety. Its async support, Pydantic v2 integration, and dependency injection system make it ideal for microservices, ML model serving, and data platform APIs. The developers building the most maintainable FastAPI applications use AI prompts that specify the full type contract, async pattern, and security requirements upfront — not as afterthoughts.

Every prompt here is written for FastAPI 0.115+, Pydantic v2, SQLAlchemy 2.0 async, Python 3.12+. They produce code that passes mypy strict mode and is ready for a production code review.

1. Project Structure for a Production FastAPI Application

You are a senior Python backend architect specializing in FastAPI production systems.

Design the directory structure for a FastAPI SaaS API with:
- Domain-driven structure: users, organizations, projects, tasks, billing domains
- Async SQLAlchemy 2.0 with PostgreSQL (asyncpg driver)
- Redis for caching and rate limiting (redis-py async)
- Celery + Redis for background job processing
- JWT authentication with role-based access control
- Alembic for database migrations
- pytest for testing with async support

Deliver:
1. Full directory tree with a one-sentence purpose for each file
2. Dependency injection architecture (where database sessions, current user, and permissions are resolved)
3. Settings management pattern (Pydantic Settings from environment variables)
4. The lifespan() pattern for startup/shutdown (not deprecated @app.on_event)
5. pyproject.toml with dependencies grouped by purpose (core, db, testing, dev)

2. Pydantic v2 Schema Design

Pydantic v2 is a breaking change from v1. Most AI-generated code defaults to v1 syntax unless you specify otherwise.

You are a Pydantic v2 expert.

Create a complete schema set for a Task resource in a FastAPI application. Use Pydantic v2 throughout:

Schemas needed:
- TaskBase: shared fields with field validators
- TaskCreate(TaskBase): input schema for POST /tasks
- TaskUpdate: all fields Optional with model_validator for at-least-one-field validation
- TaskResponse(TaskBase): output schema with computed_field for is_overdue, days_until_due
- TaskListResponse: paginated wrapper with items: list[TaskResponse], total, page, page_size, has_next

Pydantic v2 requirements:
- model_config = ConfigDict(from_attributes=True, populate_by_name=True)
- Field validators with @field_validator (not v1 @validator)
- Cross-field validation with @model_validator(mode='after')
- Proper use of Annotated types for reusable validation (e.g., PositiveInt, NonEmptyString)
- JSON schema customization for OpenAPI (json_schema_extra on Fields)
- Serialization aliases where API field names differ from Python names (camelCase output for JS clients)

Show: all 5 schema classes, a custom type alias, and one example of model_validate(orm_obj) from a SQLAlchemy model.

Why it works: Specifying model_config, field_validator, and model_validator explicitly prevents the AI from generating v1 syntax that will cause runtime errors in a v2 environment.

3. Async SQLAlchemy Models & Repository Pattern

You are a SQLAlchemy 2.0 async expert.

Design SQLAlchemy 2.0 ORM models for a multi-tenant project management database:
Entities: Organization, User, Project, Task, Comment, AuditLog

Requirements:
- SQLAlchemy 2.0 mapped_column() syntax (not the legacy Column())
- Async session: AsyncSession from sqlalchemy.ext.asyncio
- Soft deletes: deleted_at: Mapped[Optional[datetime]] column on all main entities
- Audit mixin: TimestampMixin with created_at, updated_at (server_default + onupdate)
- Tenant isolation: organization_id indexed on every entity
- Relationships: selectin loading strategy for frequently accessed relationships, lazy for others
- Repository pattern: TaskRepository class with async methods (get_by_id, list_paginated, create, update, soft_delete)
- Connection pooling: asyncpg pool with pool_size=20, max_overflow=40, pool_pre_ping=True

Output: models.py, mixins.py, repository/task_repository.py with full async implementations, and the async session dependency (get_db) for FastAPI.

4. Full CRUD Router with Dependency Injection

You are a FastAPI routing expert building production APIs.

Generate a complete FastAPI router for the Task resource with full dependency injection:

Endpoints:
- GET /tasks — paginated list (skip, limit, status filter, assignee filter, due_date range)
- GET /tasks/{task_id} — single task with nested project and assignee
- POST /tasks — create task
- PATCH /tasks/{task_id} — partial update (TaskUpdate schema)
- DELETE /tasks/{task_id} — soft delete
- POST /tasks/{task_id}/assign — assign task to user

Dependencies required (via Depends()):
- get_db: AsyncSession (from lifespan connection pool)
- get_current_user: User (decode JWT, load from DB, cache in request state)
- require_permission("tasks:write"): raise 403 if insufficient role
- get_organization: Organization (extract from current_user, validate active)
- rate_limiter(10, "minute"): 10 requests per minute per user

Response models: use TaskResponse for single, TaskListResponse for lists.
HTTP status codes: 201 for POST, 204 for DELETE, 409 for version conflict.
Always scope queries to current_user.organization_id — never trust URL parameters for tenant.

5. OAuth2 JWT Authentication System

You are a Python security engineer specializing in FastAPI authentication.

Build a complete OAuth2 JWT authentication system for FastAPI:

Token strategy:
- Access tokens: RS256 (python-jose with RSA keys loaded from env), 15-minute expiry
- Refresh tokens: opaque tokens stored in Redis (uuid4 key, user_id value), 7-day TTL
- Refresh token rotation: invalidate old token, issue new token on each refresh
- Token reuse detection: if a used refresh token is presented, blacklist all user tokens and log security event

Endpoints:
- POST /auth/register: create user, hash password with bcrypt (rounds=12), send verification email via Celery task
- POST /auth/login: OAuth2PasswordRequestForm, bcrypt compare, issue both tokens
- POST /auth/refresh: validate Redis token, rotate, return new pair
- POST /auth/logout: invalidate refresh token from Redis
- GET /auth/me: return current user from JWT (no DB hit, use JWT claims)

Security:
- Rate limit: 5 auth attempts per 15 minutes per IP (using slowapi)
- No user enumeration: return identical 401 for wrong email and wrong password
- Password validation: minimum 12 chars, at least 1 uppercase, 1 number, 1 special char

Output: auth/router.py, auth/dependencies.py, auth/token_service.py (Redis ops), auth/security.py (bcrypt + JWT utils). Full type hints.

Why it works: "No user enumeration" and "identical 401 response" are security requirements that dramatically reduce account discovery attacks. They're easy to specify and easy to miss without explicit prompting.

6. Background Tasks with Celery

You are a Celery expert building async task systems for FastAPI applications.

Build a Celery worker setup for a FastAPI application with these task categories:

Email tasks (high priority queue):
- send_welcome_email(user_id: str): fetch user, render Jinja2 template, send via Resend API
- send_task_assignment_notification(task_id: str, assignee_id: str): notify assignee
- send_overdue_warning(task_id: str): daily digest of overdue tasks

Data processing tasks (default queue):
- generate_project_report(project_id: str, format: str): query DB, generate PDF/CSV, upload to S3, notify user
- process_bulk_import(file_key: str, org_id: str): parse CSV, validate rows, batch insert to DB

Scheduled tasks (beat schedule):
- cleanup_expired_tokens(): hourly — delete expired Redis refresh tokens
- send_weekly_digest(): weekly Monday 9am UTC — per-organization summary email

Requirements:
- Celery with Redis broker and result backend
- Task retry with exponential backoff: max_retries=3, default_retry_delay=60
- Task monitoring: Flower dashboard configuration
- Type-safe task signatures with TypedDict for arguments
- Dead letter queue for permanently failed tasks

Output: celery_app.py, tasks/ folder structure, beat_schedule config, and Flower setup.

7. Alembic Database Migrations

You are a database migration expert for SQLAlchemy and Alembic.

Set up Alembic for an async SQLAlchemy FastAPI application with:

Configuration:
- Async migration runner (run_async_migrations with asyncpg)
- Auto-generate migrations from SQLAlchemy models
- Per-environment URLs loaded from Pydantic Settings (not hardcoded in alembic.ini)
- Separate migration folders per domain (users/, projects/, etc.) for clean git history

Migration best practices:
- Data migrations vs schema migrations: explain when to use separate migration scripts
- Reversible migrations: every op.add_column() paired with op.drop_column() in downgrade()
- Index creation with CONCURRENTLY (PostgreSQL only): explain why this is critical on large tables and how to implement in Alembic
- Zero-downtime column additions: 3-phase pattern (add nullable → backfill data → add NOT NULL constraint)
- Testing migrations: pytest fixture that runs all migrations up and down in a test database

Output: alembic.ini, env.py (async), an example migration file, and the pytest migration fixture.

8. pytest Testing with Async Support

You are a pytest expert for async FastAPI applications.

Build a comprehensive test suite setup for a FastAPI application:

Fixtures (conftest.py):
- async_client: httpx AsyncClient with test app instance (not TestClient — explain why)
- db_session: AsyncSession pointing to a test database (postgresql+asyncpg, rolled back after each test)
- test_user: factory fixture that creates a user + returns auth headers
- test_organization: factory with org + admin user + member user
- mock_redis: fakeredis AsyncRedis instance
- mock_celery: celery.task.apply_async always_eager=True

Write tests for POST /tasks endpoint:
1. 201: successful creation — assert response fields and DB record
2. 400: title missing — assert Zod-equivalent Pydantic validation error format
3. 400: dueDate in past — assert field-level error
4. 401: no token — assert 401 + WWW-Authenticate header
5. 401: expired token — assert 401 + error code 'token_expired'
6. 403: member trying to access admin-only org — assert 403
7. 422: invalid task_id UUID format — assert FastAPI 422 response
8. 429: rate limit exceeded — assert 429 + Retry-After header

Use pytest-asyncio with asyncio_mode='auto'. Parametrize validation tests.

9. FastAPI Performance Optimization

You are a FastAPI performance engineer.

This GET /api/tasks endpoint returns in 1,600ms average. Here is the code:

[PASTE ENDPOINT CODE + SQLALCHEMY QUERIES HERE]

Diagnose and fix these performance categories:

1. N+1 query pattern: identify if relationship loading is causing individual SELECT per row — fix with selectinload() or joinedload()
2. Sequential awaits: convert await query1 + await query2 + await query3 into asyncio.gather()
3. Over-fetching: replace SELECT * with specific column selection using load_only()
4. Missing index: identify the WHERE clause columns that lack an index — provide the CREATE INDEX statement
5. Pydantic serialization cost: identify if from_orm is called on thousands of objects — use model.model_construct() for validated-at-write data
6. Response caching: add Redis caching for queries that run identically >100 times per minute (TTL strategy)

For each issue: before code, after code, estimated latency improvement, and a k6 load test snippet to validate.

10. Docker Production Setup for FastAPI

You are a Python DevOps engineer.

Write a production Docker setup for a FastAPI application with Celery workers:

Dockerfile (FastAPI API):
- Base: python:3.12-slim-bookworm
- Use uv for dependency management (faster than pip)
- Multi-stage: deps stage (install to /opt/venv), production stage (copy venv, never install dev deps)
- Non-root user: appuser (UID 1001)
- Gunicorn + uvicorn workers: formula: workers = (2 * CPU_CORES) + 1
- Health check: GET /health returns { status: 'ok', db: 'ok', redis: 'ok' }

docker-compose.yml for production-like local development:
- api service (FastAPI + Gunicorn)
- worker service (Celery, same image, different command)
- beat service (Celery Beat scheduler)
- flower service (Celery monitoring)
- postgres:16 with persistent volume and pg_stat_statements enabled
- redis:7-alpine with AOF persistence

Include: .dockerignore, environment variable handling (never hardcode secrets), and a one-command startup script that runs migrations before starting the API.

Good vs Bad FastAPI Prompts

Task❌ Bad Prompt✅ Good Prompt
Pydantic schemas "Create a Task schema" "Create Pydantic v2 TaskCreate and TaskResponse schemas. TaskResponse needs from_attributes=True, a computed_field for is_overdue, and serialization aliases for camelCase output. Use Annotated[str, StringConstraints(min_length=3)] for title."
Database queries "Query tasks from the database" "Write an async SQLAlchemy 2.0 query using AsyncSession: fetch all Tasks for organization_id with status='in_progress', selectinload(Task.assignee), order by due_date ASC, paginate with offset/limit. Return List[Task]."
Authentication "Add JWT auth to FastAPI" "Add OAuth2PasswordBearer JWT auth to FastAPI with RS256 signing, 15-min access token, opaque refresh token stored in Redis with 7-day TTL, and a get_current_user dependency that raises 401 on expiry and 403 on inactive account. Python 3.12, python-jose."
Testing "Write tests for my endpoint" "Write pytest-asyncio tests for POST /tasks using httpx AsyncClient. Fixtures: async test DB session (rolled back after each test), test_user with auth headers, fakeredis. Cover: 201 happy path, 400 Pydantic validation, 401 missing token, 403 wrong org, 429 rate limit."
Performance "Make my FastAPI app faster" "My GET /tasks takes 1.4s. Here's the route: [CODE]. Check for: N+1 SQLAlchemy relationships (fix with selectinload), sequential awaits (fix with asyncio.gather), missing indexes on WHERE clause columns, and Pydantic serialization cost on large result sets."

Generate a custom FastAPI prompt for your exact stack → Try PromptPrepare free

Found this helpful? Share it.