API Documentation
Interview Preparation Notes
Covers: What is an API · REST Methods · Endpoints · Request/Response · Authentication · Error
Handling · Pagination & Rate Limits · Writing Docs · Postman · cURL
API Documentation — Interview Prep Notes · Page 1
FOUNDATION
What is an API
Core Definition
An API (Application Programming Interface) is a contract between two software systems defining how
they communicate. It exposes a set of rules and endpoints through which one application can request
services or data from another — without knowing the internal implementation.
Real-World Analogy
Think of an API like a restaurant menu. The menu (API) tells you what you can order (endpoints). You
don't go into the kitchen (backend). You place an order (request) and receive food (response). The waiter
is the API layer.
Types of APIs
• Open/Public APIs — Available to external developers (Twitter API, Google Maps)
• Private/Internal APIs — Connect internal services within an org
• Partner APIs — Shared between specific business partners
• Composite APIs — Combine multiple API calls into one
API vs SDK vs Library
API = the interface/protocol for communication between systems.
SDK = a package of tools, libraries, and samples to build on top of an API.
Library = reusable code for local operations; an API calls a remote service.
An SDK often wraps an API to simplify usage.
Why APIs Matter
• Enable modularity and separation of concerns
• Allow third-party integrations and ecosystems
• Enable microservices architecture
• Provide abstraction — internal changes don't break consumers
• Power mobile apps, SPAs, IoT, and automation workflows
API Documentation — Interview Prep Notes · Page 2
CORE CONCEPT
REST Basics — HTTP Methods
What is REST?
REST (Representational State Transfer) is an architectural style for APIs, introduced by Roy Fielding in
2000. It uses HTTP as the transport and treats everything as a resource. Each request must be self-
contained — the server holds no client session state.
The 6 REST Constraints
• 1. Client-Server — separation of UI and data storage concerns
• 2. Stateless — no client context stored on server between requests
• 3. Cacheable — responses must define themselves as cacheable or not
• 4. Uniform Interface — consistent interaction pattern across resources
• 5. Layered System — client doesn't know if talking to end server or proxy
• 6. Code on Demand (optional) — server can send executable code
HTTP Methods (CRUD Mapping)
GET → Read. Safe and idempotent. Never changes server state.
POST → Create. Not idempotent. Calling twice may create duplicates.
PUT → Full Replace. Idempotent. Replaces the entire resource.
PATCH → Partial Update. Modifies specific fields.
DELETE → Remove. Idempotent.
HEAD → Like GET but returns headers only (check if resource exists).
OPTIONS → Describes allowed communication options for a resource.
Idempotency — Critical Concept
An operation is idempotent if multiple identical requests produce the same result as one.
• Idempotent: GET, PUT, DELETE, HEAD, OPTIONS
• NOT idempotent: POST (two calls may create two records)
Matters for: retry logic, caching, and safe failure recovery.
REST vs Other Styles
REST vs SOAP: REST is lightweight, uses JSON/XML, stateless. SOAP uses XML only, has strict
standards — better for enterprise security.
REST vs GraphQL: REST has one endpoint per resource. GraphQL has one endpoint; client specifies
exactly what it needs.
REST vs gRPC: gRPC uses Protocol Buffers (binary), faster, ideal for microservice-to-microservice
communication.
API Documentation — Interview Prep Notes · Page 3
ARCHITECTURE
Endpoint Structure
Anatomy of an Endpoint URL
[Link]
• https:// → Protocol (always HTTPS in production)
• [Link] → Base URL / Host
• /v1/ → API Version
• /users/42/ → Resource path with path parameter
• /orders → Sub-resource
• ?status=active → Query parameter
RESTful Resource Naming Rules
• Use nouns, not verbs: /users not /getUsers
• Use plural nouns: /orders not /order
• Use lowercase with hyphens: /product-categories
• Nest resources to show hierarchy: /users/{id}/posts
• Don't nest more than 2-3 levels deep
• Express actions as sub-resources: POST /orders/{id}/cancel
Path Parameters vs Query Parameters
Path Params (/users/{id}): Identify a specific resource. Required. Part of URL structure.
Query Params (?sort=desc&page=2): Filter, sort, paginate. Optional. Don't change resource identity.
Rule: If removing the param changes WHICH resource → path param. If it changes HOW → query
param.
API Versioning Strategies
• URI Versioning: /v1/users (most common, visible)
• Header Versioning: Accept: application/[Link]+json;version=1
• Query Parameter: /users?version=1
• Subdomain: [Link]
Why version? To maintain backward compatibility when making breaking changes.
API Documentation — Interview Prep Notes · Page 4
MECHANICS
Request Components
HTTP Request Structure
Every HTTP request has:
• 1. Request Line: METHOD /path HTTP/1.1
• 2. Headers: Key-value metadata (auth, content type)
• 3. Blank Line: Separates headers from body
• 4. Body (optional): Data payload for POST/PUT/PATCH
Key Request Headers
• Content-Type: application/json — format of request body
• Accept: application/json — format client wants in response
• Authorization: Bearer <token> — authentication credentials
• X-API-Key: <key> — API key auth
• Cache-Control: no-cache — caching directives
• X-Request-ID — for tracing and debugging
Request Body Formats
JSON (most common): {"name": "Alice", "email": "alice@[Link]"}
XML (legacy/SOAP): <user><name>Alice</name></user>
multipart/form-data: For file uploads alongside metadata
Binary: For streaming or protobuf payloads
Always match Content-Type header to actual body format.
CORS — Cross-Origin Resource Sharing
Browser security policy: scripts from origin A can't freely call API at origin B without permission.
Server must return: Access-Control-Allow-Origin: [Link]
Preflight: Browser sends OPTIONS first for PUT/DELETE or custom headers.
Credentials: Cookies/auth headers only sent cross-origin if both sides explicitly allow it.
API Documentation — Interview Prep Notes · Page 5
OUTPUT
Response Structure
HTTP Status Codes — Full Map
2xx — Success:
• 200 OK — general success
• 201 Created — resource created (POST)
• 202 Accepted — async operation started
• 204 No Content — success, no body (DELETE)
3xx — Redirection:
• 301 Moved Permanently
• 304 Not Modified (cached)
4xx — Client Errors:
• 400 Bad Request — malformed syntax
• 401 Unauthorized — auth required or invalid
• 403 Forbidden — authenticated but no permission
• 404 Not Found
• 409 Conflict — duplicate resource
• 422 Unprocessable Entity — validation failure
• 429 Too Many Requests — rate limited
5xx — Server Errors:
• 500 Internal Server Error
• 502 Bad Gateway
• 503 Service Unavailable
• 504 Gateway Timeout
401 vs 403 — Critical Distinction
401 Unauthorized: "Who are you?" The client is not authenticated. Token is missing or invalid. Client
should re-authenticate.
403 Forbidden: "I know who you are, but you cannot do this." Authenticated but lacks permission.
Interviewers frequently test this distinction.
JSON Response Design
Success pattern:
{"data": {...}, "meta": {"page": 1, "total": 100}, "error": null}
Error pattern:
{"error": {"code": "VALIDATION_ERROR", "message": "Email is required", "field":
"email", "request_id": "req_abc123"}}
API Documentation — Interview Prep Notes · Page 6
Always use camelCase or snake_case consistently. Include request IDs for tracing.
Key Response Headers
• Content-Type: application/json
• Cache-Control: max-age=3600
• ETag: version identifier for conditional requests
• X-RateLimit-Limit, X-RateLimit-Remaining
• Location: /users/42 (after 201 Created)
• Retry-After: seconds to wait (after 429 or 503)
API Documentation — Interview Prep Notes · Page 7
SECURITY
Authentication & Authorization
AuthN vs AuthZ
Authentication (AuthN): Verifying WHO you are. "Are you really Alice?"
Authorization (AuthZ): Verifying WHAT you can do. "Can Alice delete this order?"
Always authenticate before authorizing.
API Key Authentication
Simple static token issued to a client.
Sent via: Header (X-API-Key) or query param (avoid — shows in logs).
Pros: Simple to implement, easy to revoke.
Cons: No expiry by default, no user-level granularity.
Best for: Server-to-server, public data APIs.
JWT — JSON Web Tokens
Structure: [Link] (Base64URL, dot-separated)
Header: algorithm (HS256 or RS256)
Payload (claims): sub, iat, exp, roles, custom claims
Signature: HMAC or RSA to verify integrity
Key facts:
• Stateless — server doesn't store sessions
• Self-contained — all info inside token
• Never store sensitive data in payload (it's encoded, not encrypted)
• Access tokens: short-lived (15min–1hr)
• Refresh tokens: long-lived, used to get new access tokens
OAuth 2.0
A delegation framework — lets users grant third-party apps access without sharing passwords.
Roles: Resource Owner (user), Client (app), Authorization Server, Resource Server
Flows:
• Authorization Code: Web apps, most secure, uses redirect URI
• PKCE: Mobile/SPA without client secret
• Client Credentials: Machine-to-machine, no user involved
• Device Flow: Smart TVs, CLI tools
OAuth Scopes
Scopes limit what a token can do:
• read:profile — can read profile
• write:posts — can create posts
API Documentation — Interview Prep Notes · Page 8
Principle of least privilege: request only the scopes you need.
Bearer Tokens
Sent as: Authorization: Bearer eyJhbGci...
"Bearer" = whoever holds this token gets access.
Tokens must be sent over HTTPS only. Short-lived with refresh mechanism. Revocable.
API Documentation — Interview Prep Notes · Page 9
RELIABILITY
Error Handling
4xx vs 5xx — Responsibility
4xx = Client's fault. The request was wrong.
5xx = Server's fault. The server failed on a valid request.
Knowing this determines where to fix the problem and who to notify.
Error Response Design
A good error should be:
• Consistent in structure across all endpoints
• Machine-readable (use error codes)
• Human-readable (clear message)
• Actionable (tell client what to fix)
Always include a request_id for tracing in logs.
Retry Logic & Exponential Backoff
Transient errors (503, 504) should be retried by clients.
Exponential backoff: wait 1s → 2s → 4s → 8s + jitter (random delay) to avoid thundering herd.
Idempotency Keys: Client sends Idempotency-Key: uuid with POST. Server stores result. Retries return
same result. Critical for payment APIs.
Never Expose Internal Errors
Never return stack traces, DB errors, or internal paths in production. Log internally, return a safe generic
message. Prevents information leakage attackers can exploit.
API Documentation — Interview Prep Notes · Page 10
SCALABILITY
Pagination & Rate Limits
Pagination Strategies
• 1. Offset-based: ?page=2&limit=20
Pros: Easy, random access. Cons: Inconsistent if data changes mid-scroll.
• 2. Cursor-based (recommended for live data): ?cursor=eyJpZCI6NDJ9&limit=20
Cursor = opaque pointer to last seen item. Stable, no skips/duplicates. No random access.
• 3. Keyset: ?after_id=42&limit=20 — uses actual field values
Pagination Response Pattern
{"data": [...], "pagination": {"page": 2, "per_page": 20, "total": 340,
"next_cursor": "abc", "next": "/users?cursor=abc"}}
Rate Limiting Strategies
• Fixed Window: 100 req/min. Simple but allows burst at boundary.
• Sliding Window: Tracks last 60 seconds. Smoother.
• Token Bucket: Tokens refill at rate. Allows controlled bursting.
• Leaky Bucket: Requests process at fixed rate. Smooths traffic.
Rate Limit Headers
• X-RateLimit-Limit: 1000
• X-RateLimit-Remaining: 743
• X-RateLimit-Reset: Unix timestamp when limit resets
• Retry-After: 30 (seconds to wait after 429)
Return 429 Too Many Requests when exceeded.
API Documentation — Interview Prep Notes · Page 11
CRAFT
Writing API Documentation
What Good API Docs Include
• Getting Started guide (quick win for new users)
• Authentication setup
• Base URL and versioning
• Full endpoint reference (description, method, URL, params, body, responses, errors, examples)
• Code samples in multiple languages
• Error code reference
• Changelog
• Rate limits and quotas
OpenAPI / Swagger Specification
Industry standard for describing REST APIs in YAML or JSON.
Key sections: openapi version, info (title, description), servers, paths, components (schemas, security)
Tools: Swagger UI (interactive), Redoc (clean read-only), Stoplight, Scalar
Documentation-First vs Code-First
Documentation-First: Write OpenAPI spec before building. Teams align on contract early. Easy to mock.
Code-First: Auto-generate docs from annotations (FastAPI, Spring Boot). Faster but docs may lag.
Best: Treat OpenAPI spec as source of truth and validate code against it.
Writing Great Endpoint Descriptions
Cover: What it does, who should use it, required permissions/scopes, side effects (does it send an
email?), idempotency, related endpoints.
Avoid vague descriptions. Say: "Creates a new user. Sends verification email. Returns 409 if email
exists."
API Documentation — Interview Prep Notes · Page 12
TOOLING
Postman Basics
What Postman Is
API platform for building, testing, documenting, and mocking APIs.
Core uses: Manual endpoint testing, automated test suites (Collections), mock servers, environment
management, team collaboration.
Collections & Environments
Collection: Group of related requests. Run as sequence via Collection Runner or Newman CLI.
Environment: Set of variables ({{base_url}}, {{token}}). Switch between dev/staging/prod without editing
requests.
Writing Tests in Postman
[Link]("Status 200", function() { [Link](200); });
[Link]("Has data field", function()
{ [Link]([Link]()).[Link]("data"); });
[Link]("Response time < 500ms", function()
{ [Link]([Link]).[Link](500); });
Mock Servers
Create a mock server from a collection. Returns example responses without hitting a real server.
Useful for: Frontend dev before backend is ready, testing error scenarios, demonstrations.
API Documentation — Interview Prep Notes · Page 13
TOOLING
cURL Usage
What is cURL?
cURL is a command-line tool for making HTTP requests. Universal — works on every OS. No
dependencies. Shows raw requests. Essential for debugging and API examples.
Common Commands
GET: curl [Link]
GET with auth: curl -H "Authorization: Bearer token" [Link]
POST: curl -X POST [Link] -H "Content-Type:
application/json" -d '{"name":"Alice"}'
DELETE: curl -X DELETE [Link]
Key Flags
• -X → HTTP method
• -H → add header
• -d → request body
• -i → include response headers
• -v → verbose (full request + response)
• -s → silent (hide progress)
• -o [Link] → save to file
• -k → skip SSL (dev only!)
• --max-time 10 → timeout
Verbose Mode for Debugging
curl -v [Link]
Shows: request line, headers sent, response status, response headers, body.
Essential for debugging — see exactly what goes out and comes back.
API Documentation — Interview Prep Notes · Page 14
EXPLORE
Further Learning & Research Areas
The topics below should be researched online to deepen expertise and stand out in interviews.
OpenAPI & Specs
• OpenAPI 3.1 vs 3.0 — what changed
• JSON Schema integration with OpenAPI
• AsyncAPI — for event-driven APIs
• API design tools: Stoplight Studio, Apicurio
Advanced Auth
• OAuth 2.0 PKCE flow in depth
• OpenID Connect (OIDC) — OAuth for identity
• JWT best practices — RS256 vs HS256, key rotation
• Token revocation strategies (Redis blocklists)
• Passkeys and FIDO2 — future of auth
API Security
• OWASP API Security Top 10 (2023)
• SQL/NoSQL injection via API parameters
• Mass assignment vulnerabilities
• Security headers: HSTS, CSP, X-Frame-Options
Advanced Patterns
• GraphQL — schema design, resolvers, subscriptions
• gRPC — Protocol Buffers, streaming, load balancing
• WebSockets vs Server-Sent Events (SSE)
• Event-driven APIs — Webhooks vs Polling
• HATEOAS — Hypermedia As Engine Of Application State
API Testing
• Contract testing with Pact
• API load testing with k6 or Locust
• Newman — Postman collections in CI/CD
• Chaos engineering for APIs
Documentation Tools
• Redoc, Scalar, Stoplight — rendering OpenAPI specs
• Mintlify, GitBook, [Link] — doc platforms
• Auto-generating SDKs from OpenAPI (OpenAPI Generator)
API Documentation — Interview Prep Notes · Page 15
• API changelog management tools
API Documentation — Interview Prep Notes · Page 16