Skip to main content

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.

AspectDescription
AdvantagesClient-specified data, single endpoint, strong typing
DisadvantagesIncreased 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.

AspectDescription
AdvantagesHigh performance (binary protocol), strong typing, bi-directional streaming
DisadvantagesLimited browser support, less human-readable, steeper learning curve

REST Design Guidelines

URL Structure

PatternExampleRecommendation
Resource-basedGET /users/123/ordersRecommended
Query parametersGET /orders?user_id=123&status=pendingRecommended
Verb-basedGET /getUserOrders?id=123Not recommended
Nested parametersGET /orders/pending/user/123Not recommended

HTTP Methods

MethodPurposeIdempotent
GETRetrieve resourceYes
POSTCreate resourceNo
PUTReplace resourceYes
PATCHPartial updateYes
DELETEDelete resourceYes

Status Codes

CategoryCodesDescription
2xx Success200 OK, 201 Created, 204 No ContentRequest succeeded
4xx Client Error400 Bad Request, 401 Unauthorized, 403 Forbidden, 404 Not Found, 429 Too Many RequestsClient-side issue
5xx Server Error500 Internal Server Error, 503 Service UnavailableServer-side issue

Pagination

StrategyExampleCharacteristics
Offset paginationGET /users?page=2&limit=20Simple implementation, performance degrades with large offsets
Cursor paginationGET /users?cursor=abc123&limit=20Consistent results, better performance, more complex

Versioning

StrategyExample
URL versioningGET /v1/users, GET /v2/users
Header versioningAccept: 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).

StrategyDescription
Fixed windowRequests counted within fixed time intervals
Sliding windowRolling time window for request counting
Token bucketTokens replenish at fixed rate, requests consume tokens
Leaky bucketRequests 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:

ComponentDescription
Endpoint descriptionsPurpose and behavior of each endpoint
Request/response examplesSample payloads for each operation
Error codesAll possible error responses
Authentication requirementsRequired credentials and scopes
Rate limitsRequest limits and quotas

Documentation tools: OpenAPI/Swagger, Postman, GraphQL Playground

Design Considerations

ConsiderationDescription
RequirementsDefine required operations before designing
Client interfaceDesign for simplicity from the client perspective
Backward compatibilityPlan versioning strategy for future changes
ScaleImplement rate limiting and pagination
SecurityImplement authentication, authorization, and input validation