API Development Architect
Designs a production-ready RESTful API with OpenAPI spec, secure auth, validation, and scalable architecture.
// prompt
You are a **senior API architect** with deep experience shipping secure, scalable RESTful services. Design a production-ready API for the project below, balancing clean contracts, security, and developer experience.
## Project Context
- **API Name:** {{api_name}}
- **Business Domain:** {{business_domain}}
- **Core Resources:** {{resource_list}}
- **Stack:** {{language_and_framework}} over {{database}}
- **Authentication:** {{authentication_method}}
- **Expected Scale:** {{expected_traffic_scale}}
## What To Deliver
### 1. Resource & Endpoint Design
- Model each resource and its relationships.
- Define RESTful, versioned routes (`/api/v1/...`) with the correct HTTP methods, status codes, and JSON request/response shapes.
- Specify pagination, filtering, and sorting conventions for collections.
### 2. OpenAPI 3.0 Specification
Produce a valid OpenAPI 3.0 spec covering the main endpoints, including parameters, request bodies, response schemas, and reusable components.
### 3. Implementation Skeleton
Provide idiomatic {{language_and_framework}} code for the key endpoints, showing routing, a typed data model/schema, dependency injection, and structured error handling.
### 4. Security & Reliability
- Apply {{authentication_method}} with authorization checks per endpoint.
- Add input validation, consistent error envelopes, rate limiting, and idempotency where relevant.
- Note CORS, secrets handling, and audit-logging considerations.
### 5. Scalability Notes
Recommend caching, indexing, and connection-pooling strategies suited to {{expected_traffic_scale}}.
## Output Format
1. A short architecture summary.
2. An endpoint table (Method · Path · Purpose · Auth).
3. The OpenAPI spec in a YAML code block.
4. Implementation code in fenced blocks.
5. A checklist of security and performance safeguards.
Ask clarifying questions only if a critical requirement (data model, auth, or scale) is ambiguous; otherwise state your assumptions and proceed.
Fill in the variables
Example response
🚀 RESTful API Design
📋 API Specification
openapi: 3.0.0
info:
title: Task Management API
version: 1.0.0
description: Professional task management system
paths:
/api/v1/tasks:
get:
summary: Get tasks with filtering and pagination
parameters:
- name: status
in: query
schema:
type: string
enum: [pending, completed, in_progress]
- name: limit
in: query
schema:
type: integer
default: 20
maximum: 100
responses:
200:
description: Tasks retrieved successfully
content:
application/json:
schema:
type: object
properties:
data:
type: array
items:
$ref: "#/components/schemas/Task"
meta:
$ref: "#/components/schemas/PaginationMeta"
post:
summary: Create new task
requestBody:
required: true
content:
application/json:
schema:
$ref: "#/components/schemas/CreateTaskRequest"
responses:
201:
description: Task created successfully
400:
description: Validation error
components:
schemas:
Task:
type: object
properties:
id:
type: integer
title:
type: string
status:
type: string
enum: [pending, completed, in_progress]
created_at:
type: string
format: date-time
🔧 FastAPI Implementation
from fastapi import FastAPI, HTTPException, Depends, Query
from fastapi.security import HTTPBearer
from pydantic import BaseModel, Field
from typing import List, Optional
from datetime import datetime
from enum import Enum
import asyncio
app = FastAPI(
title="Task Management API",
version="1.0.0",
description="Professional task management system"
)
# Security
security = HTTPBearer()
class TaskStatus(str, Enum):
PENDING = "pending"
IN_PROGRESS = "in_progress"
COMPLETED = "completed"
class TaskBase(BaseModel):
title: str = Field(..., min_length=1, max_length=200)
description: Optional[str] = Field(None, max_length=1000)
priority: int = Field(1, ge=1, le=5)
class TaskCreate(TaskBase):
pass
class TaskResponse(TaskBase):
id: int
status: TaskStatus = TaskStatus.PENDING
created_at: datetime
updated_at: datetime
class Config:
from_attributes = True
class PaginationMeta(BaseModel):
total: int
page: int
per_page: int
has_next: bool
class TaskListResponse(BaseModel):
data: List[TaskResponse]
meta: PaginationMeta
# Dependency for authentication
async def get_current_user(token: str = Depends(security)):
"""Validate JWT token and return user."""
# In real implementation, decode and validate JWT
if not token.credentials:
raise HTTPException(401, "Authentication required")
return {"user_id": 1, "username": "john_doe"}
# Rate limiting dependency
async def rate_limit():
"""Simple rate limiting implementation."""
await asyncio.sleep(0.01) # Simulate rate limiting
return True
@app.get("/api/v1/tasks", response_model=TaskListResponse)
async def get_tasks(
status: Optional[TaskStatus] = None,
limit: int = Query(20, le=100),
offset: int = Query(0, ge=0),
user=Depends(get_current_user),
_=Depends(rate_limit)
):
"""Get tasks with filtering and pagination."""
try:
# Simulate database query
tasks = [] # Would fetch from database
total = 0 # Would count from database
return TaskListResponse(
data=tasks,
meta=PaginationMeta(
total=total,
page=offset // limit + 1,
per_page=limit,
has_next=(offset + limit) < total
)
)
except Exception as e:
raise HTTPException(500, f"Internal server error: {{str(e)}}")
@app.post("/api/v1/tasks", response_model=TaskResponse, status_code=201)
async def create_task(
task: TaskCreate,
user=Depends(get_current_user),
_=Depends(rate_limit)
):
"""Create a new task."""
try:
# Validate and create task
new_task = TaskResponse(
id=123,
**task.model_dump(),
status=TaskStatus.PENDING,
created_at=datetime.now(),
updated_at=datetime.now()
)
return new_task
except ValueError as e:
raise HTTPException(400, f"Validation error: {{str(e)}}")
except Exception as e:
raise HTTPException(500, f"Internal server error: {{str(e)}}")
@app.get("/api/v1/health")
async def health_check():
"""Health check endpoint."""
return {"status": "ok", "timestamp": datetime.now()}
if __name__ == "__main__":
import uvicorn
uvicorn.run(app, host="0.0.0.0", port=8000)
🔒 Security Features
- JWT Authentication with Bearer tokens
- Input validation using Pydantic
- Rate limiting protection
- Comprehensive error handling
- CORS configuration
📖 API Documentation
Automatic interactive docs available at /docs and /redoc
Related prompts
Programming & Development
Advanced Debugging Assistant
Diagnoses bugs in your code, pinpoints root causes, and delivers fixed code with prevention tips.
Programming & Development
Algorithm Design Expert
Designs, analyzes, and optimizes algorithms with multiple approaches, Big-O complexity analysis, production code, and tests.
Programming & Development
Code Review Expert
Performs a rigorous senior-level code review covering correctness, design, performance, and security with prioritized, actionable fixes.
Programming & Development
JavaScript & React Development Expert
Generates production-grade, typed React and JavaScript code with tests, accessibility, and clear architectural reasoning.