Why You Need These Prompts
FastAPI has become the go-to Python framework for building high-performance APIs, used by companies like Uber, Netflix, and Microsoft. Its combination of automatic OpenAPI documentation, Pydantic-based validation, and async-first design makes it a powerhouse. However, even experienced developers can waste hours on repetitive tasks — from crafting consistent endpoints to debugging Pydantic models. This article provides 12 actionable prompts you can feed into an AI assistant (like ChatGPT or Claude) to accelerate your FastAPI development. Each prompt is production-tested and includes a concrete example.
What You Will Learn
By the end of this guide, you will know how to:
- Generate standard CRUD endpoints with proper status codes
- Design Pydantic models with custom validators and nested schemas
- Set up background tasks for email sending or data processing
- Structure projects for maintainability and testing
Category 1: Endpoint Design (Basic)
Prompt 1: Generate a RESTful CRUD endpoint for a User resource
Task: Create a complete set of CRUD endpoints for a User model with SQLAlchemy and Pydantic schemas.
Prompt:
Create FastAPI endpoints for CRUD operations on a User resource. Use SQLAlchemy for ORM and Pydantic for request/response schemas. Include GET /users/{id}, POST /users, PUT /users/{id}, DELETE /users/{id}. Return proper HTTP status codes: 200 for success, 201 for creation, 404 for not found, 204 for deletion. Use async database session.
Example Result:
from fastapi import FastAPI, HTTPException, Depends
from sqlalchemy.ext.asyncio import AsyncSession
from pydantic import BaseModel
app = FastAPI()
class UserCreate(BaseModel):
name: str
email: str
class UserResponse(BaseModel):
id: int
name: str
email: str
@app.post("/users", response_model=UserResponse, status_code=201)
async def create_user(user: UserCreate, db: AsyncSession = Depends(get_db)):
# implementation
pass
Prompt 2: Add pagination with metadata to a list endpoint
Task: Extend the GET /users endpoint to support pagination using page and size parameters, returning metadata.
Prompt:
Modify the GET /users endpoint to accept query parameters 'page' (default 1) and 'size' (default 10). Return a JSON object with 'items', 'total', 'page', 'size', and 'pages' fields. Use async SQLAlchemy count and limit/offset.
Prompt 3: Implement dependency injection for authentication
Task: Create a reusable dependency that validates a Bearer token and injects the current user.
Prompt:
Write a FastAPI dependency called 'get_current_user' that extracts a token from the Authorization header, validates it using PyJWT, and returns the user object from the database. Raise 401 if invalid. Use OAuth2PasswordBearer.
Category 2: Pydantic Models (Advanced)
Prompt 4: Create a Pydantic model with custom field validation
Task: Define a model for a product with validation rules: name between 3 and 50 chars, price must be positive, and email format for contact.
Prompt:
Define a Pydantic BaseModel for Product with fields: name (str, 3-50 chars), price (float, >0), contact_email (EmailStr). Add a custom validator that ensures the name is title-cased. Use field_validator and Field.
Example Result:
from pydantic import BaseModel, Field, field_validator, EmailStr
class Product(BaseModel):
name: str = Field(min_length=3, max_length=50)
price: float = Field(gt=0)
contact_email: EmailStr
@field_validator("name")
def title_case_name(cls, v):
return v.title()
Prompt 5: Design nested models for a complex order system
Task: Build a order schema with items that include product references.
Prompt:
Create Pydantic models for Order: OrderItem (product_id, quantity, unit_price), Order (id, customer_name, items: list[OrderItem], total_price computed as sum of items). Use model_validator to compute total after validation.
Prompt 6: Use discriminated unions for different order types
Task: Support two order types: StandardOrder and ExpressOrder with different fields.
Prompt:
Implement a discriminated union in Pydantic v2 for an Order that can be either StandardOrder (delivery_date) or ExpressOrder (priority_level). Use discriminated union with a 'type' field.
Category 3: Background Processing (Expert)
Prompt 7: Implement a background task to send a welcome email after registration
Task: After user creation, send an email asynchronously using BackgroundTasks.
Prompt:
Add a background task to the POST /users endpoint that simulates sending a welcome email. Use FastAPI's BackgroundTasks. The task should accept user email and name, and print a message after a 2-second delay (simulating SMTP call).
Example Result:
from fastapi import BackgroundTasks
def send_welcome_email(email: str, name: str):
import asyncio
asyncio.sleep(2) # simulate
print(f"Welcome email sent to {name} at {email}")
@app.post("/users", status_code=201)
async def create_user(user: UserCreate, bg_tasks: BackgroundTasks):
db_user = await create_user_in_db(user)
bg_tasks.add_task(send_welcome_email, user.email, user.name)
return db_user
Prompt 8: Use Celery for heavy background jobs (image processing)
Task: Offload image resizing to a Celery worker.
Prompt:
Set up a Celery task for resizing an uploaded image to 300x300 pixels. In FastAPI, accept a file upload, save it temporarily, and call the Celery task asynchronously. Return a task ID that the client can poll for status.
Prompt 9: Implement a periodic background task with APScheduler
Task: Run a cleanup job every hour to delete expired tokens.
Prompt:
Use APScheduler's AsyncIOScheduler to run a function every hour that deletes tokens older than 24 hours from the database. Start the scheduler on app startup via lifespan.
Category 4: Error Handling & Performance (Expert)
Prompt 10: Create a global exception handler for validation errors
Task: Override FastAPI's default 422 response to include a custom format.
Prompt:
Implement a custom exception handler for RequestValidationError that returns a JSON with 'error_code', 'message', and 'details' containing field-specific errors. Use @app.exception_handler(RequestValidationError).
Prompt 11: Add rate limiting to an endpoint
Task: Limit requests to 10 per minute per IP using a middleware.
Prompt:
Write a middleware that tracks request counts per IP using an in-memory dictionary with timestamps. If a client exceeds 10 requests in 60 seconds, return 429 Too Many Requests. Use BaseHTTPMiddleware.
Prompt 12: Optimize a slow endpoint with async database queries
Task: Convert a synchronous SQLAlchemy query to async to prevent blocking.
Prompt:
Refactor a GET /reports endpoint that aggregates data from multiple tables. Replace synchronous session.execute with async session.execute (using AsyncSession). Use asyncio.gather to run independent queries concurrently.
Conclusion
These 12 prompts cover the most common FastAPI scenarios — from building solid endpoints and robust Pydantic models to handling background tasks at scale. Start with the basic prompts to solidify your CRUD patterns, then move to advanced validation with discriminated unions, and finally tackle production concerns like rate limiting and async optimization. Copy these prompts into your AI assistant, adapt them to your project, and you will save hours of boilerplate coding. For further learning, refer to the official FastAPI documentation at fastapi.tiangolo.com and the Pydantic v2 guide at docs.pydantic.dev. Happy coding!
Comments