ShortIQ

ShortIQ

AI

50 AI Prompts for Python and FastAPI Development

Developer-tested AI prompts for FastAPI, Pydantic, SQLAlchemy, async Python, JWT auth, pytest, background tasks, and production deployment. Build Python APIs faster with copy-paste prompts.

June 29, 2026ShortIQ Editorial Team

Why Python and FastAPI Developers Benefit from AI Prompts

FastAPI is one of the fastest-growing Python web frameworks because it combines automatic OpenAPI documentation, native async support, and Pydantic data validation in a single package. The framework has strong conventions that AI models can follow well when given enough context — but without the right prompt structure, models often produce synchronous Flask-style code or miss Pydantic v2 syntax differences.

The most valuable AI use cases in FastAPI development are generating Pydantic models from a data description, writing dependency injection patterns for auth and database sessions, producing pytest test cases for endpoint behavior, and scaffolding async background tasks. The prompts in this guide cover all of these patterns with the context structure that produces accurate output.

  • Generate Pydantic v2 models with validators, field aliases, and computed fields
  • Build FastAPI routers with dependency injection for auth and database sessions
  • Write SQLAlchemy 2.0 async queries with correct session management
  • Scaffold Alembic migrations from SQLAlchemy model changes
  • Generate pytest tests for FastAPI endpoints with the TestClient

FastAPI Project Setup and Router Structure Prompts

A well-structured FastAPI project separates routers by domain, uses a dependency injection pattern for shared resources, and includes a lifespan context manager for startup and shutdown events. These prompts generate the initial project scaffold with the correct file layout and import patterns.

Always specify the Python version, whether you are using async or sync endpoints, and your database choice. FastAPI supports both synchronous and asynchronous handlers, and the ORM patterns differ significantly between the two. Specifying async avoids the model generating synchronous SQLAlchemy patterns that do not work with an async event loop.

text
Act as a FastAPI expert.

Task:
Scaffold a FastAPI project with the following structure and configuration.

Project structure:
app/
  main.py          # FastAPI app instance, lifespan, include_router calls
  config.py        # Settings class using pydantic-settings and .env
  database.py      # SQLAlchemy async engine and get_db dependency
  routers/
    users.py       # /users routes
    auth.py        # /auth/login, /auth/refresh routes
  models/
    user.py        # SQLAlchemy User model
  schemas/
    user.py        # Pydantic request and response schemas
  dependencies/
    auth.py        # get_current_user dependency

Tech stack: Python 3.12, FastAPI, SQLAlchemy 2.0 async, PostgreSQL, pydantic-settings
Include: pyproject.toml with all dependencies

Pydantic Models and Data Validation Prompts

Pydantic v2 is significantly faster than v1 and has breaking syntax changes. Models now use model_validator instead of root_validator, field_validator instead of validator, and the Config class is replaced by model_config with ConfigDict. AI models that have not updated their training data still generate Pydantic v1 syntax. Specify Pydantic v2 explicitly in every prompt.

These prompts generate Pydantic schemas for request validation, response serialization, nested models, custom validators, and computed fields. Include your exact field requirements and any validation rules in the prompt for accurate output.

text
Act as a Pydantic v2 expert.

Task:
Create Pydantic schemas for a user management API.

Schemas needed:
1. UserCreate: email (valid email), password (min 8 chars, at least 1 digit),
   name (min 2 chars), role (Literal admin, user, viewer — default user)

2. UserUpdate: all fields optional, same validation rules when provided

3. UserResponse: id (UUID), email, name, role, createdAt (datetime),
   isActive (bool) — exclude password from response

4. UserListResponse: items (list of UserResponse), total (int),
   page (int), limit (int)

Requirements:
- Use Pydantic v2 syntax (model_config, field_validator, not v1 validators)
- Email must be lowercased and stripped in a field_validator
- UserResponse must use model_config with from_attributes=True for ORM mode
- Use UUID type for id, datetime for timestamps

SQLAlchemy 2.0 and Alembic Prompts

SQLAlchemy 2.0 introduced a new query API that replaces the legacy session.query() pattern with select() statements, and added first-class support for async sessions via AsyncSession. Many AI models still generate the older SQLAlchemy 1.x query style. Specifying SQLAlchemy 2.0 async in the prompt switches the model to the correct patterns.

Alembic handles database migrations for SQLAlchemy projects. These prompts generate the SQLAlchemy model definitions, async CRUD repository classes, and Alembic migration configuration for common database schemas.

text
Act as a SQLAlchemy 2.0 async and Alembic expert.

Task:
Write the SQLAlchemy model and async CRUD repository for a User entity.

User model fields:
- id: UUID, primary key, server default gen_random_uuid()
- email: String(255), unique, not null, indexed
- hashed_password: String(255), not null
- name: String(100), not null
- role: Enum (admin, user, viewer), default user
- is_active: Boolean, default True
- created_at: DateTime with timezone, server default now()
- updated_at: DateTime with timezone, onupdate now()

CRUD repository methods:
- get_by_id(db, user_id) -> User | None
- get_by_email(db, email) -> User | None
- create(db, data: UserCreate) -> User
- update(db, user_id, data: UserUpdate) -> User | None
- delete(db, user_id) -> bool
- list_users(db, skip, limit) -> tuple[list[User], int]

Use: SQLAlchemy 2.0, AsyncSession, select() API, Python 3.12

JWT Authentication and Security Prompts

FastAPI dependency injection makes JWT authentication clean — a single get_current_user dependency reads the token from the Authorization header, validates it, and returns the user object. Endpoints that require auth simply declare the dependency in their function signature.

These prompts generate the full auth flow: password hashing with bcrypt, JWT token creation and validation with python-jose or PyJWT, a login endpoint that returns access and refresh tokens, a token refresh endpoint, and the get_current_user dependency with role-based access control.

text
Act as a FastAPI security expert.

Task:
Implement JWT authentication for a FastAPI application.

Requirements:
1. Password hashing: use passlib with bcrypt, verify_password and get_password_hash helpers

2. JWT tokens:
   - Access token: expires in 15 minutes, contains sub (user_id) and role
   - Refresh token: expires in 7 days, stored hash in database for rotation
   - Use PyJWT, secret from settings, algorithm HS256

3. Auth router:
   - POST /auth/login: accepts email and password, returns access_token and refresh_token
   - POST /auth/refresh: accepts refresh_token cookie, returns new access_token
   - POST /auth/logout: revokes refresh token

4. Dependencies:
   - get_current_user: reads Bearer token, returns User from DB or raises 401
   - require_admin: depends on get_current_user, raises 403 if role is not admin

Use: FastAPI, PyJWT, passlib, SQLAlchemy 2.0 async, Python 3.12

Async Background Tasks and Celery Prompts

FastAPI has built-in support for background tasks via the BackgroundTasks parameter — these run after the HTTP response is sent and are suitable for non-critical fire-and-forget operations like sending welcome emails. For heavy, long-running, or retry-critical work, Celery with Redis or RabbitMQ as a broker is the production choice.

These prompts cover both patterns: FastAPI BackgroundTasks for lightweight async work, and Celery task definitions with delay() calls, retry logic, and beat schedules for periodic tasks.

text
Act as a FastAPI and Celery expert.

Task:
Set up Celery with FastAPI for background task processing.

Architecture:
- Celery broker: Redis
- Celery result backend: Redis
- FastAPI triggers Celery tasks on certain API events

Tasks to implement:
1. send_welcome_email(user_id, email): send email after user registration
   - Retry up to 3 times on failure with 60 second delay

2. generate_monthly_report(tenant_id): heavy data aggregation
   - Time limit: 300 seconds
   - Runs on a dedicated queue: reports

3. cleanup_expired_tokens(): scheduled task, runs every hour
   - Uses Celery beat schedule

Provide:
- celery_app.py with Redis config and beat schedule
- Each task function with retry and error handling
- How to call the tasks from FastAPI route handlers

Use: FastAPI, Celery 5, Redis, Python 3.12

Testing FastAPI with Pytest Prompts

FastAPI has excellent test support through the TestClient (synchronous) and AsyncClient from httpx (asynchronous). Pytest fixtures handle database setup and teardown, while dependency overrides replace real services with mocks during testing.

These prompts generate pytest test files for FastAPI endpoints including fixtures for the test database, auth token helpers, and parametrized test cases for validation errors, success cases, and permission checks.

text
Act as a FastAPI and pytest expert.

Task:
Write pytest tests for a FastAPI users API.

Endpoints to test:
- POST /users (create user, admin only)
- GET /users (list users, admin only)
- GET /users/{user_id} (get user, authenticated)
- PUT /users/{user_id} (update user, admin or own account)
- DELETE /users/{user_id} (delete user, admin only)

Test scenarios per endpoint:
- Success case with valid data and correct auth
- 401 when no token is provided
- 403 when token has insufficient role
- 422 when request body fails Pydantic validation
- 404 when resource does not exist

Provide:
- conftest.py with: async test database setup, user factory fixture,
  auth token fixture for user and admin roles, override_get_db fixture
- test_users.py with all test cases

Use: pytest, pytest-asyncio, httpx AsyncClient, SQLAlchemy 2.0 async, Python 3.12

FastAPI Deployment and Production Optimization Prompts

FastAPI runs on any ASGI server — Uvicorn for development and Gunicorn with Uvicorn workers for production. The standard production setup is Gunicorn managing multiple Uvicorn worker processes, behind an Nginx reverse proxy with TLS termination.

These prompts cover the production deployment configuration including the Gunicorn command with the correct worker class, the Nginx configuration for proxying to FastAPI, the Dockerfile for containerization, and environment variable management with pydantic-settings.

text
Act as a FastAPI production deployment expert.

Task:
Set up production deployment for a FastAPI application.

Provide:
1. Dockerfile:
   - Multi-stage: builder installs dependencies, runtime copies app only
   - Base image: python:3.12-slim
   - Run as non-root user
   - Use uv for fast dependency installation
   - Entry point: gunicorn with uvicorn worker class, 4 workers

2. gunicorn.conf.py:
   - workers: (2 * CPU cores) + 1
   - worker_class: uvicorn.workers.UvicornWorker
   - timeout: 120
   - keepalive: 5
   - access log format with request duration

3. Nginx config:
   - Proxy to FastAPI on port 8000
   - Set X-Forwarded-For and X-Real-IP headers
   - Gzip compression for JSON responses
   - Rate limiting: 100 requests per minute per IP

4. Health check endpoint: GET /health returns {status: ok, version: str}

Also show the docker-compose.yml for local development.

FAQ

What is the best way to use AI for FastAPI development?

Specify the Python version, FastAPI version, Pydantic v2 (not v1), whether you are using async or sync, and your database (PostgreSQL with SQLAlchemy 2.0 is the most common). Without this context, AI generates outdated patterns like Pydantic v1 validators or the SQLAlchemy session.query() style.

Can AI generate Pydantic models from a description?

Yes. Describe each field with its type, validation rules, and any default values. Specify Pydantic v2 explicitly since AI models frequently default to v1 syntax. The prompt in Section 3 shows the exact pattern for generating request, update, and response schemas with validators and ORM mode.

How do I prompt AI for FastAPI JWT authentication?

Describe the token structure (access token duration, refresh token strategy), the login and refresh endpoints, and the dependency functions needed. Specify whether you want PyJWT or python-jose, and whether refresh tokens should be stored in the database for rotation. The prompt in Section 5 covers the complete auth flow.

Can AI help write pytest tests for FastAPI endpoints?

Yes. Provide the endpoint paths, the request schemas, the auth requirements, and the list of test scenarios (success, 401, 403, 422, 404). AI generates the conftest.py fixtures and the test file together. Specify pytest-asyncio and httpx AsyncClient for async endpoints — the synchronous TestClient does not handle async database sessions correctly.

How do I use AI for SQLAlchemy 2.0 async queries?

Specify SQLAlchemy 2.0 and AsyncSession in the prompt. Describe the model, the query you need, and any filters, ordering, or joins. Mention whether you need a count alongside the results. The prompt in Section 4 shows the correct select() API pattern for async queries.

What is the difference between FastAPI and Flask?

FastAPI is async-first, uses Pydantic for automatic request validation and serialization, generates OpenAPI documentation automatically, and has built-in dependency injection. Flask is synchronous by default, has no built-in validation, and requires extensions for features FastAPI includes out of the box. FastAPI is the better choice for new APIs; Flask has a larger extension ecosystem.

Can AI help deploy FastAPI to production?

Yes. Describe your deployment target (VPS with Nginx, Docker, AWS Lambda, Railway, Render) and AI generates the Dockerfile, Gunicorn configuration, Nginx proxy config, and environment variable setup. The prompt in Section 8 covers the complete production stack for a VPS deployment.

Do these prompts work with Python type hints?

All prompts in this guide target Python 3.12 with full type hints. FastAPI and Pydantic are built around Python type annotations — specifying the types in your prompt descriptions leads to accurate typed code. For older Python versions, replace the newer type syntax (list[str] instead of List[str]) in the prompts and specify your Python version.

Related free tools

If you want to turn this topic into action, use one of ShortIQ's free tools for campaign planning, UTM structure, or QR distribution.

Continue Reading

Explore more guides on link shortener SaaS strategy, Bitly alternatives, and white label link management.

Free newsletter

Get new guides in your inbox

We publish practical guides on dev tooling, prompt engineering, marketing workflows, and deployment. No fluff — straight to the point.

No spam. Unsubscribe any time.

Was this article helpful?

Tell us if this guide solved the problem or what was still missing. We use this to improve the blog and only follow up if you explicitly allow it.

We use this to improve tutorials, examples, and technical depth.