Python Backend in 2026: How One Developer Ships Production FastAPI, Django, and PostgreSQL with AI Prompts

Building a production-grade Python backend used to require a team: one person for API design, another for database optimization, a DevOps engineer for deployment, and a QA specialist for tests. In 2026, a single developer can ship a full-featured service using FastAPI or Django with PostgreSQL by leveraging AI as a force multiplier. The key is not just asking for code, but providing precise context: your schema, constraints, and stack. Below is a curated set of prompts that turn ChatGPT or Claude into a reliable pair programmer for backend tasks. Each prompt includes the exact wording, an example of how to use it, and a real-world snippet to illustrate the output.

1. Design a REST API from a Database Schema

When to use: You have a PostgreSQL schema and need a clean, versioned API.
Prompt:
"You are a senior Python backend architect. Given this PostgreSQL schema: [paste CREATE TABLE statements], design a REST API using FastAPI. Use Pydantic V2 models, include endpoints for CRUD, pagination, and filtering. Follow REST best practices: plural nouns, proper status codes, and OpenAPI tags. Output the OpenAPI spec in YAML and the FastAPI router code."
Example: For an e-commerce database with users, orders, and products, the AI generates /api/v1/products?limit=20&offset=0 and /api/v1/orders/{order_id} with correct 404 handling. It also suggests using response_model for validation.

2. Implement JWT Authentication with Refresh Tokens

When to use: You need secure auth without reinventing the wheel.
Prompt:
"Write a FastAPI authentication module using JWT with access and refresh tokens. Use python-jose and passlib[bcrypt]. Include endpoints for /register, /login, and /refresh. Store refresh tokens in Redis with a 7-day TTL. Provide the code and a docker-compose.yml for Redis."
Example: The AI returns a security.py with create_access_token(data: dict, expires_delta: timedelta) and a dependency get_current_user. It also warns about storing tokens in localStorage and recommends HTTP-only cookies.

3. Generate Alembic Migrations from SQLAlchemy Models

When to use: You changed models and need versioned migrations.
Prompt:
"I have SQLAlchemy models for a blog: User, Post, Comment. Generate an Alembic migration script that creates these tables with foreign keys and indexes. Include alembic revision --autogenerate commands and a env.py configuration for async engines."
Example: The output includes op.create_table('posts', sa.Column('id', sa.Integer, primary_key=True), ...) and a note to run alembic upgrade head.

4. Optimize Slow PostgreSQL Queries with EXPLAIN ANALYZE

When to use: A query takes seconds instead of milliseconds.
Prompt:
"Here is a slow query: [paste SQL]. The table has 10 million rows. Run EXPLAIN ANALYZE and suggest indexes. Propose a rewritten query using CTEs or window functions if needed. Explain the trade-offs."
Example: For SELECT * FROM orders WHERE user_id = 123 ORDER BY created_at DESC LIMIT 10, the AI suggests a composite index on (user_id, created_at DESC) and notes that it reduces the scan from 10M to 10 rows.

5. Convert Sync Django ORM to Async with sync_to_async

When to use: You are migrating Django views to async.
Prompt:
"Convert this Django view to async: [paste view]. Use sync_to_async for ORM calls. Ensure database queries are not blocking the event loop. Provide the refactored view and explain when to use async_to_sync."
Example: The AI wraps User.objects.get(id=user_id) in sync_to_async and adds await for the call. It also warns about select_related in async context.

6. Write Pytest Fixtures for FastAPI with Test Database

When to use: You need reliable integration tests.
Prompt:
"Create Pytest fixtures for a FastAPI app using a PostgreSQL test database. Use pytest-asyncio and httpx.AsyncClient. Include a fixture that rolls back transactions after each test. Provide a conftest.py and an example test for the /items endpoint."
Example: The fixture uses async with engine.begin() as conn: await conn.run_sync(Base.metadata.create_all) and yields a client. The test asserts response.status_code == 200.

7. Set Up Celery with Redis for Background Tasks

When to use: You need to send emails or process images asynchronously.
Prompt:
"Configure Celery with Redis as broker and result backend for a FastAPI project. Create a task that sends a welcome email. Include celery_app.py, tasks.py, and instructions to run the worker. Use task_always_eager=True for testing."
Example: The AI provides @celery_app.task def send_welcome_email(user_id: int) and a call send_welcome_email.delay(user_id). It also suggests Flower for monitoring.

8. Dockerize a FastAPI App with Multi-Stage Build

When to use: You want a small, secure production image.
Prompt:
"Write a multi-stage Dockerfile for a FastAPI app using Python 3.12-slim. Install dependencies with pip install --no-cache-dir. Copy only necessary files. Use uvicorn with --workers 4. Include a docker-compose.yml with PostgreSQL and Redis."
Example: The final image is ~150MB instead of 1GB. The compose file defines db, redis, and web services with healthchecks.

9. Generate OpenAPI Documentation with Examples

When to use: Your API docs need to be developer-friendly.
Prompt:
"Add OpenAPI examples to this FastAPI endpoint: [paste code]. Use openapi_examples in the Query and Body parameters. Provide a sample request and response for each status code."
Example: The AI adds examples={"normal": {"summary": "A normal item", "value": {"name": "Book", "price": 19.99}}} to the schema.

10. Implement Rate Limiting with SlowAPI

When to use: You need to protect endpoints from abuse.
Prompt:
"Add rate limiting to a FastAPI app using SlowAPI. Limit /login to 5 requests per minute per IP. Provide the middleware setup and a custom error handler that returns 429 with a Retry-After header."
Example: The code uses @limiter.limit("5/minute") and a _rate_limit_exceeded_handler that logs the IP.

11. Write Unit Tests for Django Models

When to use: You want to ensure business logic is correct.
Prompt:
"Write unit tests for a Django Order model with fields total, status, and a method apply_discount. Use pytest-django. Test edge cases: zero total, negative discount, and status transitions. Provide the test file and a fixture for a user."
Example: The test test_apply_discount_negative asserts that a ValueError is raised.

12. Optimize Django ORM with select_related and prefetch_related

When to use: You see N+1 queries in Django Debug Toolbar.
Prompt:
"This Django view causes N+1 queries: [paste view]. Rewrite it using select_related and prefetch_related. Explain the difference and when to use each. Provide the optimized queryset and a test to assert query count."
Example: The AI changes Post.objects.all() to Post.objects.select_related('author').prefetch_related('comments') and adds assertNumQueries(2).

13. Set Up Structured Logging with structlog

When to use: You need JSON logs for production monitoring.
Prompt:
"Configure structlog for a FastAPI app to output JSON logs. Include request ID, user ID, and log level. Integrate with uvicorn and add a middleware to bind request context. Provide the logging config and a sample log line."
Example: The middleware binds request_id using uuid4() and logs {"event": "request_started", "path": "/items", "request_id": "..."}.

14. Create a CI/CD Pipeline with GitHub Actions

When to use: You want automated tests and deployment.
Prompt:
"Write a GitHub Actions workflow for a Python backend: run pytest, ruff, and mypy on push. Build a Docker image and push to GitHub Container Registry. Deploy to a VPS via SSH using appleboy/ssh-action. Include secrets for REGISTRY_TOKEN and SSH_KEY."
Example: The workflow has jobs test and deploy, with needs: test for the latter. It uses docker/build-push-action@v5.

15. Generate Database Seed Data with Faker

When to use: You need realistic test data.
Prompt:
"Write a script to seed a PostgreSQL database with 1000 fake users and 5000 orders using Faker and SQLAlchemy. Ensure foreign keys are respected. Use bulk inserts for speed. Provide the script and a Makefile command make seed."
Example: The script uses session.bulk_save_objects(users) and commits in batches of 500.

16. Implement Health Checks and Readiness Probes

When to use: You deploy to Kubernetes.
Prompt:
"Add /health and /ready endpoints to a FastAPI app. /health returns 200 if the app is running. /ready checks PostgreSQL and Redis connections. Provide the code and Kubernetes manifest snippets for liveness and readiness probes."
Example: The readiness check runs await db.execute("SELECT 1") and returns 503 if it fails.

17. Refactor a Monolithic View into a Service Layer

When to use: Your views are bloated with business logic.
Prompt:
"Refactor this Django view into a service layer: [paste view]. Create a services.py with functions like create_order(user, items). Keep views thin. Provide the refactored code and explain the benefits for testing and reuse."
Example: The AI moves validation and payment logic to services.create_order and the view simply calls it and returns a response.

18. Write a Custom Django Management Command

When to use: You need to run periodic maintenance.
Prompt:
"Write a Django management command cleanup_expired_sessions that deletes sessions older than 30 days. Use django.contrib.sessions.models.Session. Add options for --dry-run and --days. Provide the command file and a cron example."
Example: The command uses Session.objects.filter(expire_date__lt=timezone.now() - timedelta(days=days)).delete() and logs the count.

These prompts are not magic; they work best when you provide accurate context: your schema, your constraints, and your stack versions. Treat the AI as a junior developer who needs clear instructions — review its output, run tests, and iterate. With this approach, solo developers and small teams can ship production Python backends faster while maintaining architecture quality. Start with one prompt today, and integrate AI into your workflow step by step.

← All posts

Comments