12 LLM Prompts That Build a Working CRUD App Skeleton

You ask an LLM for a CRUD app skeleton, and it happily generates a User model, a router, and a service layer. But when you try to run it, nothing works: the imports point to files that don't exist, the database migrations are missing, and the layers are mixed up. You spend hours stitching together code that was supposed to save you time. This is a common pain point, but it's fixable. The key is to stop treating the LLM as a code vending machine and start guiding it through a structured, step-by-step process that ensures coherence and completeness. In this article, we'll walk through 12 prompts that, used in sequence, will make an LLM produce a working CRUD application skeleton—with proper layering, migrations, validation, and tests—so you can actually run it and build upon it.

From schema to running app: the 12-prompt sequence
1
1. Data schema
Tables, relationships, constraints
2
2. SQLAlchemy models
Classes mapped to tables
3
3. Alembic migrations
Database version control
4
4. Pydantic schemas
Validation and serialization
5
5. Repository layer
CRUD operations
6
6. Service layer
Business logic
7
7. API routes
FastAPI endpoints
8
8. Error handling
Global exception handlers

Why the Sequence Works (and What It Costs)

LLMs are good at generating isolated pieces of code but poor at holding a whole project in mind. Asked for a "CRUD app" in one shot, the model fills gaps with plausible-looking imports for files it never wrote, and it collapses layers because nothing in the request forces them apart. The sequence below works because each prompt hands the model a small, closed problem whose inputs are files you already have on disk. The schema is the anchor: because every later prompt is told to derive from it, the model has no room to invent a users.email column that the migration doesn't create. Splitting repository from service is not ceremony—it gives the model a place to put a query and a place to put a rule, so it stops mixing them.

The trade-off is real. Twelve prompts mean twelve round-trips: more wall-clock time, more tokens, and more of your attention spent reading output. For a throwaway script or a single-table prototype, one monolithic prompt is often enough—accept the cleanup. The sequence pays off when the skeleton must survive contact with a real database and other developers. A middle path: use the full sequence for the first entity, then reuse its output as the template for the rest. More on the topic: “Twelve Prompts That Read EXPLAIN ANALYZE Better Than You Do — and the Three Moments When You Should Not Trust Them”.

1. Define the Data Schema and Relationships

Before writing any code, you need a clear data model. This prompt asks the LLM to produce a schema definition in a neutral format (like JSON or YAML) that includes tables, columns, types, and relationships. This becomes the single source of truth for later steps.

You are a database architect. Design a data schema for a simple blog with users, posts, and comments. Output the schema as a JSON object with tables, columns (name, type, constraints), and foreign key relationships. Include primary keys and indexes where appropriate. Do not write any code yet—just the schema.

What good looks like: the output should be a JSON object keyed by table, e.g. {"users": {"columns": [{"name": "id", "type": "integer", "constraints": ["primary key"]}, {"name": "email", "type": "varchar(255)", "constraints": ["unique", "not null"]}],...}, "posts": {"columns": [...], "foreign_keys": [{"column": "author_id", "references": "users.id"}]}}. If you get prose instead of JSON, re-ask.

Verify before moving on: check that every foreign key names a table and column that exist in the same document, and that every table has a primary key. Save the file as schema.json—you will paste it into the next prompts.

2. Generate SQLAlchemy Models from the Schema

Now that you have a schema, ask the LLM to generate the corresponding SQLAlchemy models. Emphasize that the models must match the schema exactly and include relationships.

Using the schema from the previous step, generate SQLAlchemy models in Python. Define each table as a class inheriting from a declarative base. Include columns with correct types, primary keys, foreign keys, and relationships (e.g., User.posts). Do not include any business logic or imports beyond what's necessary. Output only the model definitions.

What good looks like: one class per table, id = Column(Integer, primary_key=True), email = Column(String(255), unique=True, nullable=False), and a relationship("Post", back_populates="author") on each side of a foreign key.

Verify: diff the model's columns against schema.json name by name—type mismatches (String vs String(255)) and missing nullable=False are the usual drift. Then run python -c "import models" to confirm the imports resolve.

3. Set Up Database Migrations with Alembic

Migrations are often forgotten. This prompt ensures the LLM generates Alembic migration scripts that match the models.

Generate an Alembic migration script that creates the tables defined in the SQLAlchemy models from step 2. Assume the models are in models.py. Output the complete migration file, including imports and the upgrade() and downgrade() functions. Use op.create_table with all columns and constraints. Do not include any data seeding.

Verify: run alembic upgrade head, then alembic downgrade base, then upgrade head again—a migration that can't round-trip will bite you later. Compare the resulting tables (\d users in psql, or sqlite3 app.db.schema) against schema.json.

4. Create Pydantic Schemas for Validation

To handle input validation and serialization, you need Pydantic schemas. This prompt asks for schemas for creating and reading each entity.

Based on the SQLAlchemy models, generate Pydantic schemas for the User, Post, and Comment entities. For each, create a base schema, a create schema (for POST requests), and a read schema (for responses). Use Pydantic v2 syntax. Ensure fields match the models and include validation where appropriate (e.g., email format, string length). Output only the schema classes.

What good looks like: class UserCreate(UserBase) carrying email: EmailStr and password: str = Field(min_length=8), and class UserRead(UserBase) adding id: int with model_config = ConfigDict(from_attributes=True).

Verify: the read schema must include id and must not include password—leaking a hash in a response is the classic miss here.

5. Build Repository Layer for Data Access

Separate data access logic into a repository layer. This prompt asks the LLM to generate repository classes with CRUD methods.

Create a repository layer for the User, Post, and Comment models. For each, write a class with methods: get_by_id, get_all, create, update, delete. Use SQLAlchemy session. Include type hints and docstrings. Do not include any business logic or HTTP handling. Output the repository classes in a single file repositories.py.

Verify: every method should take db: Session as its first argument and contain only query/commit calls—no raise HTTPException, no email-sending, no permission checks. If you see those, the model has bled the service layer upward; cut them out before continuing.

6. Implement Service Layer with Business Logic

Services orchestrate repositories and contain business rules. This prompt asks for service classes that use the repositories.

Create a service layer for User, Post, and Comment. Each service should use the corresponding repository. Implement methods: create_user, get_user, update_user, delete_user, etc. Include validation (e.g., check if user exists before update) and raise custom exceptions. Output the service classes in services.py. Do not include HTTP-specific code.

Verify: services should import repositories and raise your own exceptions (e.g. NotFoundError), never HTTPException. Grep for fastapi in services.py—there should be zero hits.

7. Generate API Routes with FastAPI

Now expose the services via HTTP. This prompt asks for FastAPI routers with proper request/response models and dependency injection.

Create FastAPI routers for users, posts, and comments. Use the Pydantic schemas for request and response bodies. Inject the service layer via dependencies. Implement endpoints: POST /users, GET /users/{id}, PUT /users/{id}, DELETE /users/{id}, and similarly for posts and comments. Include status codes and error handling. Output the router files in a routers/ directory.

Verify: start the app with uvicorn main:app --reload and open /docs. Every endpoint should appear with the right request and response schema; if a body shows as a generic object, the router isn't wired to the Pydantic model.

8. Add Input Validation and Error Handling Middleware

To ensure robustness, add validation and error handling. This prompt asks for middleware or exception handlers.

Add global exception handlers for FastAPI to catch custom exceptions (e.g., NotFound, ValidationError) and return appropriate JSON responses with status codes. Also, add request validation using Pydantic models (already done in routes). Output the exception handlers in main.py or a separate file.

Verify: request a nonexistent id and confirm you get a 404 with a JSON body, not a 500 traceback.

9. Write Unit Tests for Services and Repositories

Tests are crucial. This prompt asks for pytest tests for the service and repository layers.

Write pytest tests for the UserService and UserRepository. Use an in-memory SQLite database for testing. Test create, read, update, delete operations. Include fixtures for database session and sample data. Output the test file test_user.py.

Verify: run pytest -q. A green run is necessary but not sufficient—open the file and confirm the tests assert on returned values, not just that no exception was raised. More on the topic: “Green Tests, Broken Contracts: 12 LLM Prompts That Hunt Reentrancy, Oracle Holes, and Gas Leaks Before Your Solidity Audit”.

10. Create Integration Tests for API Endpoints

Integration tests ensure the whole stack works. This prompt asks for tests using TestClient.

Write integration tests for the user endpoints using FastAPI's TestClient. Test POST /users, GET /users/{id}, PUT, DELETE. Use a test database. Output test_api_users.py.

Verify: each test should assert the status code and a field of the response body (e.g. the returned email matches what was posted).

11. Generate a Dockerfile and docker-compose for Easy Setup

To make the skeleton runnable anywhere, ask for containerization.

Create a Dockerfile for the FastAPI application and a docker-compose.yml that includes the app and a PostgreSQL database. Use environment variables for database connection. Output both files.

Verify: docker-compose up should bring up both services and the app should connect on first try; if it crashes on connection refused, the app is starting before Postgres is ready—add a healthcheck or retry.

12. Verify Coherence and Run the Application

Finally, ask the LLM to review all generated files for consistency and provide instructions to run.

Review all the code generated in steps 1-11. Check that imports are correct, that the database schema matches models, and that there are no missing dependencies. Provide a requirements.txt and a step-by-step guide to run the application locally (without Docker) and with Docker. Also, list any potential issues.

Verify: this step is the one most likely to be confidently wrong, because the model is reviewing from memory of what it wrote, not from your files. Paste the actual file contents back in, or better, run the checks yourself: pip install -r requirements.txt in a clean venv, then the run instructions end to end.

Failure Modes to Watch For

  • Context drift. By prompt 7 the model may have forgotten the exact field names from prompt 1. Fix: paste schema.json into every prompt that touches data, rather than saying "the schema from before."
  • Silent re-invention. The model "helpfully" adds a created_at column in the models that the migration lacks. Fix: the schema diff after steps 2 and 3.
  • Layer bleed. Repositories growing HTTP exceptions, services importing FastAPI. Fix: the greps above after steps 5 and 6.
  • Plausible-but-wrong review. Step 12's self-review misses real errors. Fix: trust the test run, not the summary.

Putting It All Together

By following these 12 prompts in sequence, you guide the LLM to produce a complete, coherent CRUD application skeleton. Each prompt builds on the previous one, and each has a cheap check you run before moving on—that check, not the prompt wording, is what keeps the pieces fitting together. You'll end up with a project that has proper layering, migrations, validation, tests, and containerization—ready for you to extend. More on the topic: “Go for Backend: What Building Reliable and Fast Backends Actually Demands — and Where Beginners Stumble”.

The key is to be explicit and incremental. Don't ask for everything at once, and always verify the output of each step before moving on. With this approach, you turn the LLM into a reliable pair programmer that delivers a working foundation, not a pile of fragments. More on the topic: “13 Prompts That Turn an LLM Into a React Native Teammate: From Navigation and FlatList to the App Store Build”.

Now, try it with your own stack. Start with the schema prompt, and iterate. You'll be surprised how much time you save when the skeleton actually runs.

AssetMaterials for this article

A document from this article — download and apply it.

  • DOCX12-Prompt CRUD Skeleton Prompt Pack.docxDOCX · 39.7 KBDownload
← All posts

Ask AI about this article

Ask a question about this article — ASI Biont will answer based on its text and the attached files.