Introduction
FastAPI has become one of the most popular Python frameworks for building high-performance APIs. Released in 2018 by Sebastián Ramírez, it now powers thousands of production systems, from small startups to enterprise applications. According to the 2025 JetBrains Python Developers Survey, FastAPI is used by over 28% of Python developers for web development, making it the fastest-growing async framework in the ecosystem.
But writing clean, maintainable, and efficient FastAPI code requires more than just knowing the basics. You need to master endpoints, Pydantic models for validation, and async background processing. This guide provides 30 ready-to-use prompts that cover real-world scenarios, from simple CRUD endpoints to complex background task pipelines. Each prompt is designed to be copy-pasted and adapted to your project, with explanations of what it does and when to use it.
Whether you are a beginner setting up your first API or an experienced developer optimizing production code, these prompts will save you hours of searching through documentation. Let’s dive in.
How to Use These Prompts
Each prompt below follows the same structure:
- Task: what the prompt helps you build
- Prompt: the exact text you can feed to an AI assistant or use as a template
- Explanation: why this works and what to watch out for
- Example: a concrete usage scenario
You can use these prompts with any AI coding assistant (GitHub Copilot, Cursor, Claude, etc.) or as standalone code templates. Modify the placeholders (like YourModel, your_field) to fit your domain.
Section 1: Endpoints (10 Prompts)
1.1 Basic CRUD Endpoint
Task: Create a read endpoint that returns a list of items from a database.
Prompt:
Write a FastAPI endpoint `GET /items` that returns a list of items from a SQLite database using SQLAlchemy. Use async session and dependency injection. Include query parameters for pagination: `skip` (int, default 0) and `limit` (int, default 10). Return a list of Pydantic models `ItemOut`.
Explanation: This prompt covers the standard pattern for listing resources. Async SQLAlchemy sessions prevent blocking the event loop. Pagination is essential for production APIs to avoid returning thousands of records at once.
Example: A user requests GET /items?skip=0&limit=5, and the endpoint returns the first 5 items.
1.2 Create Endpoint with Validation
Task: Build a POST endpoint that creates a new user.
Prompt:
Create a FastAPI `POST /users` endpoint that accepts a JSON body validated by Pydantic model `UserCreate` (fields: username, email, password). Hash the password using passlib. Return the newly created user as `UserOut` (without password). Use HTTP status code 201.
Explanation: Never store plain-text passwords. Using Pydantic ensures malformed data is rejected early. Status code 201 is semantically correct for resource creation.
Example: Sending {"username":"alice","email":"alice@example.com","password":"secret"} returns the created user object with a hashed password stored in DB.
1.3 Update Endpoint (Partial Update)
Task: Implement a PATCH endpoint for partial updates.
Prompt:
Write a FastAPI `PATCH /items/{item_id}` endpoint that partially updates an item. The request body should be a Pydantic model with all fields optional. Only update fields that are not None. Return the updated item. Use async SQLAlchemy and handle the case where item_id does not exist (return 404).
Explanation: PATCH is designed for partial updates. Using optional fields in the schema allows clients to send only changed fields. Checking for None prevents overwriting existing data with nulls.
Example: A client sends {"name":"New Name"} to update only the name of item 42.
1.4 Delete Endpoint
Task: Create a DELETE endpoint with soft delete.
Prompt:
Implement a FastAPI `DELETE /users/{user_id}` endpoint that performs a soft delete: set the `is_active` field to False instead of removing the row. Return 204 No Content. Use async SQLAlchemy.
Explanation: Soft deletes preserve data integrity and allow recovery. HTTP 204 is the standard for successful deletes with no response body.
Example: Deleting user 5 sets is_active=False in the database, but the row remains.
1.5 Search Endpoint
Task: Build a search endpoint that filters by multiple fields.
Prompt:
Create a FastAPI `GET /products/search` endpoint that accepts query parameters: `q` (string, search term), `category` (optional string), `min_price` (optional float), `max_price` (optional float). Use SQLAlchemy `ilike` for text search and range filters for price. Return paginated results.
Explanation: Search endpoints are common in e-commerce and content platforms. Using ilike makes search case-insensitive. Optional parameters allow flexible filtering.
Example: GET /products/search?q=phone&min_price=100&max_price=500 returns phones in the price range.
1.6 File Upload Endpoint
Task: Create an endpoint that accepts file uploads.
Prompt:
Write a FastAPI `POST /upload` endpoint that accepts a file using `UploadFile`. Validate the file type (only images: jpg, png) and size (max 5 MB). Save the file to a local `uploads/` directory with a UUID-based name to avoid collisions. Return the file URL.
Explanation: File uploads need validation to prevent malicious files. UUID names prevent overwriting and directory traversal attacks. Size limits protect server resources.
Example: Uploading a photo.jpg saves it as uploads/abc123.jpg and returns {"url":"/uploads/abc123.jpg"}.
1.7 WebSocket Endpoint
Task: Implement a WebSocket endpoint for real-time chat.
Prompt:
Create a FastAPI WebSocket endpoint at `/ws/chat/{room_id}` that maintains a list of connected clients per room. When a message is received, broadcast it to all other clients in the same room. Use `asyncio` and handle disconnection gracefully.
Explanation: WebSockets enable bidirectional real-time communication. Broadcasting ensures all clients in a room see messages. Graceful disconnection prevents memory leaks.
Example: Two users in room "general" can exchange messages in real time.
1.8 Dependency Injection for Authentication
Task: Add a dependency that extracts the current user from a JWT token.
Prompt:
Write a FastAPI dependency `get_current_user` that extracts a JWT token from the `Authorization` header (Bearer scheme), decodes it using PyJWT, and returns the user from the database. If the token is invalid or user not found, raise HTTPException 401. Use this dependency in a protected endpoint.
Explanation: Dependencies promote code reuse and make endpoints cleaner. JWT is stateless and widely used for authentication. The 401 status is correct for unauthorized access.
Example: GET /profile requires a valid token; otherwise, returns 401.
1.9 Rate Limiting Middleware
Task: Implement rate limiting for an endpoint.
Prompt:
Add a rate limiter to FastAPI using `slowapi`. Create a `@limiter.limit("5/minute")` decorator on a test endpoint. Configure the limiter to use in-memory storage. Return 429 Too Many Requests when the limit is exceeded.
Explanation: Rate limiting prevents abuse. slowapi integrates easily with FastAPI. A 429 status code is standard for rate limits.
Example: If a client hits the endpoint 6 times in one minute, the 6th request gets a 429 response.
1.10 OpenAPI Customization
Task: Customize the OpenAPI schema for an endpoint.
Prompt:
Modify a FastAPI endpoint to include a custom `summary` and `description` for OpenAPI docs. Add a response model that shows example values. Use `responses` decorator to document possible HTTP errors (400, 404, 500).
Explanation: Good documentation improves developer experience. Custom summaries make auto-generated docs more readable. Documenting errors helps API consumers handle failures.
Example: The /docs page shows a clear description and example responses for each status code.
Section 2: Pydantic Models (10 Prompts)
2.1 Basic Model with Validation
Task: Define a Pydantic model for a user with email validation.
Prompt:
Create a Pydantic BaseModel `UserCreate` with fields: `email` (EmailStr), `username` (str, min_length=3, max_length=50), `password` (str, min_length=8). Add a custom validator that ensures the password contains at least one digit and one uppercase letter.
Explanation: Pydantic automatically validates types and constraints. EmailStr requires the pydantic[email] extra. Custom validators enforce business rules.
Example: UserCreate(email="test@example.com", username="alice", password="Pass1234") passes validation; "pass" fails.
2.2 Nested Models
Task: Model a blog post with nested comments.
Prompt:
Define two Pydantic models: `Comment` (fields: id, content, created_at) and `Post` (fields: id, title, content, comments: list[Comment]). Use `from_attributes=True` in the Config class to support ORM mode. Ensure `created_at` is a datetime field with a default factory.
Explanation: Nested models represent complex relationships. ORM mode allows converting SQLAlchemy objects directly to Pydantic models. Datetime defaults simplify creation.
Example: A Post object automatically includes a list of Comment objects when serialized.
2.3 Union Types for Responses
Task: Create a response model that can be either success or error.
Prompt:
Define a Pydantic model `APIResponse` that uses `Union[SuccessResponse, ErrorResponse]`. `SuccessResponse` has a `data` field of generic type. `ErrorResponse` has a `detail` string. Use `discriminator` field to distinguish between types.
Explanation: Union types with discriminators make APIs more predictable. Clients can check a field to know which type they received.
Example: A successful create returns {"type":"success","data":{"id":1}}.
2.4 Computed Fields
Task: Add a computed field that depends on other fields.
Prompt:
Create a Pydantic model `Order` with fields: `items` (list of `OrderItem` with price and quantity), and a computed field `total_price` that sums `item.price * item.quantity`. Use `@computed_field` decorator from Pydantic v2.
Explanation: Computed fields eliminate redundant storage. Pydantic v2‘s @computed_field is cleaner than custom validators for derived data.
Example: An order with two items of 10 and 20 units at $5 each returns total_price=150.
2.5 Strict Mode
Task: Enforce strict type checking for an input model.
Prompt:
Define a Pydantic model `StrictInput` with `model_config = {"strict": True}`. All fields must match types exactly: no string-to-int coercion. Test that passing a string "123" for an int field raises a validation error.
Explanation: Strict mode prevents silent type coercion, which can hide bugs. Useful when input comes from external systems.
Example: {"age": "30"} fails because age expects an int, not a string.
2.6 Field Aliases
Task: Map JSON field names to Python field names.
Prompt:
Create a Pydantic model `ExternalAPI` with a field `user_name` that maps from JSON key `"user_name"` using `Field(alias="user_name")`. Add `populate_by_name=True` to allow both alias and actual name in input.
Explanation: Aliases bridge naming conventions between systems (e.g., snake_case in Python, camelCase in JSON). populate_by_name adds flexibility.
Example: JSON {"user_name":"alice"} populates the user_name field.
2.7 Custom Validators with @field_validator
Task: Validate that a date range is logical.
Prompt:
Create a model `DateRange` with `start_date` and `end_date` (both datetime). Add a `@field_validator('end_date')` that checks `end_date > start_date`. Raise ValueError with a clear message if validation fails.
Explanation: Cross-field validators enforce business logic that spans multiple fields. The validator runs after individual field validation.
Example: {"start_date":"2026-01-01","end_date":"2025-12-31"} raises an error.
2.8 Generic Models
Task: Create a generic paginated response model.
Prompt:
Define a generic Pydantic model `PaginatedResponse[T]` with fields: `items` (list[T]), `total` (int), `page` (int), `size` (int). Use `Generic` and `TypeVar` from typing. Show how to instantiate it with `ItemOut`.
Explanation: Generics reduce code duplication by reusing the same pagination structure for different resource types.
Example: PaginatedResponse[ItemOut] returns paginated items.
2.9 Secret Fields
Task: Hide sensitive fields in model export.
Prompt:
Create a model `UserInDB` with a field `password` typed as `SecretStr`. Ensure that when the model is serialized to dict or JSON, the password appears as `'********'`. Demonstrate using `.model_dump()`.
Explanation: SecretStr prevents accidental exposure of secrets in logs or responses. It’s a small but critical security practice.
Example: user.model_dump() shows {"password":"********"}.
2.10 Model Config for Immutability
Task: Make a model immutable after creation.
Prompt:
Define a Pydantic model `Config` with `model_config = {"frozen": True}`. All fields are read-only after initialization. Attempting to set an attribute raises an error. Use this for configuration objects.
Explanation: Frozen models prevent accidental mutation, which is useful for settings or constants.
Example: After creating Config(debug=True), config.debug = False raises a FrozenInstanceError.
Section 3: Background Processing (10 Prompts)
3.1 Simple Background Task with BackgroundTasks
Task: Send a welcome email after user registration.
Prompt:
In a FastAPI `POST /register` endpoint, use `BackgroundTasks` to add a task that sends a welcome email to the new user. Define an async function `send_welcome_email(email: str)` that simulates sending (print to console or use an SMTP library). Return the user immediately without waiting for the email.
Explanation: BackgroundTasks is built into FastAPI and runs tasks after the response is sent. This keeps the endpoint fast.
Example: Registration returns instantly; the email is sent a few milliseconds later.
3.2 Long-Running Task with asyncio.create_task
Task: Process a large file upload in the background.
Prompt:
Create an endpoint `POST /process-file` that accepts a file and immediately returns a task ID. Use `asyncio.create_task` to run a coroutine `process_file(file_path, task_id)` that processes the file (e.g., resizing images). Store the status in an in-memory dict. Provide a `GET /task/{task_id}` endpoint to check status.
Explanation: For long tasks, BackgroundTasks may not be enough because the server process could be recycled. asyncio.create_task is better for in-process async tasks. A task ID pattern lets clients poll for completion.
Example: Uploading a video returns task ID abc123; polling shows "processing" then "done".
3.3 Celery Integration
Task: Offload a CPU-bound task to Celery.
Prompt:
Set up a Celery app with Redis as broker. Create a task `generate_report` that takes a user ID and generates a PDF report. In FastAPI, call `generate_report.delay(user_id)` from an endpoint and return a task ID. Write a status endpoint that queries Celery’s result backend.
Explanation: Celery handles distributed background tasks, especially CPU-bound or long-running ones. Redis is a common broker. The delay method is non-blocking.
Example: Requesting a report returns immediately; the PDF is generated by a worker.
3.4 Periodic Tasks with APScheduler
Task: Run a daily cleanup job.
Prompt:
Integrate APScheduler with FastAPI. Create a scheduled job that runs every day at midnight to delete expired tokens from the database. Use `AsyncIOScheduler` and start it in a lifespan event. Log the number of deleted tokens.
Explanation: Periodic tasks are essential for maintenance. APScheduler supports async schedulers that integrate with FastAPI’s event loop.
Example: At midnight, the job deletes all tokens older than 30 days.
3.5 Progress Tracking
Task: Track progress of a background task via WebSocket.
Prompt:
Create a FastAPI WebSocket endpoint `/ws/progress/{task_id}`. When a background task starts, it periodically sends progress updates (0-100%) to the WebSocket. Use `asyncio.Queue` to pass messages from the task to the WebSocket handler.
Explanation: WebSockets provide real-time progress without polling. A queue decouples the task from the connection.
Example: A file upload shows 10%, 50%, 100% in real time on the client.
3.6 Error Handling in Background Tasks
Task: Catch and log errors in background tasks.
Prompt:
In a background task function, wrap the main logic in try-except. Log the error using Python’s logging module. Update a task status dict with `"error": str(e)`. Return the error message in the status endpoint.
Explanation: Unhandled exceptions in background tasks can silently fail. Logging and status updates help debugging.
Example: If a PDF generation fails, the status becomes {"status":"error","error":"Memory limit exceeded"}.
3.7 Task Queues with Redis
Task: Implement a simple task queue using Redis lists.
Prompt:
Use `redis-py` to push task data as JSON to a Redis list `task_queue`. Create a separate worker script that pops tasks from the list using `BLPOP` and processes them. In FastAPI, an endpoint pushes a task and returns immediately.
Explanation: A lightweight alternative to Celery for simple queuing. Redis lists guarantee at-least-once delivery with BLPOP.
Example: A POST /send-notification pushes {"user_id":1,"message":"Hello"} to the queue.
3.8 Rate-Limited Background Processing
Task: Process tasks at a controlled rate.
Prompt:
Create a background worker that processes tasks from a queue at a maximum rate of 10 per second. Use `asyncio.Semaphore` to limit concurrency. Log the processing rate and any dropped tasks.
Explanation: Rate limiting prevents overwhelming downstream services (e.g., external APIs). Semaphores control concurrency.
Example: If 100 tasks arrive, the worker processes 10 per second over 10 seconds.
3.9 Chained Background Tasks
Task: Execute a sequence of dependent background tasks.
Prompt:
Design a pipeline where task A (download file) triggers task B (process file) upon completion. Use a message broker like RabbitMQ with direct exchanges. In FastAPI, publish to the first queue; a consumer publishes to the second queue after finishing.
Explanation: Chained tasks model workflows like ETL pipelines. Each step is independent and can be scaled separately.
Example: Download → Validate → Transform → Notify.
3.10 Graceful Shutdown
Task: Ensure background tasks complete before server shutdown.
Prompt:
Use FastAPI’s lifespan context manager to manage a list of running tasks. On shutdown, await all pending tasks with a timeout (e.g., 30 seconds). Log any tasks that did not finish. Use `asyncio.gather` with `return_exceptions=True`.
Explanation: Graceful shutdown prevents data loss. The lifespan pattern in FastAPI is the recommended way to manage startup/shutdown events.
Example: If a task is still running when the server receives SIGTERM, it waits up to 30 seconds before forcing exit.
Conclusion
These 30 prompts cover the most common and powerful patterns in FastAPI development—from building robust endpoints with validation to managing complex background workflows. By mastering Pydantic models, you ensure data integrity from the moment it enters your API. By leveraging background processing, you keep your endpoints responsive and your users happy.
The key takeaway is that FastAPI’s ecosystem—Pydantic, SQLAlchemy, Celery, Redis—works together seamlessly when you follow these patterns. Start by implementing the prompts that match your current project, then gradually adopt more advanced techniques like WebSocket progress tracking or chained tasks.
Remember: good prompts are not just copy-paste templates. They are teaching tools that help you understand why each pattern exists. Experiment with them, adapt them to your domain, and soon you will be writing production-grade FastAPI code without reaching for documentation every five minutes.
For a complete library of ready-to-use prompts covering FastAPI and dozens of other AI tools, visit asibiont.com/blog—your shortcut from idea to production.
Comments