FastAPI CRUD endpoints with Pydantic v2, Alembic and pytest tests

Generate a complete FastAPI module for one resource: Pydantic v2 schemas, model and Alembic migration, a paginated CRUD router, and pytest tests with httpx. Designed for ChatGPT, Claude, Gemini and Microsoft Copilot. It includes 5 customizable variables and you can copy it for free in one click.

Intermediate · Code · Pending editorial review

Prompt

Act as a senior backend developer specializing in Python, FastAPI and SQLAlchemy.

I want to add a complete module to an existing FastAPI API to manage {{resource}}.
- Fields and types: {{fields}}
- Business rules: {{rules}}
- Database: {{database}}
- Data access: {{data_access}}

Deliverables, in this order:
1. File layout (router, schemas, model, service or repository, tests) with one sentence justifying the split.
2. Separate Pydantic v2 schemas for create, partial update and response, with validation (`Field`, `field_validator`, `model_validator`) that enforces the business rules.
3. The database model and its Alembic migration, with indexes and unique constraints where they make sense.
4. A router with a paginated, filterable list, detail, create, partial update (PATCH) and delete. Use the correct status codes (201, 204, 404, 409, 422) and a `response_model` on every endpoint.
5. A database session injected with `Depends`, no global state, and clearly scoped transactions.
6. Tests with pytest and `httpx.AsyncClient` (or `TestClient` if data access is sync): happy path, validation, missing resource and business-rule conflict, against an isolated test database.
7. Commands to run the app, apply the migration and run the tests.

Constraints:
- Python 3.11+, fully typed, no unnecessary dependencies.
- Do not invent fields or rules: if anything is ambiguous, ask me before writing code or mark it as [FILL IN].
- Point out which decisions depend on how the rest of my project is set up (auth, settings, table naming).

Format: one code block per file with its path as the heading, then a list of assumptions at the end.

How to use it

  1. Describe the resource with its real fields and the rules you currently enforce by hand.
  2. Pick your database and whether you use async SQLAlchemy, sync SQLAlchemy or SQLModel.
  3. Copy the files, generate the migration and run pytest before merging.
  4. If your project already has folder conventions, paste them so the code follows them.

Usage example

Resource: restaurant table bookings · Fields: guest, date and time, party size · Rule: max 40 guests per slot · PostgreSQL with async SQLAlchemy.

Sample output

2. Pydantic v2 schemas — app/bookings/schemas.py

from datetime import datetime, timedelta, timezone
from enum import Enum
from pydantic import BaseModel, Field, field_validator

class BookingStatus(str, Enum):
    pending = "pending"
    confirmed = "confirmed"
    cancelled = "cancelled"

class BookingCreate(BaseModel):
    guest_name: str = Field(min_length=1, max_length=120)
    phone: str = Field(pattern=r"^\+?[0-9 ]{7,20}$")
    starts_at: datetime
    party_size: int = Field(ge=1, le=12)

    @field_validator("starts_at")
    @classmethod
    def within_booking_window(cls, v: datetime) -> datetime:
        if v.tzinfo is None:
            raise ValueError("starts_at must include a timezone")
        now = datetime.now(timezone.utc)
        if v < now or v > now + timedelta(days=60):
            raise ValueError("bookings must be between now and 60 days ahead")
        return v

class BookingUpdate(BaseModel):
    starts_at: datetime | None = None
    party_size: int | None = Field(default=None, ge=1, le=12)
    status: BookingStatus | None = None

The 40 guests per 30-minute slot rule needs a database query, so it does not belong in the schema: the service sums the party sizes for that slot inside the same transaction and returns 409 when the limit would be exceeded.

Assumptions

  • Slots start at :00 and :30 → [FILL IN] if your restaurant works differently.
  • The phone pattern is a placeholder…

Key facts

Category
Programming & development · Python
Output type
Code
Level
Intermediate
Designed for
ChatGPT, Claude, Gemini and Microsoft Copilot
Verified in
Pending editorial verification
Variables
Resource, Fields and types, Business rules, Database and Data access
Language
English
Price
Free, no sign-up
Updated
Nov 7, 2026

Frequently asked questions

Why three different Pydantic schemas for one resource?

Create, update and response need different fields: in PATCH everything is optional, and the response includes the id and timestamps. Splitting them avoids leaking internal fields and inconsistent validation.

Where should business rules live, in the schema or the service?

Format and range checks belong in Pydantic. Rules that need a database lookup, such as slot capacity, belong in the service and should return 409 on conflict.

Does it work with SQLModel?

Yes. Choose SQLModel in the data access variable and the prompt adapts models and schemas, while still keeping input and output separate.

What is this prompt for?

Generate a complete FastAPI module for one resource: Pydantic v2 schemas, model and Alembic migration, a paginated CRUD router, and pytest tests with httpx.

Which AI tools does it work with?

It is designed for ChatGPT, Claude, Gemini and Microsoft Copilot. We have not verified it in these tools yet, so results may vary between them.

How do I customize the prompt?

Click “Customize” and fill in the variables (Resource, Fields and types, Business rules, Database and Data access). The text updates instantly and you can then copy it in one click. Values are stored only in your browser.

Do I need experience to use it?

It is intermediate: it helps to know the topic so you can provide good context and review the result critically.

Is this prompt free?

Yes. Every HomeCasa Prompts prompt is free, with no sign-up or subscription. You can also use them in professional projects.

Can I trust the AI output?

Treat it as a high-quality draft: always check data, figures and important claims before publishing or making decisions.

Related prompts