API Design Best Practices

Language: OpenAPI, YAML, JSON October 15, 2025

REST and GraphQL API design principles with modern best practices.

---
applyTo: "**/*.graphql, **/openapi.yml, **/swagger.yml"
---

# API Design Development Instructions (2025)

_Last updated: October 2025_

- Always use the fetch tool to look up API design best practices and documentation
- Design APIs that are intuitive, consistent, and easy to use
- Follow REST principles or GraphQL best practices appropriately
- Use proper HTTP methods and status codes
- Implement versioning strategy from the start
- Document APIs thoroughly with OpenAPI/Swagger or GraphQL schema

**REST API Design:**

- Use nouns for resource endpoints (e.g., /users, /products)
- Use HTTP methods appropriately (GET, POST, PUT, PATCH, DELETE)
- Implement proper URL structure (/api/v1/resources/{id})
- Use query parameters for filtering, sorting, pagination
- Return appropriate HTTP status codes
- Use HATEOAS for discoverability when appropriate

**GraphQL Design:**

- Design schema with clear types and relationships
- Use meaningful field names and descriptions
- Implement proper input validation
- Use DataLoader for N+1 query prevention
- Implement proper error handling
- Use fragments for reusable field selections

**HTTP Status Codes:**

- 200 OK: Successful GET, PUT, PATCH
- 201 Created: Successful POST with resource creation
- 204 No Content: Successful DELETE
- 400 Bad Request: Invalid input
- 401 Unauthorized: Missing or invalid authentication
- 403 Forbidden: Authenticated but not authorized
- 404 Not Found: Resource doesn't exist
- 500 Internal Server Error: Server-side error

**Request/Response Format:**

- Use JSON as default format
- Implement consistent response structure
- Include metadata (pagination, timestamps)
- Use camelCase for JSON property names
- Return meaningful error messages
- Include correlation IDs for tracking

**Error Handling:**

- Return consistent error response format
- Include error codes, messages, and details
- Provide actionable error messages
- Log errors with proper context
- Don't expose internal implementation details
- Use problem details (RFC 7807) for errors

**Versioning:**

- Use URL versioning (/api/v1/users)
- Version breaking changes only
- Support old versions for transition period
- Document deprecation timeline
- Use semantic versioning
- Communicate changes to API consumers

**Security:**

- Use HTTPS for all endpoints
- Implement authentication (JWT, OAuth 2.0)
- Use API keys for service-to-service communication
- Implement rate limiting
- Validate and sanitize all inputs
- Use CORS properly for browser access

**Authentication:**

- Use JWT tokens with proper expiration
- Implement refresh token mechanism
- Use OAuth 2.0 for third-party access
- Implement proper scope/permission system
- Use secure token storage
- Implement token revocation

**Pagination:**

- Use cursor-based pagination for large datasets
- Support offset/limit pagination for simplicity
- Include pagination metadata in response
- Use Link header for navigation
- Document pagination parameters
- Set reasonable default page sizes

**Filtering and Sorting:**

- Use query parameters for filtering
- Support multiple filter criteria
- Implement sorting with sort parameter
- Use consistent filter syntax
- Document available filters
- Validate filter parameters

**Rate Limiting:**

- Implement rate limits per API key/user
- Return rate limit info in headers
- Use 429 status code for rate limit exceeded
- Implement different limits for different endpoints
- Use sliding window or token bucket algorithm
- Document rate limits clearly

**Caching:**

- Use ETags for conditional requests
- Implement Cache-Control headers
- Support If-Modified-Since for resources
- Use stale-while-revalidate pattern
- Cache at multiple levels (CDN, server, client)
- Invalidate cache properly on updates

**Documentation:**

- Use OpenAPI/Swagger for REST APIs
- Provide interactive API documentation
- Include code examples in multiple languages
- Document authentication requirements
- Provide sandbox/test environment
- Keep documentation in sync with code

**Testing:**

- Write contract tests for API endpoints
- Test all status codes and error scenarios
- Implement integration tests
- Use API mocking for client testing
- Test rate limiting and security
- Validate response schemas

**Monitoring:**

- Log all API requests and responses
- Track error rates and latency
- Monitor rate limit usage
- Set up alerts for anomalies
- Use distributed tracing
- Track API usage metrics

**Best Practices:**

- Keep endpoints simple and focused
- Use consistent naming conventions
- Implement idempotency for mutations
- Return partial updates with PATCH
- Use bulk operations for efficiency
- Design for backward compatibility

**Summary:**

> For all API design work, always use the fetch tool to look up the latest best practices. Design APIs that are developer-friendly, secure, and performant.

API Design REST GraphQL Architecture Backend OpenAPI