Module 3: API Design
3.1 What is an API?
Definition: An Application Programming Interface (API) is a contract that lets one piece of software request data or functionality from
another, without needing to know its internal implementation.
Request
Client App API Backend
Data
Why it matters: APIs decouple frontend from backend, enable microservices to talk to each other, and let third parties integrate with
your platform (e.g., payment gateways, maps).
3.2 REST API
Definition: Representational State Transfer — an architectural style using standard HTTP methods and stateless requests to operate on
"resources" identified by URLs.
Method Purpose
GET Retrieve a resource
POST Create a resource
PUT Replace a resource fully
PATCH Update a resource partially
DELETE Remove a resource
Principles: Statelessness, resource-based URLs ( /orders/123 not /getOrder?id=123 ), use of HTTP status codes, HATEOAS (optional, links to
related actions).
3.3 SOAP API
Definition: Simple Object Access Protocol — a strict, XML-based messaging protocol with a formal contract (WSDL), built-in error handling,
and support for enterprise features like WS-Security.
REST SOAP
Lightweight, JSON typical Verbose, XML only
Flexible, multiple formats Strict contract (WSDL)
Stateless by convention Can be stateful
Common in modern web/mobile Common in legacy banking/enterprise systems
3.4 GraphQL
Definition: A query language for APIs where the client specifies exactly what data it needs in a single request, avoiding over-fetching or
under-fetching common in REST.
Users DB
GraphQL
Client Query Server
Orders DB
Real-world example: A mobile app screen needing user name + last 3 orders can get both in one GraphQL query, instead of two
separate REST calls.
Trade-off: GraphQL's flexibility adds server-side complexity (resolvers, N+1 query risk) and complicates HTTP-level caching compared to REST.
3.5 gRPC
Definition: A high-performance RPC framework by Google using HTTP/2 and Protocol Buffers (binary serialization) for fast, strongly-typed
service-to-service communication.
Best for: Internal microservice-to-microservice calls where performance matters more than human readability; supports streaming (client,
server, and bidirectional).
Azure implementation: AKS-hosted microservices commonly use gRPC for internal calls, with Dapr providing gRPC-based service
invocation out of the box.
3.6 API Versioning
Strategy Example
URI versioning /v1/orders , /v2/orders
Header versioning Accept: application/[Link].v2+json
Query param versioning /orders?version=2
Why it matters: Lets you evolve an API (breaking changes) without disrupting existing consumers who remain on an older version until
they migrate.
3.7 API Gateway
Definition: A single entry point that sits in front of multiple backend services, handling routing, authentication, rate limiting, caching, and
request/response transformation.
Orders Svc
Client API Gateway Users Svc
Payments Svc
Azure implementation: Azure API Management (APIM) provides gateway functionality — policies, throttling, developer portal, and
analytics — in front of microservices or Azure Functions.
3.8 Authentication
Definition: The process of verifying who a user or system is (e.g., via credentials, tokens, certificates), answering "are you who you claim
to be?"
3.9 Authorization
Definition: The process of determining what an authenticated identity is allowed to do, answering "are you allowed to do this?"
Authentication happens first (identity check), authorization happens second (permission check) — they are frequently confused but serve distinct
purposes.
3.10 JWT (JSON Web Token)
Definition: A compact, self-contained, digitally-signed token format for securely transmitting identity/claims between parties. Structure:
[Link] .
The server verifies the signature (using a secret or public key) without needing to query a database, making JWTs ideal for stateless
authentication across distributed services.
Interview Q&A
Q: Can a JWT be revoked before it expires?
A: Not natively — JWTs are stateless. Revocation requires extra mechanisms like a token blocklist, short expiry with refresh tokens, or switching to
server-side sessions for sensitive scenarios.
3.11 OAuth2
Definition: An authorization framework that lets a user grant a third-party application limited access to their resources without sharing
their password, using access tokens.
2. Get token
Auth Server
User 1. Login/consent Client App
Resource Server
3. Use token
Grant types: Authorization Code (web apps), Client Credentials (service-to-service), Refresh Token (renew access without re-login).
Implicit and Password grants are now deprecated for security reasons.
3.12 OpenID Connect (OIDC)
Definition: An identity layer built on top of OAuth2 that adds authentication (an ID Token, itself a JWT) on top of OAuth2's authorization
capabilities.
OAuth2 answers "what can this app access?"; OIDC additionally answers "who is this user?" — that's why login flows ("Sign in with
Google/Microsoft") use OIDC, not plain OAuth2.
Azure implementation: Azure Entra ID (formerly Azure AD) implements both OAuth2 and OIDC, issuing access tokens and ID tokens for
enterprise SSO.
3.13 API Rate Limiting
Definition: Restricting the number of requests a client can make in a given time window, protecting backend services from overload or
abuse.
Algorithm How it works
Fixed window Count resets every fixed interval (e.g., 100 req/min)
Sliding window Smooths bursts at window boundaries
Token bucket Tokens refill at a steady rate; each request consumes one
Leaky bucket Requests processed at a constant fixed rate
Azure implementation: Azure API Management has built-in rate-limit and quota policies configurable per subscription key or per client
IP.
3.14 API Pagination
Definition: Splitting large result sets into smaller pages to reduce payload size and improve performance.
Offset-based: ?page=2&limit=20 — simple but can skip/duplicate rows if data changes between calls.
Cursor-based: ?after=eyJpZCI6MTIzfQ — more stable for frequently-changing datasets, used by most modern social/feed APIs.
3.15 Idempotency
Definition: An operation is idempotent if performing it multiple times produces the same result as performing it once — critical for safely
retrying failed requests (e.g., due to network timeouts).
Method Idempotent?
GET, PUT, DELETE Yes
POST No (by default)
Real-world example: Payment APIs (e.g., Stripe) require an Idempotency-Key header on POST requests so a retried "charge card" call
doesn't double-charge the customer.
3.16 API Caching
Definition: Storing responses to avoid recomputing/refetching them for repeated identical requests, reducing latency and backend load.
Mechanisms: HTTP caching headers ( Cache-Control , ETag ), CDN edge caching for public GET responses, gateway-level response caching
(e.g., APIM cache policy).
3.17 Request Validation
Definition: Verifying that incoming request data (types, required fields, formats, ranges) is correct before processing, rejecting malformed
input early with clear error messages.
Prevents downstream errors, protects against injection attacks, and improves API consumer experience via precise 400-level error
responses instead of confusing 500 errors.
3.18 Error Handling
Definition: Consistent, predictable structuring of error responses so API consumers can programmatically detect and handle failures.
Status Code Meaning
400 Bad Request — invalid input
401 Unauthorized — missing/invalid auth
403 Forbidden — authenticated but not permitted
404 Not Found
409 Conflict — e.g., duplicate resource
429 Too Many Requests — rate limited
500 Internal Server Error
503 Service Unavailable
3.19 OpenAPI (Swagger)
Definition: A standardized, machine-readable specification format (YAML/JSON) describing an API's endpoints, request/response schemas,
and authentication — enabling auto-generated docs, client SDKs, and server stubs.
paths:
/orders/{id}:
get:
summary: Get order by ID
responses:
'200':
description: Success
Azure implementation: Azure API Management can import an OpenAPI spec directly to auto-generate the gateway configuration and
interactive developer portal documentation.
3.20 Postman
Definition: A widely-used tool for designing, testing, documenting, and automating API calls — supporting collections, environment
variables, scripted tests, and mock servers.
Real-world use: Teams build a Postman collection per API, run automated test suites in CI/CD pipelines (via Newman CLI), and share
environments (dev/staging/prod) with variable-based base URLs and tokens.
Module 3 Common Mistakes
Making POST requests non-idempotent when retries are expected; using GET for actions that mutate data; skipping request validation and relying
only on database constraints; exposing internal error stack traces to API consumers; not versioning APIs before the first breaking change is needed.
Module 3 Practice Interview Questions
1. Design a REST API for a hotel booking system — list key endpoints and HTTP methods.
2. Why is idempotency critical for payment APIs, and how would you implement it?
3. Compare REST, GraphQL, and gRPC — when would you choose each?
4. Explain the OAuth2 Authorization Code flow end-to-end.
5. How would you design rate limiting for a public API with free and paid tiers?