Introduction
FastAPI has become one of the most productive frameworks for building APIs in Python. It combines automatic OpenAPI documentation, Pydantic validation, and native async support. The hard part is knowing how to ask for exactly what you need when you work with AI assistants.
This article is a prompt collection for FastAPI. Each prompt includes a task, a ready-to-copy prompt, and an example result. Use these FastAPI prompts with ChatGPT, Claude, Cursor, or any other AI coding tool to create endpoint code, validation rules, and background processing logic in seconds.
How to read the prompts
Each prompt follows the same pattern:
- Task: what you are trying to build.
- Prompt: the exact text you can paste into an AI tool.
- Example result: a FastAPI code snippet you should expect.
| Category | Prompts | Best for |
|---|---|---|
| Basic | 1-4 | First endpoints, path params, Pydantic request models |
| Advanced | 5-8 | Validators, async I/O, background tasks, dependency injection |
| Expert | 9-12 | Production architecture, Celery, async database access |
Basic FastAPI prompts
Prompt 1: Health check endpoint
Task: Create a minimal FastAPI health check.
Prompt: Write a FastAPI app with a GET /health endpoint that returns a status and a version. Use a plain Python dict for the response.
Example result:
from fastapi import FastAPI
app = FastAPI(version='1.0.0')
@app.get('/health')
def health_check():
return {'status': 'ok', 'version': app.version}
Prompt 2: Path and query parameters
Task: Build an endpoint that accepts both path and query parameters.
Prompt: Create a GET /users/{user_id} endpoint. The path parameter user_id must be an integer. Add an optional query parameter details that defaults to False. Return both values.
Example result:
@app.get('/users/{user_id}')
def get_user(user_id: int, details: bool = False):
return {'user_id': user_id, 'details': details}
FastAPI automatically rejects non-integer path values and treats details as a query parameter.
Prompt 3: POST endpoint with Pydantic
Task: Accept a validated JSON body.
Prompt: Create a POST /users endpoint that accepts a Pydantic model with name, email, and age. Return a new user object with an id.
Example result:
from pydantic import BaseModel
class UserCreate(BaseModel):
name: str
email: str
age: int
@app.post('/users', status_code=201)
def create_user(user: UserCreate):
return {'id': 1, 'name': user.name, 'email': user.email, 'age': user.age}
Prompt 4: Response model and status codes
Task: Separate input and output schemas.
Prompt: Create a UserIn model and a UserOut model. Use response_model to hide the password field and return only id, email, and created_at. Set status code 201.
Example result:
from datetime import datetime
from pydantic import BaseModel
class UserIn(BaseModel):
email: str
password: str
class UserOut(BaseModel):
id: int
email: str
created_at: datetime
@app.post('/users', response_model=UserOut, status_code=201)
def create_user(user: UserIn):
return UserOut(id=1, email=user.email, created_at=datetime.now())
Advanced FastAPI prompts
Prompt 5: Pydantic validators
Task: Add custom validation to a Pydantic model.
Prompt: Create a Pydantic model for an event with name and max_attendees. Add a field_validator that raises ValueError when max_attendees is less than 1.
Example result:
from pydantic import BaseModel, field_validator
class Event(BaseModel):
name: str
max_attendees: int
@field_validator('max_attendees')
@classmethod
def check_positive(cls, value):
if value < 1:
raise ValueError('max_attendees must be positive')
return value
Prompt 6: Async endpoint with httpx
Task: Call an external API without blocking.
Prompt: Write an async GET /posts endpoint that uses httpx.AsyncClient to fetch posts from a public API and returns them.
Example result:
import httpx
from fastapi import FastAPI
app = FastAPI()
@app.get('/posts')
async def get_posts():
async with httpx.AsyncClient() as client:
response = await client.get('https://jsonplaceholder.typicode.com/posts')
return response.json()
Prompt 7: Background notification with BackgroundTasks
Task: Send a welcome email after registration.
Prompt: Create a POST /register endpoint that receives an email, adds a send_welcome_email function to BackgroundTasks, and returns immediately.
Example result:
from fastapi import BackgroundTasks
def send_welcome_email(email: str):
print(f'sending welcome email to {email}')
@app.post('/register')
async def register(email: str, background_tasks: BackgroundTasks):
background_tasks.add_task(send_welcome_email, email)
return {'message': 'Registration complete'}
Use BackgroundTasks for light work. For heavy jobs, move to Celery or a queue.
Prompt 8: Dependency injection for auth
Task: Extract auth logic from route handlers.
Prompt: Create a dependency get_current_user that reads the Authorization header and returns a user dict. Use it in a protected endpoint.
Example result:
from fastapi import Depends, Header
def get_current_user(authorization: str = Header(...)):
return {'token': authorization}
@app.get('/me')
def read_me(user: dict = Depends(get_current_user)):
return user
Expert FastAPI prompts
Prompt 9: Background jobs with Celery
Task: Move heavy work out of the request cycle.
Prompt: Create a Celery app and add a task generate_report that accepts a user_id and returns a report id. Expose a FastAPI endpoint that queues the task and returns the task id.
Example result:
from celery import Celery
from fastapi import FastAPI
celery = Celery('app', broker='redis://localhost:6379/0')
app = FastAPI()
@celery.task
def generate_report(user_id: int):
return {'report_id': user_id * 100}
@app.post('/reports')
def create_report(user_id: int):
task = generate_report.delay(user_id)
return {'task_id': task.id}
Prompt 10: Async SQLAlchemy session
Task: Use AsyncSession with FastAPI dependencies.
Prompt: Create a get_db dependency that yields an AsyncSession. Write a GET /products endpoint that returns all products.
Example result:
from fastapi import Depends
from sqlalchemy.ext.asyncio import AsyncSession, async_sessionmaker
async def get_db():
async with async_sessionmaker() as session:
yield session
@app.get('/products')
async def get_products(db: AsyncSession = Depends(get_db)):
result = await db.execute(select(Product))
return result.scalars().all()
This is a simplified pattern. Add your engine, model imports, and commit logic for production.
Prompt 11: Rate limiting
Task: Protect an endpoint from abuse.
Prompt: Add slowapi rate limiting to FastAPI. Create a GET /limited endpoint with a limit of 5 requests per minute.
Example result:
from fastapi import FastAPI, Request
from slowapi import Limiter
from slowapi.util import get_remote_address
limiter = Limiter(key_func=get_remote_address)
app = FastAPI()
app.state.limiter = limiter
@app.get('/limited')
@limiter.limit('5/minute')
def limited(request: Request):
return {'ok': True}
Prompt 12: End-to-end test with pytest-asyncio
Task: Test an async FastAPI endpoint.
Prompt: Write a pytest test for the GET /health endpoint using httpx.AsyncClient and pytest-asyncio.
Example result:
import pytest
from httpx import AsyncClient
from main import app
@pytest.mark.asyncio
async def test_health_check():
async with AsyncClient(app=app, base_url='http://test') as client:
response = await client.get('/health')
assert response.status_code == 200
Prompt optimization tips
- Be explicit about the framework version. Pydantic v2 uses field_validator, while v1 uses @validator.
- Include data contracts. List all fields, types, and validation rules.
- Ask for tests. A small prompt produces a small result.
- Add production constraints. Mention async, logging, retries, and security.
Conclusion
FastAPI rewards clarity. Use these FastAPI prompts to generate endpoints, Pydantic schemas, background tasks, and production-ready patterns. Instead of starting from a blank file, copy one of these prompts and let your AI assistant scaffold the code.
Bookmark this article, try the prompt that matches your next task, and share which endpoint you are building in the comments. If you want more API tutorials, subscribe to the Asibiont blog for weekly Python and FastAPI deep dives.
Comments