AI for REST API Design — Generate OpenAPI Specs and Consistent Endpoints
Advertisement
Introduction
Why This Matters
API design is high-leverage work: a poorly designed API creates technical debt that compounds across every client that consumes it. Resource naming inconsistencies, missing error codes, undocumented edge cases, and authentication gaps are all problems that are cheap to fix before the API ships and expensive to fix after. AI tools accelerate API design by generating consistent drafts, surfacing common mistakes, and producing OpenAPI specs that become living documentation. This guide focuses on making AI output reliable enough to base production API design on.
Describing Resources and Generating Endpoint Designs
The most effective approach is to describe the domain in plain English, then ask for a RESTful endpoint design.
Prompt:
Design a RESTful API for a project management tool with these resources:
- Projects (owned by a team)
- Tasks (belong to a project, assigned to a user)
- Comments (belong to a task)
Include: resource URLs, HTTP methods, request/response body shapes,
status codes for success and common errors, and pagination for list endpoints.
Use snake_case for JSON keys.AI output (excerpt):
GET /projects List all projects for the authenticated team
POST /projects Create a new project
GET /projects/:id Get a single project
PATCH /projects/:id Update project fields
DELETE /projects/:id Delete a project (and all its tasks)
GET /projects/:id/tasks List tasks in a project (paginated)
POST /projects/:id/tasks Create a task in a project
GET /projects/:id/tasks/:task_id Get a single task
PATCH /projects/:id/tasks/:task_id Update task fields
DELETE /projects/:id/tasks/:task_id Delete a task
Response shape (GET /projects/:id):
{
"id": "proj_abc123",
"name": "Website Redesign",
"status": "active",
"created_at": "2026-03-01T10:00:00Z",
"task_count": 12
}
Error responses:
404: { "error": "not_found", "message": "Project not found" }
403: { "error": "forbidden", "message": "Access denied" }
422: { "error": "validation_error", "fields": { "name": "required" } }This becomes the starting point for design review, not the final design.
Generating OpenAPI YAML
Once the design is agreed on, ask the AI to produce the OpenAPI specification:
openapi: 3.1.0
info:
title: Project Management API
version: 1.0.0
paths:
/projects:
get:
summary: List projects
operationId: listProjects
parameters:
- name: page
in: query
schema:
type: integer
default: 1
- name: per_page
in: query
schema:
type: integer
default: 20
maximum: 100
responses:
'200':
description: Paginated list of projects
content:
application/json:
schema:
$ref: '#/components/schemas/ProjectList'
post:
summary: Create project
operationId: createProject
requestBody:
required: true
content:
application/json:
schema:
$ref: '#/components/schemas/ProjectCreate'
responses:
'201':
description: Project created
content:
application/json:
schema:
$ref: '#/components/schemas/Project'
'422':
description: Validation error
content:
application/json:
schema:
$ref: '#/components/schemas/ValidationError'
components:
schemas:
Project:
type: object
properties:
id:
type: string
example: proj_abc123
name:
type: string
status:
type: string
enum: [active, archived]
created_at:
type: string
format: date-timeThis YAML can be imported directly into Swagger UI, Stoplight, or Postman.
Reviewing Existing APIs for Inconsistencies
Paste your existing API documentation or routes and ask for a consistency audit:
Review this list of API endpoints for inconsistencies in naming,
HTTP method usage, error response format, and pagination:
GET /getUserById/:id
POST /create-task
GET /tasks?user=:id
PUT /task/:id/done
DELETE /remove-comment/:idAI findings:
Inconsistencies found:
1. Naming: Mix of camelCase (/getUserById), kebab-case (/create-task),
and verb-prefixed (/remove-comment). REST convention uses noun-based
plural paths: /users/:id, /tasks, /comments/:id.
2. HTTP methods: PUT /task/:id/done should be PATCH /tasks/:id with
body { "status": "done" }. Don't encode state in the URL.
3. Query parameter naming: ?user=:id should be ?user_id=:id for clarity.
4. Singular vs plural: /task/:id should be /tasks/:id (plural resources).
Recommended standardized routes:
GET /users/:id
POST /tasks
GET /tasks?user_id=:id
PATCH /tasks/:id
DELETE /comments/:idGenerating FastAPI Implementation from OpenAPI
Once the spec exists, AI can generate the FastAPI implementation:
from fastapi import APIRouter, HTTPException, Query
from pydantic import BaseModel
from typing import Optional
router = APIRouter(prefix="/projects", tags=["projects"])
class ProjectCreate(BaseModel):
name: str
description: Optional[str] = None
class ProjectResponse(BaseModel):
id: str
name: str
description: Optional[str]
status: str
created_at: str
@router.get("", response_model=list[ProjectResponse])
async def list_projects(
page: int = Query(1, ge=1),
per_page: int = Query(20, ge=1, le=100),
):
offset = (page - 1) * per_page
# ... implementation
return projects
@router.post("", response_model=ProjectResponse, status_code=201)
async def create_project(body: ProjectCreate):
# ... implementation
return project
@router.get("/{project_id}", response_model=ProjectResponse)
async def get_project(project_id: str):
project = await db.get_project(project_id)
if not project:
raise HTTPException(status_code=404, detail="Project not found")
return projectCommon Mistakes
- Accepting AI endpoint naming without review: AI defaults to common REST conventions but may not match your existing API's established patterns.
- Not specifying error response format: Specify your error schema in the prompt or AI will invent one that may not match what clients expect.
- Skipping authentication design: AI often omits auth from the first draft. Explicitly ask "How should authentication work? Include auth headers in every endpoint."
- Not versioning from day one: Ask the AI to include a versioning strategy (URL versioning
/v1/, header versioning) in the initial design.
Best Practices
- Provide the AI with examples of your existing API patterns so new endpoints stay consistent
- Generate the OpenAPI spec before generating implementation code — spec first forces clarity on contracts
- Ask the AI to include error scenarios for every endpoint, not just the happy path
- Import the generated OpenAPI YAML into Swagger UI immediately to catch obvious issues before coding
- Review the design with the teams that will consume the API before finalizing — AI does not know your clients' constraints
Key Takeaways
- AI generates consistent RESTful API designs fastest when given a plain-English description of the domain and its resources
- OpenAPI YAML generated by AI can be imported directly into Swagger UI, Stoplight, or Postman for visual review
- AI consistency audits on existing APIs reliably catch naming, method, and response format inconsistencies
- Specifying your error response schema in the prompt prevents AI from inventing a format inconsistent with existing clients
- FastAPI automatically converts Pydantic models and docstrings into OpenAPI documentation — AI-generated code is self-documenting
- Generate the API spec before implementation code — the spec forces design decisions to be made explicitly
- Authentication, versioning, and pagination must be explicitly requested — AI omits them in initial drafts
- AI API design is a first draft for human review, not a final artifact — the consuming teams should validate the contract
Advertisement