Skip to content
Intermediate 45 min 6 Steps

Build APIs with AI — Design, Code & Document

Building a well-designed API is hard: you need to think through your schema upfront, write consistent endpoint logic, handle auth and errors correctly, generate documentation that developers actually ...

What You'll Build

6
Steps
45m
Time
4
Tools
5
Prompts
Difficulty Intermediate
Best for
api developmentbackendrest apisoftware engineering

Step-by-Step Guide

Follow this 6-step workflow to complete in about 45 min.

Design YourGenerate EndpointWrite MiddlewareAuto-Generate APIPolish YourTest Your
1

Design Your API Schema

Before writing any code, define your data models, endpoint structure, and design decisions with AI. A good schema conversation catches problems that are painful to fix after you've written 500 lines of code.

Prompt Template
Help me design an API for a [describe your application, e.g., 'task management app' / 'e-commerce platform' / 'user analytics service']. **What I need the API to do:** [List the core actions your API needs to support, e.g.: - Users can register, log in, and manage their profile - Users can create, read, update, and delete tasks - Tasks can be assigned to users and tagged with labels - Admin users can view usage stats across all users] **Technical context:** - Backend language/framework: [e.g., Node.js + Express / Python + FastAPI / Go + Gin / Ruby on Rails] - Database: [e.g., PostgreSQL / MySQL / MongoDB] - Authentication approach: [e.g., JWT / OAuth2 / API Keys / Sessions] - This API will be consumed by: [e.g., a React frontend / mobile app / third-party developers / internal microservices] - API style preference: [REST / GraphQL / gRPC — or help me decide] **Please produce:** 1. **Data Models**: List each entity (resource), its fields, field types, and constraints (required, unique, max length, etc.). Flag any many-to-many relationships that need junction tables. 2. **Endpoint Map**: A table of all endpoints with HTTP method, path, what it does, authentication required (yes/no), and any pagination/filtering support needed. 3. **Request/Response Shapes**: For each endpoint, show the expected request body (if POST/PUT/PATCH) and the response body structure with example values. 4. **Design Decisions to Make**: Flag any choices I haven't specified where there are meaningful tradeoffs — e.g., 'Should task deletion be soft delete (archived) or hard delete? Soft delete lets users undo, hard delete keeps the DB clean.' Give me your recommendation for each. 5. **Potential Problems**: Point out anything in my requirements that could become a scaling, security, or consistency problem later. Format the endpoint map as a table. Use TypeScript interface syntax or JSON Schema for the data models — whichever is cleaner for my stack.
Tip: Don't skip this step and jump straight to code generation. Ten minutes of schema design conversation will save you hours of refactoring. Pay particular attention to the design decisions the AI flags — those are the ones that bite you in production.
2

Generate Endpoint Code

With your schema finalized, generate the actual route handlers and controller logic. Give AI the full context of your project structure so the generated code fits in cleanly.

Prompt Template
Generate the [framework, e.g., Express / FastAPI / Gin] code for the following API endpoints. I'll give you the schema we designed and my project structure so the code fits in correctly. **Endpoints to generate:** [List the specific endpoints you want, e.g.: - POST /api/tasks — Create a new task - GET /api/tasks — List tasks (with pagination and filtering) - GET /api/tasks/:id — Get a single task - PUT /api/tasks/:id — Update a task - DELETE /api/tasks/:id — Delete a task (soft delete)] **Data models:** ``` [Paste the data model definitions from Step 1] ``` **My project structure:** ``` [Paste your directory tree or describe it, e.g.: src/ routes/ ← route definitions go here controllers/ ← business logic goes here models/ ← database models go here middleware/ ← auth, validation, error handling utils/ ← helpers] ``` **Conventions to follow:** - Error handling: [e.g., centralized error handler / inline try-catch / result pattern] - Response format: [e.g., { success: true, data: {...} } / { data: {...}, meta: {...} } / bare object] - Authentication: [e.g., JWT middleware that populates req.user / API key in header] - Validation: [e.g., Zod / Joi / express-validator / Pydantic / manual] - ORM/DB library: [e.g., Prisma / Sequelize / SQLAlchemy / GORM / raw SQL] **For each endpoint, generate:** 1. Route definition (with middleware chain) 2. Controller/handler function with full business logic 3. Input validation schema 4. Database query/ORM call 5. Error handling for common failure cases (not found, validation error, duplicate, unauthorized) 6. Inline comments for any non-obvious logic Do NOT generate authentication implementation yet — I'll handle that separately. Do NOT generate database migrations yet — just the query logic. After the code, list any assumptions you made that I should verify.
Tip: If you're using Cursor, open your existing routes or controllers file before prompting — it will pick up your actual conventions from context. For ChatGPT/Claude, paste a real example file from your codebase and say 'follow this exact pattern.'
3

Write Middleware (Auth, Validation, Error Handling)

Middleware is the scaffolding that makes an API production-ready. Auth, input validation, rate limiting, and error formatting are repetitive to write but critical to get right — exactly where AI adds value.

Prompt Template
Generate production-quality middleware for my [framework] API. Here's what I need: **1. Authentication Middleware** Approach: [JWT / API Key / OAuth2 token introspection / Session cookie] Specific requirements: - [e.g., JWT: Extract token from Authorization header, verify with secret, populate req.user with user ID + role] - [e.g., Support both user tokens and service-to-service API keys] - [e.g., Roles: 'user', 'admin', 'readonly' — endpoint access depends on role] Generate: - The authentication middleware function - An authorization helper (e.g., requireRole('admin')) that can wrap specific routes - How to apply it globally vs. per-route - Correct error responses for: missing token, expired token, invalid token, insufficient permissions **2. Input Validation Middleware** Validation library: [Zod / Joi / express-validator / Pydantic / class-validator / manual] Generate: - A generic validation middleware factory that takes a schema and validates req.body - Example schemas for: [e.g., 'create task' body / 'update task' body / pagination query params] - Consistent error response format when validation fails (include which fields failed and why) - How to validate: request body, query params, and path params **3. Error Handling Middleware** Generate a centralized error handler that: - Catches all unhandled errors in route handlers - Maps error types to HTTP status codes (validation → 400, auth → 401/403, not found → 404, conflict → 409, server error → 500) - Returns consistent JSON error format: { error: { code: string, message: string, details?: any } } - Logs the full error internally (with stack trace) but only returns safe messages to the client - Does NOT expose stack traces or internal error details to clients in production - Handles async errors correctly (common mistake: async errors not caught by Express error handler) **4. Rate Limiting** (if applicable) - [e.g., 100 requests per minute per IP for public endpoints / 1000 per minute for authenticated users] - What library to use and how to configure it For each piece of middleware, show where it gets wired up in my app (app.use vs. router.use vs. per-route).
Tip: The most common middleware mistakes: (1) async error handling — if you're using Express, errors thrown inside async route handlers won't be caught by your error handler unless you use express-async-errors or wrap everything in try-catch; (2) validation middleware that only validates the body but ignores query params and path params where injection attacks can also live.
4

Auto-Generate API Documentation

Good API docs are the difference between developers loving your API and emailing you with basic questions. AI can generate OpenAPI specs, README-style docs, and even interactive Postman collections from your code.

Prompt Template
Generate API documentation for my endpoints. Here's the code: ```[language] [Paste your route definitions and/or controller code] ``` **Documentation I need:** **1. OpenAPI 3.0 Specification (YAML)** Generate a complete openapi.yaml that includes: - API info (title, version, description) - All endpoints with their HTTP methods and paths - Request body schemas with field descriptions, types, and required/optional status - Response schemas for success (200/201) and common error cases (400, 401, 403, 404, 500) - Authentication scheme definition (Bearer token / API Key header / etc.) - Example values for every field - Query parameter documentation for filtering and pagination - Tags to group endpoints logically This YAML should be valid and importable into Swagger UI, Redoc, or Postman without modification. **2. Developer README Section** Write a markdown section titled 'API Reference' that includes: - Authentication guide: how to get a token/key and include it in requests - Base URL and versioning - A quick-start example showing a complete request-response cycle (with curl) - Error response format with a table of error codes and what they mean - Rate limiting explanation (if applicable) - Pagination guide (if applicable): how cursor/offset pagination works, what fields to use **3. Postman Collection JSON** Generate a Postman collection (v2.1 format) with: - All endpoints as requests - Pre-populated example request bodies - A {{baseUrl}} environment variable - A {{token}} variable for auth headers - Brief description for each request For descriptions, write them for the developer consuming this API, not the developer who built it. Assume they know what REST APIs are but don't know anything about this specific system.
Tip: Once you have the OpenAPI YAML, plug it into Swagger UI (free, self-hosted) or Redoc to get a live interactive doc site instantly. If you're using FastAPI or NestJS, you may be able to generate the spec directly from decorators in your code — ask AI to help you add the right annotations instead of writing the YAML from scratch.
5

Polish Your Output with Coda One

Give your AI-generated content a final polish — fix grammar, improve readability, and make it sound more natural.

Tip: Free tools, no signup required. Just paste your text and go.
6

Test Your Endpoints

Generate a complete test suite for your API — covering happy paths, auth failures, validation errors, and edge cases. API testing is well-suited to AI generation because the pattern is formulaic: given a request, assert a response.

Prompt Template
Write a complete API test suite for my endpoints. Here's what I have: **Endpoints to test:** [List or paste your route definitions] **Test framework:** [e.g., Jest + Supertest / Pytest + httpx / Go testing + net/http/httptest / RSpec + Rails request specs] **Database strategy for tests:** [e.g., Use a test database that gets wiped before each test / Use an in-memory database / Mock the database layer] **For each endpoint, generate tests covering:** 1. **Successful cases (2xx):** - Valid request with all fields returns correct response body - Valid request with only required fields (optional fields omitted) still works - Response body contains exactly the expected fields (no extra, no missing) - Correct HTTP status code (200 vs 201 vs 204) 2. **Authentication failures (401/403):** - Request without auth token → 401 - Request with expired token → 401 - Request with valid token but insufficient permissions → 403 3. **Validation failures (400):** - Missing required field → 400 with useful error message - Field with wrong type (string where number expected) → 400 - Field exceeding max length → 400 - Invalid enum value → 400 4. **Not found (404):** - Request for resource with ID that doesn't exist → 404 - Request for resource belonging to a different user → 404 (not 403 — don't reveal existence) 5. **Conflict/business logic errors (409/422):** - [Any domain-specific error cases, e.g., trying to add a duplicate, exceeding a quota, invalid state transition] **Test setup to generate:** - A test factory/fixture function that creates a valid authenticated user and returns their token - A factory for each main resource type (e.g., createTestTask()) that inserts test data and returns the object - Before/after hooks to set up and tear down test data **Quality requirements:** - Each test name must describe the scenario and expected outcome: 'POST /tasks — returns 400 when title is missing' - Tests must be independent (no test depends on state left by another test) - Use realistic but simple test data (not 'aaa', 'test123' — use real-looking values) Also: point out any endpoint behavior that is ambiguous or untestable from the code — this often reveals missing specs.
Tip: Run your tests against a real (test) database, not mocks of your database layer. Mocking the DB gives you tests that pass even when your SQL queries are wrong. The only things that should be mocked are external services (email, payment processors, third-party APIs) and the system clock.

Recommended Tools for This Scenario

MCP Servers for This Scenario

Browse all MCP servers →

Frequently Asked Questions

Should I design the schema first, or just start generating code?
Always design the schema first. The most expensive mistakes in API development are data model decisions: choosing the wrong relationships, not planning for the fields you'll need later, or designing endpoints that don't match how your clients actually want to consume data. A 15-minute schema conversation with Claude can surface these problems before you've written a line of code. Once you start generating code against a bad schema, fixing it means touching every layer of the stack.
Can AI generate production-ready API code, or do I always need to review and fix it?
AI generates code that is usually logically correct and follows common patterns, but it often makes assumptions you need to verify: it may use a slightly different error format than the rest of your codebase, miss a business rule you didn't mention, or use a library function in a way that works but isn't ideal for your setup. Treat AI-generated code as a very good first draft — review it the same way you'd review a PR from a capable but context-lacking junior developer. The more context you give (existing code examples, your conventions, your project structure), the less cleanup you'll need.
Which tool is best for API development — Claude, ChatGPT, or Cursor?
Use all three for different tasks. Claude and ChatGPT are best for design conversations (schema design, architecture decisions) because they can reason through tradeoffs in a dialogue. Cursor is best for generating and editing the actual code because it can read your existing files and match your conventions automatically. GitHub Copilot is best for filling in boilerplate inside an editor while you type. A practical workflow: design with Claude, generate the skeleton with Claude or ChatGPT, then switch to Cursor or Copilot for the ongoing implementation.
How do I keep AI-generated API code consistent across a large project?
The key is giving AI a style reference every time. Keep a short 'API conventions' document that specifies your response format, error format, authentication approach, and naming conventions. Paste it at the top of every code-generation prompt. In Cursor, you can put this in a .cursorrules file so it's automatically included. When you generate a new endpoint and then look at the output, ask 'does this match my existing code?' and have AI diff it against a real example file if needed.

Coda One Tools for This Scenario

Try AI Humanizer

Transform AI-generated text into natural, human-sounding writing that bypasses detection tools.

Try Free

Try AI Rewriter

Rewrite and improve any text while preserving meaning and adding a human touch.

Try Free

Try AI Grammar Checker

Find and fix grammar, spelling, and punctuation errors with detailed explanations.

Try Free
api developmentbackendrest apisoftware engineeringdocumentationtestingprogramming
Was this helpful?

Get More Scenarios Like This

New AI guides, top tools, and prompt templates — curated weekly.