API Design Principles
Good API design is crucial for system maintainability and developer experience.
API Design Principles
1. Consistency
- Use consistent naming conventions
- Follow similar patterns across endpoints
2. Simplicity
- Easy to understand and use
- Minimize required knowledge
3. Completeness
- Cover all necessary operations
- Handle edge cases
4. Evolution
- Version your APIs
- Backward compatibility
5. Documentation
- Clear, comprehensive docs
- Examples and tutorials
REST API Naming Conventions
Good:
GET /users (list users)
GET /users/123 (get user 123)
POST /users (create user)
PUT /users/123 (update user 123)
DELETE /users/123 (delete user 123)
Bad:
GET /getUsers
POST /createUser
GET /user/delete/123
API Design Patterns
| Pattern | Description | Example |
|---|---|---|
| Collection | List of resources | GET /users |
| Resource | Single resource | GET /users/123 |
| Nested | Related resources | GET /users/123/orders |
| Action | Custom operations | POST /users/123/activate |
API Versioning
Versioning Strategies:
1. URL Path
/v1/users
/v2/users
2. Header
Accept: application/vnd.api.v2+json
3. Query Parameter
/users?version=2
Recommended: URL path (visible, cacheable)
REST APIs
REST (Representational State Transfer) is the most common API architecture.
REST Constraints
1. Client-Server
- Separation of concerns
- Independent evolution
2. Stateless
- No client context on server
- Each request contains all info
3. Cacheable
- Responses must indicate cacheability
- Improves performance
4. Uniform Interface
- Resource identification (URIs)
- Resource manipulation through representations
- Self-descriptive messages
- HATEOAS (hypermedia)
5. Layered System
- Client can't tell if connected to end server
- Enables load balancing, caching
6. Code on Demand (optional)
- Server can send executable code
HTTP Methods in REST
| Method | Purpose | Idempotent | Safe |
|---|---|---|---|
| GET | Read resource | Yes | Yes |
| POST | Create resource | No | No |
| PUT | Replace resource | Yes | No |
| PATCH | Partial update | No | No |
| DELETE | Delete resource | Yes | No |
REST Example
# Create user
POST /api/v1/users
Content-Type: application/json
{
"name": "John Doe",
"email": "john@example.com"
}
Response: 201 Created
{
"id": "123",
"name": "John Doe",
"email": "john@example.com",
"createdAt": "2024-01-15T10:30:00Z"
}
# Get user
GET /api/v1/users/123
Response: 200 OK
{
"id": "123",
"name": "John Doe",
"email": "john@example.com"
}
REST Best Practices
- Use nouns for resources, not verbs
- Use HTTP methods for operations
- Return appropriate status codes
- Support pagination for lists
- Use filtering and sorting
- Implement rate limiting
- Version your APIs
GraphQL Overview
GraphQL is a query language for APIs that provides flexible data fetching.
GraphQL vs REST
REST: Multiple endpoints, fixed data structure
GET /users/123 → Full user object
GET /users/123/orders → User's orders
GET /users/123/posts → User's posts
GraphQL: Single endpoint, client specifies data
POST /graphql
{
user(id: 123) {
name
email
orders {
id
total
}
}
}
→ Only requested fields
GraphQL Schema
type User {
id: ID!
name: String!
email: String!
posts: [Post!]
orders: [Order!]
}
type Post {
id: ID!
title: String!
content: String!
author: User!
}
type Query {
user(id: ID!): User
users: [User!]
}
type Mutation {
createUser(name: String!, email: String!): User!
updateUser(id: ID!, name: String): User!
}
GraphQL Advantages
| Advantage | Description |
|---|---|
| No over-fetching | Client requests only needed fields |
| No under-fetching | Single request for related data |
| Strong typing | Schema defines types |
| Introspection | Client can query schema |
| Versioning | Schema evolution, no versioning |
GraphQL Challenges
1. Complexity
- Learning curve
- Schema design
2. Caching
- HTTP caching doesn't work well
- Need application-level caching
3. N+1 Problem
- Query optimization required
- DataLoader pattern
4. Security
- Query complexity limits
- Depth limiting
Practice Problems
Design a scalable API system. Cover high-level architecture, data model, and API design.
Solution
// Complete system design:
// - Functional + Non-functional requirements
// - Capacity estimation
// - Data model (SQL/NoSQL choice)
// - API endpoints
// - Component architecture
// - Scaling strategy
// - Monitoring & reliabilityHow would you scale API to handle 10x the current load? Identify bottlenecks and solutions.
Solution
// Scaling approach:
// 1. Load balancing
// 2. Database sharding/replication
// 3. Cache layer (Redis)
// 4. CDN for static assets
// 5. Async processing (queues)
// 6. Microservices decompositionAnalyze potential failure modes for API and design mitigation strategies.
Solution
// Failure mitigation:
// 1. Redundancy (multi-AZ)
// 2. Circuit breakers
// 3. Retry with backoff
// 4. Dead letter queues
// 5. Health checks
// 6. Graceful degradationQuiz
1. What does REST stand for?
2. Which HTTP method should be used to create a new resource?
3. What is the main advantage of GraphQL over REST?
4. What does it mean for an HTTP method to be idempotent?
Flashcards
Question
What are the 6 constraints of REST?
Click to reveal answer
Answer
1) Client-Server, 2) Stateless, 3) Cacheable, 4) Uniform Interface, 5) Layered System, 6) Code on Demand (optional).
Question
What are the HTTP methods in REST?
Click to reveal answer
Answer
GET (read), POST (create), PUT (replace), PATCH (partial update), DELETE (delete). GET, PUT, DELETE are idempotent.
Question
What is GraphQL?
Click to reveal answer
Answer
A query language for APIs where clients specify exactly what data they need. Single endpoint, strong typing, avoids over/under-fetching.
Question
What is API versioning?
Click to reveal answer
Answer
Strategy for managing API changes while maintaining backward compatibility. Common: URL path (/v1/users), Header, Query parameter.
Question
What is API?
Click to reveal answer
Answer
API is a key concept in system design.
Revision Notes
Key Takeaways
- 1.REST is the most common API architecture with clear constraints
- 2.Use proper HTTP methods and status codes
- 3.GraphQL provides flexibility but adds complexity
- 4.API versioning is essential for evolution
- 5.Good API design improves developer experience
Interview Tips
- •Default to REST unless you have specific reasons for GraphQL
- •Discuss API versioning strategy
- •Use proper HTTP methods (GET for read, POST for create, etc.)
- •Consider rate limiting and authentication in your API design
Cheat Sheet
API - Cheat Sheet
Design Principles:
- Consistency
- Simplicity
- Completeness
- Evolution
- Documentation
REST Constraints:
- Client-Server
- Stateless
- Cacheable
- Uniform Interface
- Layered System
HTTP Methods:
| Method | Purpose | Idempotent |
|---|---|---|
| GET | Read | Yes |
| POST | Create | No |
| PUT | Replace | Yes |
| PATCH | Update | No |
| DELETE | Delete | Yes |
GraphQL vs REST:
- GraphQL: Single endpoint, flexible queries
- REST: Multiple endpoints, fixed structure