# Production Ready APIs Reference

> **Type**: Reference document (not a workflow skill)
> **Use**: Checklist for API development and review

---

## API Design Principles

### RESTful Conventions
- [ ] Use appropriate HTTP methods (GET for retrieval, POST for creation, PUT/PATCH for updates, DELETE for deletion)
- [ ] Use resource-based URLs (nouns, not verbs: `/users/{id}`, not `/getUser`)
- [ ] Implement proper status codes (200, 201, 204, 400, 401, 403, 404, 500)
- [ ] Use plural nouns for collection endpoints
- [ ] Support pagination for list endpoints
- [ ] Use query parameters for filtering, sorting, and pagination
- [ ] Use nested resources for relationships: `/users/{id}/posts`

### Request/Response Design
- [ ] Use consistent JSON structure across all endpoints
- [ ] Include pagination metadata in list responses (total, page, page_size)
- [ ] Use standardized response envelope: `{ data, errors, meta }`
- [ ] Use camelCase for JSON keys (or snakeCase consistent with language convention)
- [ ] Include timestamps for created_at and updated_at fields
- [ ] Use ISO 8601 format for all datetime fields
- [ ] Limit response payload size (use fields filtering or projections)
- [ ] Use HTTP compression (gzip, deflate) for large payloads

## Security

### Authentication & Authorization
- [ ] Implement proper authentication (JWT, OAuth2, API keys)
- [ ] Use HTTPS for all API endpoints
- [ ] Validate authentication tokens on each request
- [ ] Implement proper authorization checks (role-based, attribute-based)
- [ ] Use principle of least privilege for API access
- [ ] Implement rate limiting to prevent abuse
- [ ] Use secure token storage (HttpOnly, Secure, SameSite cookies)

### Input Validation
- [ ] Validate all input parameters (path, query, body, headers)
- [ ] Sanitize user input to prevent injection attacks
- [ ] Use parameterized queries to prevent SQL injection
- [ ] Validate file uploads (type, size, content)
- [ ] Implement request size limits
- [ ] Use schema validation (JSON Schema, Pydantic, etc.)
- [ ] Reject malformed requests with clear error messages

### Security Headers
- [ ] Set security headers: CSP, X-Frame-Options, X-Content-Type-Options
- [ ] Implement CORS policies correctly
- [ ] Set appropriate cache-control headers
- [ ] Remove sensitive headers in error responses
- [ ] Use secure cookie flags (HttpOnly, Secure, SameSite)

## Error Handling

### Error Response Format
- [ ] Return consistent error response structure
- [ ] Include error code and human-readable message
- [ ] Provide actionable error details
- [ ] Log errors server-side with sufficient context
- [ ] Don't expose sensitive information in error responses
- [ ] Include request ID for tracing
- [ ] Use appropriate HTTP status codes for error types

### Error Categories
| Code | Name | Use Case |
|------|------|----------|
| 400 | Bad Request | Invalid input or malformed request |
| 401 | Unauthorized | Missing or invalid authentication |
| 403 | Forbidden | Valid auth but insufficient permissions |
| 404 | Not Found | Resource doesn't exist |
| 409 | Conflict | Request conflicts with current state |
| 422 | Unprocessable Entity | Semantic validation errors |
| 429 | Too Many Requests | Rate limit exceeded |
| 500 | Internal Server Error | Unexpected server errors |
| 503 | Service Unavailable | Service maintenance or overload |

## Testing

### Test Categories
- [ ] **Unit Tests**: Test all business logic independently
- [ ] **Integration Tests**: Test API endpoints end-to-end
- [ ] **Contract Tests**: Validate responses match OpenAPI spec
- [ ] **Performance Tests**: Load test critical endpoints

### Test Coverage
- [ ] Test validation logic thoroughly
- [ ] Test error paths and edge cases
- [ ] Test authentication and authorization
- [ ] Test concurrent requests
- [ ] Test rate limiting

## Documentation

### Required Documentation
- [ ] OpenAPI/Swagger specification
- [ ] All endpoints with request/response examples
- [ ] Authentication requirements
- [ ] Rate limits and quotas
- [ ] Error response documentation
- [ ] Quick start guide

## Versioning

### Strategy
- [ ] Choose versioning approach (URL path, header, query parameter)
- [ ] Document versioning policy
- [ ] Support multiple versions concurrently
- [ ] Communicate deprecation timelines
- [ ] Use semantic versioning (MAJOR.MINOR.PATCH)

## Observability

### Logging
- [ ] Log all API requests with metadata
- [ ] Include request/response correlation IDs
- [ ] Use structured logging (JSON format)

### Monitoring
- [ ] Monitor request rate and error rate
- [ ] Monitor response times (p50, p95, p99)
- [ ] Set up alerts for anomalies

## Common Anti-Patterns

### Security
- ❌ Hardcoding credentials or API keys
- ❌ Not validating user input
- ❌ Exposing sensitive data in error messages
- ❌ Missing authentication/authorization checks

### Design
- ❌ Using verbs instead of nouns in URLs
- ❌ Returning different structures for same resource
- ❌ Missing pagination on list endpoints
- ❌ Not using HTTP status codes correctly

### Performance
- ❌ N+1 query problems
- ❌ Missing database indexes
- ❌ Not caching expensive operations
- ❌ Returning too much data in responses

## Review Questions

1. What are the security implications of this API change?
2. How does this change affect existing API consumers?
3. Are all error paths properly handled?
4. What authentication/authorization is required?
5. How will this API perform under load?
6. Is this change backward compatible?
7. Is the API documentation up to date?
