APIs & HTTP
Junior Questions
Junior
8
How should API errors be communicated?
- Use the correct HTTP status code — never return 200 with an error body.
- Return a structured error body consistently:
- RFC 7807 Problem Details is a standard format:
type,title,status,detail,instance. - Don't expose internal stack traces or system details in production errors.
- Log detailed errors server-side and return a correlation ID for debugging.
What problems does this solve?
- Consistent, structured error responses are what separate a well-designed API from a frustrating one.
Junior
9
What are API design best practices?
- Nouns, not verbs in URIs:
/users, not/getUsers. - Plural resource names:
/users,/orders. - Correct HTTP methods & status codes.
- Consistent error format (RFC 7807 Problem Details).
- Versioning from day one.
- Pagination, filtering, sorting on collection endpoints.
- Use HTTPS. Return
Content-Type: application/json. - Idempotency keys for non-idempotent operations.
- Document with OpenAPI.
- Don't expose internal details (DB IDs, stack traces, field names) in responses.
What problems does this solve?
- API design best practices separate professional APIs from ad-hoc ones — these are the conventions expected at any experienced level.
Junior
11
What are Webhooks?
- Webhooks are HTTP callbacks — instead of polling, the server sends an HTTP POST to a URL you provide when an event occurs.
- Use cases: Payment events (Stripe), CI/CD triggers (GitHub), form submissions.
- Verification: Always validate the webhook signature (HMAC) to confirm it came from the expected sender.
- Reliability: Acknowledge with 200 quickly; process asynchronously. Implement retry handling and deduplication (check event IDs for idempotency).
What problems does this solve?
- Webhooks are the dominant pattern for event-driven integrations — security and reliability best practices are frequently asked.
Junior
12
What are important HTTP request and response headers?
- Request:
Authorization,Content-Type,Accept,Accept-Encoding,User-Agent,Cookie,If-None-Match,If-Modified-Since. - Response:
Content-Type,Cache-Control,ETag,Last-Modified,Set-Cookie,Location(for redirects/created resources),Retry-After. Content-Type: application/json; charset=utf-8— required for JSON APIs.Accept: application/json— client signals accepted format (content negotiation).
What problems does this solve?
- Headers communicate metadata about the request/response — misusing them breaks caching, auth, and content negotiation.
Junior
13
What are the HTTP methods and their semantics?
- GET — Retrieve a resource. Safe, idempotent, cacheable. No body.
- POST — Create a resource or trigger an action. Not idempotent. May have body.
- PUT — Replace a resource entirely. Idempotent.
- PATCH — Partially update a resource. Not necessarily idempotent.
- DELETE — Remove a resource. Idempotent.
- HEAD — Same as GET but response has no body (useful for checking existence/headers).
- OPTIONS — Describes communication options. Used by CORS preflight.
- Safe: GET, HEAD, OPTIONS — don't modify state. Idempotent: GET, PUT, DELETE, HEAD, OPTIONS.
What problems does this solve?
- HTTP method semantics are the foundation of RESTful API design — misuse leads to confusing APIs and broken caching.
Junior
14
What are the REST principles?
- Client-Server: Separation of UI and data storage concerns.
- Stateless: Each request contains all information needed. No session state on server.
- Cacheable: Responses must label themselves as cacheable or not.
- Uniform Interface: Resource identification in requests (URIs), manipulation via representations, self-descriptive messages, HATEOAS.
- Layered System: Client doesn't know if it's talking to the origin server or a proxy.
- Code on Demand (optional): Server can send executable code (e.g., JavaScript).
- Most REST APIs are not truly RESTful — they omit HATEOAS and are more accurately called "HTTP APIs".
What problems does this solve?
- Understanding REST constraints vs common practice shows architectural depth and prevents cargo-culting REST vocabulary.
Junior
17
What are the key HTTP status code ranges?
- 1xx Informational: 100 Continue.
- 2xx Success: 200 OK, 201 Created, 204 No Content.
- 3xx Redirection: 301 Moved Permanently, 302 Found, 304 Not Modified.
- 4xx Client Error: 400 Bad Request, 401 Unauthorized, 403 Forbidden, 404 Not Found, 409 Conflict, 422 Unprocessable Entity, 429 Too Many Requests.
- 5xx Server Error: 500 Internal Server Error, 502 Bad Gateway, 503 Service Unavailable, 504 Gateway Timeout.
- Key distinctions: 401 = not authenticated (login required). 403 = authenticated but forbidden. 422 = validation error (semantically invalid body).
What problems does this solve?
- Using the correct status code communicates intent clearly — returning 200 with an error body is a common anti-pattern.
Junior
21
What happens when you type a URL and press Enter?
- 1. DNS resolution — domain → IP address (cache → resolver → root/TLD/auth nameserver).
- 2. TCP connection — 3-way handshake (SYN → SYN-ACK → ACK).
- 3. TLS handshake — certificate verification, shared key establishment.
- 4. HTTP request — browser sends GET with headers (User-Agent, Accept, cookies).
- 5. Server processes — routing, auth, DB queries, response assembled.
- 6. HTTP response — status code, headers, body.
- 7. Browser rendering — HTML parsed → DOM built → CSS applied → JS executed → paint.
What problems does this solve?
- One of the most common interview questions ever — a comprehensive answer demonstrates breadth across networking, browsers, and servers.
Junior
23
What is OpenAPI / Swagger?
- OpenAPI Specification (OAS) is a standard, language-agnostic format for describing REST APIs in JSON or YAML.
- Enables auto-generated documentation (Swagger UI, Redoc), client SDKs (openapi-generator), server stubs, and contract testing.
- Version 3.x is current. Swagger is the tooling ecosystem around OpenAPI.
- Design-first: Write the spec before code. Code-first: Generate spec from annotations in code.
What problems does this solve?
- OpenAPI is the industry standard for API documentation and contract definition — knowing it shows professional API development experience.
Mid-Level Questions
Mid
1
How do HTTP caching headers work?
Cache-Control:max-age=3600(cache for 1h),no-cache(validate before serving),no-store(never cache),private(browser only),public(CDN + browser).ETag: Hash of resource content. Client sendsIf-None-Match: {etag}; server returns 304 if unchanged.Last-Modified/If-Modified-Since: Timestamp-based validation.- Stale-While-Revalidate: Serve stale content while fetching a fresh copy in the background.
- Proper caching reduces server load and dramatically improves performance.
What problems does this solve?
- HTTP caching is one of the highest-leverage performance tools — misunderstanding it leads to stale data or excessive server requests.
Mid
2
How do WebSockets work and when should you use them?
- WebSockets provide a persistent, full-duplex connection between client and server over a single TCP connection.
- Handshake: HTTP upgrade request (
Upgrade: websocket). Server responds with 101 Switching Protocols. Connection stays open. - Use cases: Chat, live collaboration, multiplayer games, real-time dashboards, trading platforms.
- Trade-offs: More complex than HTTP (state management, reconnection logic). Harder to scale horizontally (sticky sessions or pub/sub broker needed).
- Libraries: Socket.io (auto-reconnect, rooms, fallback), ws (bare WebSocket for Node.js).
What problems does this solve?
- WebSockets are the standard for low-latency bidirectional communication — knowing when they're needed vs SSE or polling is key.
Mid
4
How does API rate limiting work?
- Controls API request frequency to prevent abuse, ensure fair use, and protect backend resources.
- Headers clients receive:
X-RateLimit-Limit,X-RateLimit-Remaining,X-RateLimit-Reset,Retry-After. - Algorithms: Token Bucket (allows bursting), Sliding Window (smooth), Fixed Window (simple).
- Granularity: Per API key, per user, per IP, per endpoint.
- Return
429 Too Many Requests.
What problems does this solve?
- Rate limiting is a foundational API protection — the response headers communicate policy to well-behaved clients.
Mid
5
How does CORS work in detail?
- CORS (Cross-Origin Resource Sharing) is an HTTP mechanism allowing controlled cross-origin browser requests via response headers.
- Simple requests (GET/POST with safe headers): Browser checks
Access-Control-Allow-Originheader in response. - Preflight (OPTIONS): Triggered for non-simple requests. Browser sends
OPTIONSwithAccess-Control-Request-MethodandAccess-Control-Request-Headers. Server must respond with appropriateAccess-Control-Allow-*headers before browser sends the real request. - CORS is browser-only enforcement — doesn't protect against server-to-server or curl requests.
What problems does this solve?
- CORS is one of the most debugged issues in web development — understanding preflight eliminates most confusion.
Mid
6
How does DNS resolution work?
- DNS translates domain names to IP addresses.
- Resolution steps: Browser cache → OS cache → Recursive resolver (ISP/8.8.8.8) → Root nameserver → TLD nameserver (.com) → Authoritative nameserver → IP returned → cached at each layer.
- TTL — Time to Live controls how long each layer caches the record.
- Record types: A (IPv4), AAAA (IPv6), CNAME (alias), MX (mail), TXT (verification), NS (nameserver).
- DNS lookup adds latency —
dns-prefetchandpreconnecthints help browsers resolve early.
What problems does this solve?
- DNS is the first step of every HTTP request — understanding resolution explains why new deployments can take time to propagate.
Mid
10
What are Server-Sent Events (SSE)?
- SSE provides one-way, server-to-client streaming over a standard HTTP connection.
- Uses
Content-Type: text/event-stream. Client usesEventSourceAPI. Auto-reconnects on disconnect. - Format:
data: {"'{...}'}. Supports event types and IDs for replay. - Use cases: Notification feeds, live scores, progress updates — where the server pushes but client doesn't send data.
- vs WebSockets: SSE is simpler, works over plain HTTP/2 (multiplexed), auto-reconnects, but unidirectional only.
What problems does this solve?
- SSE is underused but is often the right choice over WebSockets for server-push-only scenarios — simpler and HTTP/2-friendly.
Mid
16
What are the differences between REST and GraphQL?
- REST: Multiple endpoints, each returning a fixed shape. Simple to cache (HTTP caching). Easier to reason about. Can over-fetch or under-fetch data.
- GraphQL: Single endpoint. Client specifies exactly what data it needs. Eliminates over/under-fetching. Strong type system and introspection. Harder to cache (POST by default). N+1 problem requires DataLoader.
- When REST: Simple CRUD APIs, public APIs, when HTTP caching is critical.
- When GraphQL: Complex data requirements, multiple client types (mobile/web), rapid frontend iteration without backend changes.
What problems does this solve?
- REST vs GraphQL is one of the most common API design discussions — showing measured trade-off thinking is the right answer.
Mid
18
What are the main API authentication patterns?
- API Keys: Static secret in header/query param. Simple. No expiry by default. Good for server-to-server.
- Bearer Tokens (JWT): Short-lived tokens in
Authorization: Bearer {token}. Stateless, self-contained. Used in OAuth 2.0 flows. - Basic Auth:
Authorization: Basic base64(user:pass). Only over HTTPS. Sends credentials on every request. - OAuth 2.0: Delegated access without exposing credentials. Industry standard for third-party integrations.
- mTLS: Mutual TLS — both client and server present certificates. Used in microservices zero-trust architectures.
What problems does this solve?
- Choosing the right auth pattern for the use case (public API vs internal service vs user-delegated) is a key API design decision.
Mid
19
What are the main API versioning strategies?
- URI versioning:
/api/v1/users. Simple, explicit, highly visible. Most common. - Header versioning:
Accept: application/vnd.example.v2+json. Keeps URLs clean. Harder to test/share. - Query param:
?version=2. Simple but pollutes the URL. - No versioning: Backwards-compatible changes only (additive). Breaking changes require major versions.
- Version only when needed for breaking changes. Deprecate old versions with sunset headers and migration guides.
What problems does this solve?
- API versioning strategy affects developer experience and maintenance — URI versioning is the pragmatic default.
Mid
20
What are the main pagination strategies?
- Offset pagination:
?page=2&limit=20. Simple. Breaks when items are added/removed during pagination (results skip/repeat). - Cursor pagination:
?after=cursor_id. Stable — doesn't break on concurrent inserts. Used by most social APIs (Twitter, Facebook). Better for infinite scroll. - Keyset pagination: Filter on a column value (e.g.,
WHERE id > last_id). Performant with indexed columns. - Return
next_cursororLinkheader with next/prev URLs (RFC 5988).
What problems does this solve?
- Pagination is a universal API pattern — choosing cursor over offset avoids data consistency bugs.
Mid
22
What is Long Polling?
- Long polling is a workaround for real-time updates over HTTP: the client sends a request, the server holds it open until there's new data (or a timeout), then the client immediately sends another request.
- Simulates server push without WebSockets. Higher latency than WS. Works everywhere HTTP does.
- Largely superseded by SSE and WebSockets for new projects.
What problems does this solve?
- Long polling's role in evolution from polling → long polling → SSE/WebSockets is a useful historical context question.
Mid
25
What is content negotiation?
- Content negotiation allows client and server to agree on the format of the response.
- Client sends:
Accept: application/json, text/html;q=0.9(with quality factors). - Server sends: Response in the best matching format with
Content-Typeheader andVary: Acceptfor correct cache keying. - Also used for language (
Accept-Language), encoding (Accept-Encoding: gzip, br).
What problems does this solve?
- Content negotiation is foundational to building APIs that serve multiple client types from a single endpoint.
Mid
27
What is idempotency and why does it matter?
- An operation is idempotent if performing it multiple times has the same effect as performing it once.
- HTTP idempotent methods: GET, PUT, DELETE, HEAD, OPTIONS.
- POST is not idempotent — submitting a form twice creates two orders.
- Idempotency keys: For non-idempotent operations (payments), clients include a unique key; server deduplicates retries. Stripe and most payment APIs use this pattern.
- Critical for safe retries in distributed systems and unreliable networks.
What problems does this solve?
- Idempotency is a distributed systems concept that directly impacts API reliability — critical for payment and mutation APIs.
Mid
30
When should you use cookies vs token (Bearer) auth?
- Cookies (httpOnly): Browser sends automatically. CSRF protection required (
SameSite). Works for same-origin web apps. Supports session revocation easily. - Bearer tokens (Authorization header): Must be explicitly sent by JS. No CSRF risk (can't be sent by forms). Better for SPAs, mobile apps, cross-origin APIs. Revocation harder (JWT expiry).
- Hybrid: Store refresh token in
httpOnlycookie; access token in memory (not localStorage).
What problems does this solve?
- Cookie vs token is a common auth design question — the right answer depends on the deployment context.
Senior Questions
Senior
3
How do microservices communicate?
- Synchronous (request-response): REST/HTTP, gRPC. Simpler. Tightly coupled — caller waits for response. Risk of cascading failures.
- Asynchronous (message-based): Message queues (RabbitMQ, SQS), event streaming (Kafka). Decoupled. Eventually consistent. Better resilience. More complex.
- Service mesh (Istio, Linkerd): Infrastructure layer handling mTLS, retries, circuit breaking, tracing between services.
- Choose sync for real-time queries; async for commands and events.
What problems does this solve?
- Microservice communication patterns are a core system design topic — sync vs async trade-offs are asked in senior interviews.
Senior
7
How does the TLS/HTTPS handshake work?
- TLS encrypts HTTP traffic. The handshake authenticates the server and establishes a shared encryption key.
- TLS 1.3 (simplified): Client hello (supported algorithms + nonce) → Server hello + certificate → Key exchange (ECDHE) → Encrypted application data begins. 1-RTT (0-RTT for resumed sessions).
- The certificate is signed by a trusted CA, proving the server's identity.
- After the handshake, symmetric encryption (AES-GCM) is used for both parties.
What problems does this solve?
- Understanding TLS shows you can reason about data-in-transit security — asked at full-stack and backend interviews.
Senior
15
What are the differences between HTTP/1.1, HTTP/2, and HTTP/3?
- HTTP/1.1: One request per connection (head-of-line blocking). Workarounds: multiple connections, domain sharding, concatenating files.
- HTTP/2: Multiplexing — multiple requests over a single TCP connection. Header compression (HPACK). Server push. Binary framing. ~Most sites now use HTTP/2.
- HTTP/3: Uses QUIC (UDP-based) instead of TCP. Eliminates TCP head-of-line blocking. Faster connection establishment (0-RTT). Better performance on lossy networks.
- HTTP/2 made many old performance hacks (bundling, sprites) unnecessary or counterproductive.
What problems does this solve?
- Understanding HTTP evolution shows you can reason about network performance — important for senior web performance roles.
Senior
24
What is an API Gateway?
- An API Gateway is a server that acts as the single entry point for all client requests, routing them to the appropriate microservice.
- Responsibilities: Routing, authentication/authorisation, rate limiting, SSL termination, request/response transformation, logging, caching.
- Examples: AWS API Gateway, Kong, Nginx, Traefik, Envoy.
- Eliminates the need for each microservice to implement cross-cutting concerns individually.
What problems does this solve?
- API Gateways are ubiquitous in microservice architectures — knowing their role shows production systems awareness.
Senior
26
What is gRPC?
- gRPC is a high-performance RPC framework using Protocol Buffers (protobuf) for serialisation over HTTP/2.
- Advantages: Strongly typed contracts, binary serialisation (smaller/faster than JSON), code generation for multiple languages, bidirectional streaming.
- vs REST: Much faster, better for internal service-to-service communication. Less human-readable. Harder to test manually.
- Use cases: Microservice internal APIs, mobile gRPC (gRPC-Web for browsers).
What problems does this solve?
- gRPC is the standard for internal microservice APIs at scale — understanding it shows awareness beyond public REST APIs.
Senior
28
What is the Circuit Breaker pattern?
- A circuit breaker prevents cascading failures by stopping requests to a failing downstream service.
- States: Closed (requests flow normally) → Open (failures exceed threshold, requests fail immediately) → Half-Open (test requests allowed to check recovery).
- Prevents a slow service from exhausting thread pools / connection limits across the system.
- Libraries: Resilience4j (Java), opossum (Node.js).
What problems does this solve?
- The circuit breaker is one of the most important microservice resilience patterns — preventing cascading failures is a distributed systems fundamental.
Senior
29
What is the OWASP API Security Top 10?
- API1 – Broken Object Level Authorisation (IDOR) — Most common API vulnerability.
- API2 – Broken Authentication
- API3 – Broken Object Property Level Authorisation — Mass assignment, over/under exposure.
- API4 – Unrestricted Resource Consumption — No rate limits, no pagination limits.
- API5 – Broken Function Level Authorisation — Admin endpoints accessible to regular users.
- API6 – Unrestricted Access to Sensitive Business Flows
- API7 – SSRF
- API8 – Security Misconfiguration
- API9 – Improper Inventory Management — Old/undocumented versions exposed.
- API10 – Unsafe Consumption of APIs — Trusting third-party API responses without validation.
What problems does this solve?
- APIs are the primary attack surface of modern applications — the OWASP API Top 10 frames the key risks.