High Level Design
API Design
What makes a good API — goals of scalability, extensibility, and ease of use, plus REST best practices and common design patterns.
An API (Application Programming Interface) is a software contract that defines the expectations and interactions between external users (clients) and a piece of code (service). It specifies:
- API name
- Accepted parameters
- Response structure
- Error messages and codes
Goals of Good API Design#
1. Scalability#
- Supports increased load (traffic, data, users) with minimal changes
- Follows standards that allow horizontal scaling (e.g., RESTful resource modeling)
2. Extensibility#
Easy to add new features or modify behavior without breaking existing consumers. Achieved by:
- Versioning (/v1, /v2)
- Optional parameters
- Backward-compatible responses
3. Ease of Use#
- Clear, intuitive naming and structure
- Helpful and consistent error messages
- Good documentation
REST API Principles#
REST (Representational State Transfer) is a set of architectural constraints for building web APIs:
- Stateless — each request contains all the information needed to process it
- Resource-based — endpoints represent resources (/users, /orders)
- Standard HTTP methods — GET, POST, PUT, PATCH, DELETE
- Consistent error codes — use standard HTTP status codes
HTTP Method Semantics#
| Method | Operation | Idempotent? |
|---|---|---|
| GET | Read resource | ✅ Yes |
| POST | Create resource | ❌ No |
| PUT | Replace resource | ✅ Yes |
| PATCH | Partial update | ✅ Yes |
| DELETE | Delete resource | ✅ Yes |
Common Status Codes#
| Code | Meaning |
|---|---|
| 200 | OK |
| 201 | Created |
| 400 | Bad Request |
| 401 | Unauthorized |
| 403 | Forbidden |
| 404 | Not Found |
| 429 | Too Many Requests (rate limit) |
| 500 | Internal Server Error |
API Versioning Strategies#
| Strategy | Example | Pros | Cons |
|---|---|---|---|
| URL path | /v1/users | Easy to understand | URL pollution |
| Query param | /users?version=1 | Non-breaking | Less clean |
| Header | Accept: application/vnd.api.v1+json | Clean URLs | Hidden from browser |
Error Response Design#
Consistent error responses help clients handle failures gracefully:
json
{
"error": {
"code": "RATE_LIMIT_EXCEEDED",
"message": "You have exceeded your request quota.",
"retry_after": 30
}
}
Pagination Patterns#
| Pattern | Description | Use Case |
|---|---|---|
| Offset-based | ?page=2&limit=20 | Simple; good for small datasets |
| Cursor-based | ?after=eyJpZCI6MTB9 | Consistent for large/changing datasets |
| Keyset | ?after_id=1000 | Efficient for database queries |