π― What is API Design?
API (Application Programming Interface) design is the process of creating interfaces that allow different software systems to communicate. Good API design makes your service easy to use, understand, and maintain.
Why Good API Design Matters
- Developer Experience: Easy to understand and use
- Maintainability: Easier to update and extend
- Scalability: Handles growth efficiently
- Consistency: Predictable behavior across endpoints
- Documentation: Self-explanatory structure
- Performance: Optimized data transfer
ποΈ REST Principles
Core REST Concepts
- Resources: Everything is a resource (users, posts, products)
- URIs: Each resource has a unique identifier
- HTTP Methods: Standard operations (GET, POST, PUT, DELETE)
- Stateless: Each request contains all necessary information
- Representations: Resources can be represented in different formats (JSON, XML)
π€ URL Structure & Naming
Best Practices
β Good Examples: GET /api/v1/users # Get all users GET /api/v1/users/123 # Get specific user POST /api/v1/users # Create new user PUT /api/v1/users/123 # Update user DELETE /api/v1/users/123 # Delete user GET /api/v1/users/123/posts # Get user's posts β Bad Examples: GET /api/v1/getUsers # Don't use verbs GET /api/v1/user # Use plural nouns POST /api/v1/users/create # HTTP method defines action GET /api/v1/Users # Use lowercase GET /api/v1/user_posts # Use hyphens, not underscores
Naming Conventions
- Use nouns, not verbs:
/usersnot/getUsers - Use plural nouns:
/usersnot/user - Use lowercase:
/usersnot/Users - Use hyphens for readability:
/user-profilesnot/user_profiles - Keep it simple: Max 2-3 levels deep
- Be consistent: Follow same pattern everywhere
π§ HTTP Methods
GET - Retrieve Data
Safe and idempotent. Should not modify data.
GET /api/v1/users GET /api/v1/users/123 GET /api/v1/users?page=1&limit=20&sort=name
POST - Create Resource
Not idempotent. Creates new resource.
POST /api/v1/users
Content-Type: application/json
{
"name": "John Doe",
"email": "john@example.com"
}PUT - Update/Replace Resource
Idempotent. Replaces entire resource.
PUT /api/v1/users/123
Content-Type: application/json
{
"name": "John Smith",
"email": "john.smith@example.com"
}PATCH - Partial Update
Idempotent. Updates specific fields.
PATCH /api/v1/users/123
Content-Type: application/json
{
"email": "newemail@example.com"
}DELETE - Remove Resource
Idempotent. Deletes resource.
DELETE /api/v1/users/123
π HTTP Status Codes
Success Codes (2xx)
- 200 OK: Request succeeded (GET, PUT, PATCH)
- 201 Created: Resource created (POST)
- 204 No Content: Success but no data to return (DELETE)
Client Error Codes (4xx)
- 400 Bad Request: Invalid request data
- 401 Unauthorized: Authentication required
- 403 Forbidden: Authenticated but not authorized
- 404 Not Found: Resource doesn't exist
- 409 Conflict: Resource conflict (duplicate)
- 422 Unprocessable Entity: Validation failed
- 429 Too Many Requests: Rate limit exceeded
Server Error Codes (5xx)
- 500 Internal Server Error: Generic server error
- 502 Bad Gateway: Invalid response from upstream
- 503 Service Unavailable: Server temporarily down
- 504 Gateway Timeout: Upstream timeout
π Request & Response Format
Standard Response Structure
// Success Response
{
"success": true,
"data": {
"id": 123,
"name": "John Doe",
"email": "john@example.com",
"createdAt": "2026-05-17T10:30:00Z"
},
"message": "User retrieved successfully"
}
// Error Response
{
"success": false,
"error": {
"code": "VALIDATION_ERROR",
"message": "Invalid email format",
"details": [
{
"field": "email",
"message": "Must be a valid email address"
}
]
}
}
// List Response with Pagination
{
"success": true,
"data": [
{ "id": 1, "name": "User 1" },
{ "id": 2, "name": "User 2" }
],
"pagination": {
"page": 1,
"limit": 20,
"total": 100,
"totalPages": 5
}
}π Filtering, Sorting & Pagination
Query Parameters
// Pagination GET /api/v1/users?page=1&limit=20 // Sorting GET /api/v1/users?sort=name # Ascending GET /api/v1/users?sort=-createdAt # Descending (- prefix) // Filtering GET /api/v1/users?status=active GET /api/v1/users?role=admin&status=active // Search GET /api/v1/users?search=john // Field Selection GET /api/v1/users?fields=id,name,email // Combined GET /api/v1/users?page=1&limit=20&sort=-createdAt&status=active
π Authentication & Authorization
Common Methods
1. API Keys
Simple but less secure. Good for server-to-server.
GET /api/v1/users X-API-Key: your-api-key-here
2. Bearer Token (JWT)
Most common. Stateless and scalable.
GET /api/v1/users Authorization: Bearer eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9...
3. OAuth 2.0
Industry standard for third-party access.
GET /api/v1/users Authorization: Bearer oauth-access-token
π API Versioning
Versioning Strategies
1. URL Versioning (Recommended)
GET /api/v1/users GET /api/v2/users
β Clear, visible, easy to route
2. Header Versioning
GET /api/users Accept: application/vnd.myapi.v1+json
β οΈ Less visible, harder to test
3. Query Parameter
GET /api/users?version=1
β Not recommended, mixes concerns
β‘ Rate Limiting
Implementation
// Response Headers
X-RateLimit-Limit: 1000 # Max requests per window
X-RateLimit-Remaining: 999 # Remaining requests
X-RateLimit-Reset: 1621234567 # Unix timestamp when limit resets
// When limit exceeded
HTTP/1.1 429 Too Many Requests
Retry-After: 3600
{
"error": {
"code": "RATE_LIMIT_EXCEEDED",
"message": "Too many requests. Try again in 1 hour."
}
}π API Documentation
Essential Elements
- Overview: What the API does
- Authentication: How to authenticate
- Endpoints: All available endpoints
- Request Examples: Sample requests with parameters
- Response Examples: Sample responses
- Error Codes: All possible errors
- Rate Limits: Usage limits
- Changelog: Version history
Documentation Tools
OpenAPI/Swagger
Industry standard, interactive docs
Postman
API testing and documentation
Redoc
Beautiful OpenAPI docs
API Blueprint
Markdown-based documentation
β API Design Checklist
- β Use RESTful principles
- β Consistent naming conventions
- β Proper HTTP methods and status codes
- β Versioning strategy implemented
- β Authentication and authorization
- β Rate limiting configured
- β Pagination for list endpoints
- β Filtering and sorting options
- β Consistent error responses
- β Comprehensive documentation
- β CORS configured properly
- β HTTPS enforced
- β Input validation
- β Logging and monitoring
π― Conclusion
Good API design is about creating interfaces that are intuitive, consistent, and easy to use. Follow REST principles, use proper HTTP methods and status codes, implement versioning, and provide comprehensive documentation. Remember that your API is a productβtreat it with the same care you'd give to any user-facing feature.
π οΈ Test Your APIs
Need to test your API endpoints? Use our free JSON Formatter and API testing tools to validate responses and debug issues.
Try JSON Formatter β