API Design Flashcards
REST Principles
-
Stateless
Each request must contain all the information needed to process it. The server does not store session state between requests.
Why?: Improves scalability since the server does not need to track client state.
Example:
β RESTful: Each request has an Authorization token in headers.
2.** Client-Server Architecture **
The client (UI) and server(data) must be independent;
Why?: Increases flexibility; clients and servers can evolve independently.
-
Uniform Interface π―
A consistent way to interact with resources using standard methods (GET, POST, PUT, DELETE).
Why?: Simplifies API usage and improves interoperability.
Example:
β /users/123 β GET (Fetch user), PUT (Update user), DELETE (Remove user).
β /fetchUser?id=123 (Non-uniform, not RESTful).
4.** Cacheability**
Definition: Responses must define whether they are cacheable to reduce unnecessary requests.
Why?: Boosts performance, reduces server load.
-
Layered System
The client doesnβt need to know if itβs communicating with the final server or intermediary (load balancer or proxy).
Why?: Enhances security, scalability, and flexibility.
Example:
A gateway (like API Gateway) handles authentication before forwarding the request to the actual API server. -
Code on Demand (Optional)
Definition: The server can send executable code (like JavaScript or scripts) to the client to execute.
Why?: Can extend functionality dynamically
Example:
A REST API delivering a JavaScript snippet for A/B testing.
What is REST, REST API, RESTful API
REST (Representational State Transfer) is an architectural style for designing networked applications. It relies on stateless communication over HTTP and follows a resource-based approach.
REST : Implementation, may not fully conform, statelessness depends on implementation
RESTful : Strict implementation, stricly stateless
What Does Stateless Mean?
A stateless REST API means each request from the client must contain all necessary information for the server to process it.
The server does not store session state between requests.
Each request is independent, and no previous request affects the current one.
Authentication, user details, and request context (pagination details, filters, and preferences)must be sent every time.
Why is Statelessness Important?
Benefits of Stateless APIs
β
Scalability β Easy to scale horizontally (add more servers) since no session data is stored on a specific server.
β
Reliability β No risk of session data loss if a server crashes.
β
Performance β No need for expensive session lookups in memory or DB.
β
Cacheable β Stateless APIs work well with caching (ETag, Cache-Control).
β
Simplifies Failover & Load Balancing β Any request can go to any server.
[ApiController]
Automatic 400 bad request if model state, input is invalid.
Automatic detection of FromBody FromQuery
Less code for validation and binding
Auto documentation hints
Why Some APIs Might Not Be Stateless?
Complex workflows β Some applications need multi-step interactions (e.g., shopping carts).
Performance Optimization β Maintaining state in-memory reduces DB calls.
User Sessions β Some applications store user sessions for authentication.
Web Applications Needing Session State β e.g., a dashboard tracking user sessions.
Long-Lived Workflows β Workflows requiring persistent state (e.g., video uploads).
πΉ Tradeoff? β Use tokens (JWT) . If state must be stored, use Redis or DB, not in-memory storage. Else If the server restarts, data is lost.
πΉ Solution? β Use Redis, DB, or stateful APIs selectively while keeping other services stateless.
What are stateless authentication
JWT Token : elf-contained, containing user info in the token payload
OAuth
API Keys
Do not use session or cookies because server will then have to track and store
What Does Client-Server Architecture Mean?
Client-Server is a separation of concerns between the client (frontend, mobile app) and server (backend, API).
The client sends requests to the server and only handles UI/UX and interactions.
The server processes business logic, authentication, and data storage.
What happens if Violate Client Server Architecture?
β Tightly Coupled Systems β If frontend logic is hardcoded into the backend, changes require full redeployment.
β Business Logic on the Client β Leads to security risks, as logic can be manipulated by users.
πΉ Tradeoff? β Keep UI and business logic separate, use APIs for communication.
Why is Client-Server Separation Important?
β
Scalability β Servers can be upgraded independently of clients.
β
Flexibility β Clients (web, mobile, desktop) can evolve separately from backend APIs.
β
Security β Sensitive logic (authentication, database) is kept on the server.
β
Reusability β Same API can be used by multiple frontends (React, iOS, Android).
β
Performance Optimization β Clients handle UI rendering, reducing backend load.
What is Layered Architecture?
Layered Architecture in REST enforces a hierarchical structure where components are organized in layers, each performing a specific role.
Layers are independent and interact only with adjacent layers.
Clients do not need to know how the backend is structured.
Security, caching, and load balancing can be added without affecting the client.
How to Implement Client-Server Separation Correctly?
The Client Should Only Handle UI/UX
The client should not contain business logic (e.g., pricing calculations).
The backend should perform validations, authentication, and processing.
The Server Should Not Manage UI Logic
API should return raw data, not UI-specific formats (like error messages).
UI elements (e.g., dropdown options) should be handled by the frontend.
Use API Gateways for Cross-Platform Support
A single API should support multiple clients (mobile, web, IoT).
API Gateway can handle versioning, rate limiting, authentication.
Donβt Overloadin the Server with UI-Specific Endpoints. Return all necessary data in one request.
Donβt Hardcode API Calls in Frontend
Secure the Client-Server Communication
Why is Layered Architecture Important?
β
Scalability β Each layer can be scaled independently.
β
Security β Sensitive data processing happens in deeper layers, not exposed to clients.
β
Flexibility β API Gateway can be modified without affecting backend logic.
β
Maintainability β Changes in one layer do not require modifications in others.
β
Extensibility β Easy to introduce caching, logging, security layers.
How to Implement Layered Architecture Correctly?
Use an API Gateway for Routing, Security, and Load Balancing. API Gateway acts as a single entry point for all requests.
β
Good Approach: Manages authentication, rate limiting, logging, and security. Reduces direct exposure of backend services.
β Bad Example (Clients Accessing Microservices Directly)
GET /inventory/orders/12345 // Direct access
β
Good Example (Using API Gateway)
GET /orders/12345 // Routed through API Gateway
Separate Business Logic from API Controllers
Controller Layer: Handles API requests.
Service Layer: Contains business logic. Caching logic
Repository Layer: Communicates with the database.
Asynchronous processing to improve response times.
What is Cacheability in REST APIs?
Cacheability ensures that responses from a REST API can be stored and reused instead of being regenerated for each request. This improves performance, reduces server load, and minimizes latency.
Data freshness and consistency must be maintained to avoid stale data issues.
β
Lower Bandwidth Usage β Cached responses prevent unnecessary network traffic.
β
Scalability β Helps scale services to handle more users with fewer resources.
When Not to Use Caching?
β Highly Dynamic Data β Frequent changes (e.g., stock prices, real-time updates).
β Personalized Responses β User-specific data (e.g., user dashboards).
β Security-Sensitive Data β API responses containing sensitive info (e.g., authentication tokens).
πΉ Tradeoff? β Balancing freshness and performance is critical.
How to Implement Cacheability in REST APIs?
Example of a Cacheable API Response
HTTP/1.1 200 OK
Cache-Control: public, max-age=3600
ETag: βa1b2c3d4β
What are ETags
ETags (Entity Tags) help determine if a cached response is still valid.
If content is unchanged, return 304 (Not Modified) instead of 200 (OK).
Reduces bandwidth usage and speeds up requests.
First Request: Server Generates ETag
GET /products/123
HTTP/1.1 200 OK
ETag: βxyz123β
Cache-Control: public, max-age=3600
Subsequent Request with ETag Check
GET /products/123
If-None-Match: βxyz123β
Server Response (If Data Unchanged)
HTTP/1.1 304 Not Modified
Server Response (If Data Changed)
HTTP/1.1 200 OK
ETag: βabc456β // New ETag, updated content
304 response avoids sending duplicate data, saving bandwidth.
Cache Layers
Client-Side Cache Browser or mobile app stores API responses. HTTP caching, IndexedDB, Service Workers.
Proxy Cache Caches responses between client and server. Cloudflare, Akamai, Varnish.
Application Cache Stores API results within the API itself. Redis, MemoryCache (C#).
Database Query Cache Caches expensive DB queries. PostgreSQL Query Cache, MySQL Query Cache.
Caching Strategy?
Categorize API responses: static, semi-static, dynamic.
Apply caching only where it benefits performance.
Use public for shared data, private for user-specific data.
Implement no-cache for frequently changing data.
Use Layered Caching. Client Cache β CDN Cache β API Cache β Database Cache.
What is Uniform Interface in REST APIs?
The Uniform Interface is a fundamental principle of REST APIs that ensures all clients interact with the API in a consistent and predictable way. This improves scalability, interoperability, and ease of use.
πΉ Key Characteristics of a Uniform Interface
β Resource-Based URLs β Everything is treated as a resource (/users, /orders).
β Standard HTTP Methods β Use GET, POST, PUT, DELETE, PATCH correctly.
β Consistent Request & Response Formats β JSON/XML with clear structure.
β Stateless Interactions β Each request is independent.
β HATEOAS (Hypermedia as the Engine of Application State) β Responses include links for navigation.
Why is Uniform Interface Important?
β
Predictability β Clients know what to expect from the API.
β
Interoperability β Different clients (web, mobile, IoT) can use the API without special logic.
β
Decoupling β The client and server evolve independently.
β
Scalability β Standardized APIs can handle more clients efficiently.
Correct way to Uniform Interface
Verbs should be represented by HTTP methods, not in the URL.
Use Consistent Request and Response Formats
Standardized JSON format improves readability and API integration.
Include status codes, messages, and HATEOAS links (optional).
Use HATEOAS for API Discoverability
HATEOAS
HATEOAS (Hypermedia as the Engine of Application State) includes navigational links in responses.
β
β
Example: HATEOAS in User Response
β
{
βidβ: 123,
βnameβ: βJohn Doeβ,
βemailβ: βjohn@example.comβ,
βlinksβ: {
βselfβ: β/users/123β,
βordersβ: β/users/123/ordersβ,
βupdateβ: β/users/123/updateβ
}
}