API Design
APIs define contracts between services and clients. Changes to published APIs can break dependent systems. This section covers API paradigms, design patterns, and implementation considerations.
API Paradigms
REST (Representational State Transfer)
REST is the most widely used paradigm for web APIs.
Common operations:
- GET /users - List users
- GET /users/123 - Get specific user
- POST /users - Create user
- PUT /users/123 - Update user
- DELETE /users/123 - Delete user
REST principles:
- Resource-based URLs
- HTTP methods for operations
- Stateless communication
- Standard HTTP status codes
GraphQL
GraphQL provides a single endpoint where clients specify the exact data they need.
Example query: A client can request a user by ID and specify exactly which fields to return (name, email) along with nested related data (post titles). The server returns only the requested fields, reducing over-fetching.
| Aspect | Description |
|---|---|
| Advantages | Client-specified data, single endpoint, strong typing |
| Disadvantages | Increased complexity, caching challenges, N+1 query problems |
gRPC
gRPC is Google's RPC framework using Protocol Buffers (binary format) for service-to-service communication.
Service definition: Services are defined in Protocol Buffer files specifying RPC methods (such as GetUser, CreateUser), their request types, and return types. Code generators create client and server stubs from these definitions.
| Aspect | Description |
|---|---|
| Advantages | High performance (binary protocol), strong typing, bi-directional streaming |
| Disadvantages | Limited browser support, less human-readable, steeper learning curve |
REST Design Guidelines
URL Structure
| Pattern | Example | Recommendation |
|---|---|---|
| Resource-based | GET /users/123/orders | Recommended |
| Query parameters | GET /orders?user_id=123&status=pending | Recommended |
| Verb-based | GET /getUserOrders?id=123 | Not recommended |
| Nested parameters | GET /orders/pending/user/123 | Not recommended |
HTTP Methods
| Method | Purpose | Idempotent |
|---|---|---|
| GET | Retrieve resource | Yes |
| POST | Create resource | No |
| PUT | Replace resource | Yes |
| PATCH | Partial update | Yes |
| DELETE | Delete resource | Yes |
Status Codes
| Category | Codes | Description |
|---|---|---|
| 2xx Success | 200 OK, 201 Created, 204 No Content | Request succeeded |
| 4xx Client Error | 400 Bad Request, 401 Unauthorized, 403 Forbidden, 404 Not Found, 429 Too Many Requests | Client-side issue |
| 5xx Server Error | 500 Internal Server Error, 503 Service Unavailable | Server-side issue |
Pagination
| Strategy | Example | Characteristics |
|---|---|---|
| Offset pagination | GET /users?page=2&limit=20 | Simple implementation, performance degrades with large offsets |
| Cursor pagination | GET /users?cursor=abc123&limit=20 | Consistent results, better performance, more complex |
Versioning
| Strategy | Example |
|---|---|
| URL versioning | GET /v1/users, GET /v2/users |
| Header versioning | Accept: application/vnd.api+json;version=1 |
Error Handling
Standard error response format should include an error code for programmatic handling, a human-readable message, and optional details array with field-level errors for validation failures.
Rate Limiting
Rate limiting protects APIs from excessive usage.
Response headers: When rate limited, return HTTP 429 status with headers indicating the limit (total allowed requests), remaining quota, and reset timestamp (when the limit resets).
| Strategy | Description |
|---|---|
| Fixed window | Requests counted within fixed time intervals |
| Sliding window | Rolling time window for request counting |
| Token bucket | Tokens replenish at fixed rate, requests consume tokens |
| Leaky bucket | Requests processed at fixed rate, excess queued or dropped |
Authentication and Authorization
API Keys
API keys provide simple authentication for server-to-server communication. API keys should not be used in browser-based applications due to exposure risk. Pass the API key in the Authorization header.
OAuth 2.0 / JWT
OAuth 2.0 with JWT tokens provides stateless authentication for user-facing applications. Pass the Bearer token in the Authorization header.
Scopes
Scopes limit access to specific operations, defining what resources or actions the token can access (such as read:users or write:orders).
Documentation
API documentation should include:
| Component | Description |
|---|---|
| Endpoint descriptions | Purpose and behavior of each endpoint |
| Request/response examples | Sample payloads for each operation |
| Error codes | All possible error responses |
| Authentication requirements | Required credentials and scopes |
| Rate limits | Request limits and quotas |
Documentation tools: OpenAPI/Swagger, Postman, GraphQL Playground
Design Considerations
| Consideration | Description |
|---|---|
| Requirements | Define required operations before designing |
| Client interface | Design for simplicity from the client perspective |
| Backward compatibility | Plan versioning strategy for future changes |
| Scale | Implement rate limiting and pagination |
| Security | Implement authentication, authorization, and input validation |