Skip to content
intermediatePhase 44 · Web Architecture

API

Design APIs with proper endpoints, versioning, and documentation.

45m
0 problems
Topic Progress0%

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

  1. Use nouns for resources, not verbs
  2. Use HTTP methods for operations
  3. Return appropriate status codes
  4. Support pagination for lists
  5. Use filtering and sorting
  6. Implement rate limiting
  7. 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

0/3solved
Design API System

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 & reliability
API Scaling

How 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 decomposition
API Failure Modes

Analyze 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 degradation

Quiz

1. What does REST stand for?

Question 1 options

2. Which HTTP method should be used to create a new resource?

Question 2 options

3. What is the main advantage of GraphQL over REST?

Question 3 options

4. What does it mean for an HTTP method to be idempotent?

Question 4 options

Flashcards

Question

What are the 6 constraints of REST?

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?

Answer

GET (read), POST (create), PUT (replace), PATCH (partial update), DELETE (delete). GET, PUT, DELETE are idempotent.

Question

What is GraphQL?

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?

Answer

Strategy for managing API changes while maintaining backward compatibility. Common: URL path (/v1/users), Header, Query parameter.

Question

What is API?

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:

  1. Consistency
  2. Simplicity
  3. Completeness
  4. Evolution
  5. Documentation

REST Constraints:

  1. Client-Server
  2. Stateless
  3. Cacheable
  4. Uniform Interface
  5. 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