🎉 75% of content is free forever — Unlock Premium from $10/mo →
CW
💼 Servicesℹ️ About✉️ ContactView Pricing Plansfrom $10

API Design

FoundationsInterface Design🟢 Free Lesson

Advertisement

System Design Foundations

API Design

APIs are the contracts between system components. Good API design reduces coupling, enables evolution, and makes systems easier to use and maintain. This guide covers REST, GraphQL, gRPC, and the essential patterns for production APIs.

  • REST — Resource-oriented, stateless, cacheable HTTP interfaces
  • GraphQL — Client-driven queries with a typed schema
  • gRPC — High-performance, contract-first RPC with Protocol Buffers

Design APIs for the consumer, not the implementer.

What Is an API?

An API (Application Programming Interface) defines the boundary between software components—how they communicate, what operations are available, and what data formats are used.

API Paradigms

REST (Representational State Transfer)

REST is an architectural style for designing networked applications, defined by Roy Fielding in his 2000 doctoral dissertation.

REST API Design Principles

Architecture Diagram
GET    /api/v1/users          # List users
GET    /api/v1/users/123      # Get user 123
POST   /api/v1/users          # Create user
PUT    /api/v1/users/123      # Replace user 123
PATCH  /api/v1/users/123      # Update user 123
DELETE /api/v1/users/123      # Delete user 123
GET    /api/v1/users/123/posts # List posts by user 123

REST Response Format

{
  "data": {
    "id": "123",
    "name": "Alice",
    "email": "alice@example.com",
    "created_at": "2025-01-15T10:30:00Z"
  },
  "meta": {
    "request_id": "req_abc123",
    "timestamp": "2025-01-15T10:30:01Z"
  }
}

REST Pagination

{
  "data": [...],
  "pagination": {
    "total": 1250,
    "page": 3,
    "per_page": 20,
    "total_pages": 63,
    "next": "/api/v1/users?page=4&per_page=20",
    "prev": "/api/v1/users?page=2&per_page=20"
  }
}

GraphQL

GraphQL is a query language and runtime for APIs, developed by Facebook.

GraphQL vs REST

AspectRESTGraphQL
EndpointsMultiple endpointsSingle endpoint
Data fetchingFixed structure per endpointClient specifies exact fields
Over-fetchingCommonEliminated
Under-fetchingCommon (N+1 problem)Eliminated
Type systemOptional (OpenAPI)Built-in
CachingHTTP caching nativeRequires custom caching
File uploadNativeRequires specification extension

GraphQL Schema Example

type User {
  id: ID!
  name: String!
  email: String!
  posts: [Post!]!
}

type Post {
  id: ID!
  title: String!
  body: String!
  author: User!
}

type Query {
  user(id: ID!): User
  users(limit: Int, offset: Int): [User!]!
}

type Mutation {
  createUser(name: String!, email: String!): User!
  updateUser(id: ID!, name: String): User!
  deleteUser(id: ID!): Boolean!
}

gRPC (Google Remote Procedure Call)

gRPC is a high-performance RPC framework using Protocol Buffers and HTTP/2.

gRPC Communication Patterns

PatternDescriptionUse Case
UnarySingle request, single responseStandard CRUD
Server streamingSingle request, stream of responsesReal-time updates
Client streamingStream of requests, single responseFile upload, aggregation
BidirectionalStream of requests, stream of responsesChat, real-time sync

Protocol Buffer Example

syntax = "proto3";

service UserService {
  rpc GetUser (GetUserRequest) returns (User);
  rpc ListUsers (ListUsersRequest) returns (stream User);
  rpc CreateUser (CreateUserRequest) returns (User);
}

message User {
  string id = 1;
  string name = 2;
  string email = 3;
}

message GetUserRequest {
  string id = 1;
}

Protocol Comparison

FeatureRESTGraphQLgRPC
ProtocolHTTP/1.1HTTPHTTP/2
FormatJSONJSONProtobuf (binary)
SchemaOpenAPI (optional)RequiredRequired
StreamingNot nativeSubscriptionsNative
PerformanceModerateGoodExcellent
Browser supportNativeNativeRequires gRPC-Web
Learning curveLowMediumMedium

API Versioning

APIs evolve over time. Versioning strategies manage breaking changes.

Versioning Strategies

StrategyExampleProsCons
URL path/api/v1/usersExplicit, cacheableURL proliferation
Query parameter/api/users?version=1Easy to addLess clean URLs
HeaderAccept: application/vnd.api.v1+jsonClean URLsHidden from URL bar
Content negotiationAccept: application/vnd.api.v1+jsonRESTfulComplex to implement

Rate Limiting

Rate limiting protects APIs from abuse and ensures fair resource usage.

Rate Limiting Algorithms

AlgorithmHow It WorksTrade-off
Fixed WindowCount requests in fixed time windowsSimple but allows burst at window boundary
Sliding Window LogTimestamp-based, checks recent requestsMemory intensive, most accurate
Sliding Window CounterWeighted average of current and previous windowGood balance of accuracy and efficiency
Token BucketTokens refill at fixed rate, each request consumes oneAllows controlled bursts
Leaky BucketRequests queue, processed at fixed rateSmooths traffic but adds latency

Rate Limit Response Headers

HTTP/1.1 429 Too Many Requests
X-RateLimit-Limit: 100
X-RateLimit-Remaining: 0
X-RateLimit-Reset: 1640995200
Retry-After: 30

API Security

Authentication and Authorization

MechanismDescriptionUse Case
API KeysSimple token in headerInternal services, simple auth
OAuth 2.0Delegated authorizationThird-party access
JWTSelf-contained tokensStateless authentication
mTLSCertificate-basedService-to-service

OAuth 2.0 Flows

ClientAuth ServerResource Svc1. Auth Code2. Token3. Bearer TokenAuthorization Code Flow with PKCE

Practice Exercises

  1. Design: Design a RESTful API for a URL shortener. Include endpoints for creating, retrieving, and deleting short URLs, plus analytics. Consider rate limiting and versioning.

  2. Compare: You're building a social media feed API. Compare REST, GraphQL, and gRPC for this use case. Which would you choose and why?

  3. Implementation: Design a rate limiting strategy for an API that serves 10,000 requests/second. Which algorithm would you use? How would you handle distributed rate limiting across multiple servers?

  4. Security: Design an authentication strategy for a system with three user types: anonymous readers, authenticated users, and admin users. How do you handle token refresh and revocation?


What to Learn Next

-> Databases SQL vs NoSQL, indexing, replication, and sharding.

-> Caching Strategies Redis, Memcached, cache invalidation, and write strategies.

-> Load Balancing Algorithms, health checks, and L4 vs L7.

-> Message Queues Kafka, RabbitMQ, event-driven architecture.

-> Microservices Service decomposition, discovery, and API gateways.

-> Networking Fundamentals TCP/IP, HTTP, DNS, and network latency.

Need Expert System Design Help?

Get personalized tutoring, project support, or professional consulting.

Advertisement