## API Design Framework
### Phase 1: Requirements Analysis
```
I need to design an API for:
**Domain:** [What business domain does this serve]
**Consumers:** [Who will use this API - mobile, web, third-parties]
**Scale:** [Expected request volume and growth]
**Protocol:** [REST, GraphQL, gRPC, or hybrid]
Help me define API requirements:
1. **Resource Identification**
- What are the core entities/resources?
- What relationships exist between resources?
- Which operations (CRUD) are needed per resource?
2. **Consumer Analysis**
- Primary use cases for each consumer type
- Latency and performance requirements
- Offline/caching needs
- Authentication requirements
3. **Constraints**
- Existing system integrations
- Backward compatibility requirements
- Regulatory/compliance needs (GDPR, HIPAA)
- Rate limiting and quotas
4. **Non-Functional Requirements**
- Availability targets (99.9%, 99.99%)
- Response time SLAs
- Throughput requirements
```
### Phase 2: Resource Design
#### REST Resource Modeling
```
Design RESTful resources for:
**Domain:** [Description]
**Core Resources:** [List main entities]
For each resource, define:
1. **URI Structure**
- Collection endpoint: /api/v1/[resources]
- Instance endpoint: /api/v1/[resources]/{id}
- Nested resources: /api/v1/[parent]/{id}/[children]
2. **HTTP Methods**
- GET: Retrieve resource(s)
- POST: Create new resource
- PUT/PATCH: Update resource
- DELETE: Remove resource
- HEAD: Metadata only
3. **Query Parameters**
- Filtering: ?status=active&type=premium
- Sorting: ?sort=created_at:desc
- Pagination: ?limit=20&offset=40 or ?cursor=xyz
- Field selection: ?fields=id,name,email
4. **Response Structure**
- Success envelope: { data: {...}, meta: {...} }
- Collection envelope: { data: [...], meta: { total, page, limit } }
- Error envelope: { error: { code, message, details } }
5. **Relationships**
- Embedding: ?include=author,comments
- Links: HATEOAS approach with _links
Generate OpenAPI 3.0 specification for these resources.
```
#### GraphQL Schema Design
```
Design GraphQL schema for:
**Domain:** [Description]
**Primary Types:** [List main types]
Schema components:
1. **Type Definitions**
- Object types with fields and types
- Input types for mutations
- Enum types for fixed values
- Interface and Union types for polymorphism
2. **Query Design**
- Single resource: user(id: ID!): User
- Collection: users(filter: UserFilter, first: Int, after: String): UserConnection
- Nested queries: user { posts { comments } }
3. **Mutation Design**
- Create: createUser(input: CreateUserInput!): User!
- Update: updateUser(id: ID!, input: UpdateUserInput!): User!
- Delete: deleteUser(id: ID!): Boolean!
4. **Connection Pattern**
- Edges with cursor and node
- PageInfo with hasNextPage, endCursor
- Relay-style pagination
5. **Directives**
- @deprecated(reason: "...")
- @auth(requires: ADMIN)
- Custom directives for validation
Generate SDL schema with documentation comments.
```
### Phase 3: Error Handling & Security
```
Design error handling and security for the API:
**API Type:** [REST/GraphQL]
**Security Model:** [OAuth2, API Keys, JWT]
1. **Error Response Format**
{
"error": {
"code": "RESOURCE_NOT_FOUND",
"message": "User with ID 123 not found",
"details": [...],
"request_id": "abc-123",
"documentation_url": "https://api.example.com/docs/errors#RESOURCE_NOT_FOUND"
}
}
2. **HTTP Status Codes**
- 200 OK: Successful GET/PUT/PATCH
- 201 Created: Successful POST
- 204 No Content: Successful DELETE
- 400 Bad Request: Validation errors
- 401 Unauthorized: Missing/invalid auth
- 403 Forbidden: Insufficient permissions
- 404 Not Found: Resource doesn't exist
- 409 Conflict: Resource state conflict
- 422 Unprocessable Entity: Semantic errors
- 429 Too Many Requests: Rate limited
- 500/502/503: Server errors
3. **Authentication**
- OAuth2 flows: Authorization Code, Client Credentials
- JWT structure and claims
- API key handling
- Token refresh strategy
4. **Authorization**
- Role-based access control (RBAC)
- Resource-level permissions
- Field-level access control (GraphQL)
5. **Rate Limiting**
- Limits by tier: Free (100/hr), Pro (1000/hr)
- Headers: X-RateLimit-Limit, X-RateLimit-Remaining
- Retry-After header on 429
Generate security middleware implementation.
```
### Phase 4: Documentation & Versioning
```
Create API documentation and versioning strategy:
**API:** [Name and description]
**Current Version:** [e.g., v1]
**Breaking Changes Planned:** [List any]
1. **OpenAPI/Swagger Documentation**
- Complete endpoint descriptions
- Request/response examples
- Authentication requirements
- Error codes and meanings
2. **Versioning Strategy**
- URL path: /api/v1/users vs /api/v2/users
- Header: Accept-Version: v2
- Query param: ?version=2
3. **Deprecation Policy**
- Sunset header with deprecation date
- Migration guides
- Backward-compatible changes preferred
- Breaking change notification timeline (6 months)
4. **SDK Generation**
- OpenAPI Generator for client SDKs
- Language targets: TypeScript, Python, Go
- Versioned package releases
5. **Developer Portal**
- Interactive API explorer
- Authentication playground
- Code samples per endpoint
- Changelog and release notes
Generate complete OpenAPI specification and changelog template.
```
## Best Practices
1. **Consistency**: Use consistent naming, casing, and patterns across all endpoints
2. **Idempotency**: Make PUT/DELETE idempotent; use idempotency keys for POST
3. **Pagination**: Always paginate collections; prefer cursor over offset
4. **Filtering**: Support flexible filtering without over-engineering
5. **Versioning**: Plan for versioning from day one
6. **Caching**: Use ETags and Cache-Control headers appropriately
7. **HATEOAS**: Include links for discoverability when practical
8. **Validation**: Validate early; return clear, actionable error messages
## Example Session
**User**: "Design an API for a task management application with users, projects, and tasks."
**Response**:
> I'll design a RESTful API for task management:
>
> **Resource Hierarchy:**
>
> - /api/v1/users
> - /api/v1/projects
> - /api/v1/projects/{id}/tasks
> - /api/v1/tasks (flat access)
>
> **Key Endpoints:**
>
> ```yaml
> # Users
> GET /api/v1/users # List users (admin only)
> GET /api/v1/users/me # Current user profile
> PATCH /api/v1/users/me # Update profile
>
> # Projects
> GET /api/v1/projects # List user's projects
> POST /api/v1/projects # Create project
> GET /api/v1/projects/{id} # Get project details
> PATCH /api/v1/projects/{id} # Update project
> DELETE /api/v1/projects/{id} # Archive project
>
> # Tasks
> GET /api/v1/projects/{id}/tasks # List project tasks
> POST /api/v1/projects/{id}/tasks # Create task
> PATCH /api/v1/tasks/{id} # Update task
> DELETE /api/v1/tasks/{id} # Delete task
> POST /api/v1/tasks/{id}/complete # Mark complete (action)
> ```
>
> **Query Examples:**
>
> - `GET /api/v1/tasks?status=pending&assignee=me&sort=due_date:asc`
> - `GET /api/v1/projects?include=tasks,members&fields=id,name,task_count`
>
> Shall I generate the complete OpenAPI specification?
## Related Resources
- [OpenAPI Specification](https://spec.openapis.org/oas/latest.html)
- [JSON:API Specification](https://jsonapi.org/)
- [GraphQL Best Practices](https://graphql.org/learn/best-practices/)
- [REST API Design Rulebook](https://www.oreilly.com/library/view/rest-api-design/9781449317904/)