Introduction
FastAPI has become one of the most popular Python web frameworks for building high-performance APIs. Its combination of automatic OpenAPI documentation, async support, and Pydantic-based validation makes it a go-to choice for developers. But even with its powerful built-in features, writing clean, production-ready code often requires a bit of prompting — whether from an AI assistant or from a well-structured cheat sheet.
This article provides 15 ready-to-use prompts for FastAPI development, covering essential areas: endpoint creation, Pydantic models, background tasks, and async processing. Each prompt is designed to be copy-pasted directly into an AI tool or used as a template for your own code. Whether you're building a REST API, integrating with third-party services, or handling background jobs, these prompts will save you time and help you follow best practices.
1. Prompt for Basic FastAPI Endpoint
Task: Generate a simple FastAPI endpoint with GET method.
Prompt:
Create a FastAPI endpoint that returns a JSON response with status 'ok' and a current timestamp. Use GET method at route '/health'.
Example output:
from fastapi import FastAPI
from datetime import datetime
app = FastAPI()
@app.get("/health")
async def health_check():
return {"status": "ok", "timestamp": datetime.now().isoformat()}
2. Prompt for Path and Query Parameters
Task: Define an endpoint that accepts both path and query parameters with validation.
Prompt:
Create a FastAPI endpoint that accepts a user ID as a path parameter (integer, > 0) and an optional 'include_details' query parameter (boolean, default False). Return a dict with both parameters.
Example output:
@app.get("/users/{user_id}")
async def get_user(user_id: int, include_details: bool = False):
return {"user_id": user_id, "include_details": include_details}
3. Prompt for Pydantic Model Definition
Task: Define a Pydantic model for user registration with validation.
Prompt:
Define a Pydantic BaseModel for user registration with fields: username (str, min 3 chars, max 50), email (EmailStr), age (int, between 18 and 120), and is_active (bool, default True). Use validators to ensure email is lowercase.
Example output:
from pydantic import BaseModel, EmailStr, validator
class UserRegister(BaseModel):
username: str
email: EmailStr
age: int
is_active: bool = True
@validator("email")
def email_lowercase(cls, v):
return v.lower()
4. Prompt for POST Endpoint with Pydantic Body
Task: Create a POST endpoint that accepts a Pydantic model and returns a response.
Prompt:
Create a FastAPI POST endpoint '/users' that accepts the UserRegister model and returns a success message with the created user's username.
Example output:
@app.post("/users")
async def create_user(user: UserRegister):
return {"message": f"User {user.username} created", "user": user}
5. Prompt for Response Model with Pydantic
Task: Define a response model and use it in an endpoint.
Prompt:
Create a Pydantic model 'UserResponse' with fields: id (int), username (str), email (str). Then create a GET endpoint '/users/{user_id}' that returns a mock user using this response model.
6. Prompt for Background Tasks
Task: Add a background task to a POST endpoint using FastAPI's BackgroundTasks.
Prompt:
Create a FastAPI endpoint '/send-email' that accepts an email address (str) and a message (str) via POST. Use BackgroundTasks to simulate sending email asynchronously. Return immediate response 'Email queued'.
Example output:
from fastapi import BackgroundTasks
def send_email(email: str, message: str):
print(f"Sending to {email}: {message}")
@app.post("/send-email")
async def send_email_endpoint(email: str, message: str, background_tasks: BackgroundTasks):
background_tasks.add_task(send_email, email, message)
return {"status": "Email queued"}
7. Prompt for Async Database Operations
Task: Write an async endpoint that simulates a database query.
Prompt:
Create an async FastAPI endpoint '/items' that simulates fetching items from a database using asyncio.sleep(1). Return a list of 3 sample items.
8. Prompt for Error Handling with HTTPException
Task: Add error handling for missing resources.
Prompt:
Create a FastAPI endpoint '/items/{item_id}' that raises an HTTPException with status 404 if item_id is not in a predefined list of allowed IDs (1, 2, 3).
9. Prompt for Dependency Injection
Task: Create a dependency that extracts user agent from headers.
Prompt:
Write a FastAPI dependency function 'get_user_agent' that extracts the User-Agent header from request headers. Then use it in a GET endpoint '/info'.
10. Prompt for File Upload Endpoint
Task: Build an endpoint that accepts file upload.
Prompt:
Create a FastAPI POST endpoint '/upload' that accepts an uploaded file (using UploadFile) and returns the filename and file size in bytes.
11. Prompt for CORS Middleware Setup
Task: Add CORS middleware to allow cross-origin requests.
Prompt:
Add CORS middleware to a FastAPI app that allows all origins, methods, and headers.
12. Prompt for Pagination with Query Parameters
Task: Implement pagination for a list endpoint.
Prompt:
Create a FastAPI endpoint '/items' that accepts 'page' (int, default 1) and 'size' (int, default 10) query parameters. Return a dict with 'page', 'size', 'total', and 'items' (empty list).
13. Prompt for WebSocket Endpoint
Task: Set up a simple WebSocket endpoint.
Prompt:
Create a FastAPI WebSocket endpoint '/ws' that accepts a connection and echoes back any received text message.
14. Prompt for Background Task with Return Value
Task: Use BackgroundTasks to update a resource after response.
Prompt:
Create a POST endpoint '/orders' that accepts an order_id (int). Immediately return 'Order received', and in background, simulate processing by printing 'Processing order {order_id}'.
15. Prompt for Combining Async and Sync Code
Task: Handle synchronous blocking code inside async endpoint.
Prompt:
Create a FastAPI endpoint '/report' that uses run_in_executor to call a synchronous function 'generate_report()' (which sleeps for 2 seconds) without blocking the async event loop.
Conclusion
These 15 prompts cover the most common patterns in FastAPI development — from basic endpoints to advanced async processing and background tasks. By using them as templates or inspiration, you can accelerate your API development while maintaining clean, idiomatic code. FastAPI's strength lies in its simplicity and type safety, and these prompts help you leverage that without reinventing the wheel.
Remember to always test your endpoints with the built-in interactive docs at /docs, and consider integrating with external services via their APIs. For example, ASI Biont supports connection to various services through API — you can learn more at asibiont.com/courses. Happy coding!
Comments