0% found this document useful (0 votes)
3 views18 pages

REST API Interview Guide

The document is a comprehensive guide on REST APIs, covering fundamental concepts, principles, HTTP protocols, request/response structures, authentication, security, and best practices. It outlines key topics such as error handling, data formats, caching, versioning, pagination, and filtering, providing essential information for interview preparation. The guide emphasizes the importance of statelessness, resource-based architecture, and proper endpoint design in RESTful API development.

Uploaded by

bharathnick0
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
3 views18 pages

REST API Interview Guide

The document is a comprehensive guide on REST APIs, covering fundamental concepts, principles, HTTP protocols, request/response structures, authentication, security, and best practices. It outlines key topics such as error handling, data formats, caching, versioning, pagination, and filtering, providing essential information for interview preparation. The guide emphasizes the importance of statelessness, resource-based architecture, and proper endpoint design in RESTful API development.

Uploaded by

bharathnick0
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd

REST API

Complete Interview Guide


Fundamentals • HTTP • Auth • Security • Design • Advanced

Deep • Crisp • Interview-Ready

TABLE OF CONTENTS

# Topic

01 What is REST API

02 REST Principles (All 6)

03 HTTP Protocol

04 Request & Response Structure

05 Headers, Body, Params

06 URI / Endpoint Design

07 Authentication & Authorization

08 Security — HTTPS & CORS

09 HTTP Status Codes

10 Idempotency

11 Error Handling

12 Data Formats (JSON & XML)

13 Caching

14 Versioning

15 Pagination & Filtering

16 Rate Limiting

17 HATEOAS

18 REST vs SOAP

19 Quick Reference Tables


REST API Interview Guide Page 2

01 — What is REST API

REST API stands for Representational State Transfer – Application Programming Interface.
It is an architectural style (not a protocol) for designing networked applications where two systems communicate
over HTTP using standard web methods, resources are identified by URLs, and requests are stateless.

Core HTTP Methods


Method Purpose Idempotent
GET Read a resource Yes

POST Create a new resource No

PUT Replace entire resource Yes

PATCH Partial update No

DELETE Remove resource Yes

GET /users/10

Response:
{ "id": 10, "name": "Bharath", "email": "bharath@[Link]" }

One-liner: A REST API is a stateless, resource-oriented interface that uses standard HTTP methods to enable communication betwe

02 — REST Principles (All 6 Constraints)

1. Client–Server Separation
Client (UI) and server (logic/DB) are completely independent. They communicate only via HTTP. Changes on one
side do not break the other.
Why it matters: Allows independent development, deployment, and scaling.

2. Statelessness
Every request must contain all info needed to process it. The server stores NO session data between requests.
Auth tokens sent on every request.
Why it matters: Enables horizontal scaling — any server can handle any request.

3. Uniform Interface
Consistent, standardized interaction via URIs, HTTP methods, self-descriptive messages, and (optionally)
HATEOAS.
Why it matters: Decouples client and server; makes APIs predictable.

4. Resource-Based Architecture
Everything is a resource identified by a URI. Actions are expressed via HTTP verbs, NOT verbs in the URL.
Why it matters: Clean API design that leverages full HTTP semantics.

Deep • Crisp • Interview-Ready


REST API Interview Guide Page 3

5. Cacheability
Responses must clearly declare if they can be cached using Cache-Control, ETag, Last-Modified headers.
Why it matters: Reduces server load, improves latency, improves scalability.

6. Layered System
Client doesn't know if it's hitting the real server or an intermediary (gateway, load balancer, cache). Each layer only
knows adjacent layers.
Why it matters: Improves security, scalability, and flexibility.

Deep • Crisp • Interview-Ready


REST API Interview Guide Page 4

03 — HTTP Protocol

HTTP (HyperText Transfer Protocol) is an application-layer, stateless, request-response protocol over which
REST APIs operate.

Key Characteristics
• Stateless — server retains no info between requests
• Request–Response model — client sends request, server returns response
• Text-based and platform-independent
• Supports caching, compression, and content negotiation

HTTP vs HTTPS
Aspect HTTP HTTPS
Encryption None TLS/SSL

Port 80 443

Security Insecure Secure

Use in REST ■ Avoid ■ Always

One-liner: HTTP is a stateless application-layer protocol that defines how clients and servers exchange requests and responses. RE

04 — Request & Response Structure

HTTP Request Structure

POST /users HTTP/1.1


Host: [Link]
Authorization: Bearer <token>
Content-Type: application/json
Accept: application/json

{ "name": "Bharath", "email": "bharath@[Link]" }

Part Description Required


Request Line METHOD + URI + HTTP Version Yes

Headers Metadata (auth, content-type, cache) Yes

Body Data payload (POST, PUT, PATCH) No (GET has none)

HTTP Response Structure

Deep • Crisp • Interview-Ready


REST API Interview Guide Page 5

HTTP/1.1 201 Created


Content-Type: application/json
ETag: "v2"

{ "id": 10, "name": "Bharath" }

Part Description
Status Line HTTP Version + Status Code + Message

Headers Server metadata (content-type, cache, security)

Body Response data (JSON/XML)

Deep • Crisp • Interview-Ready


REST API Interview Guide Page 6

05 — Headers, Body & Params

Headers

Headers carry metadata about the request or response — not the main business data.

Header Purpose
Authorization Pass token or credentials

Content-Type Format of the body (application/json)

Accept Expected response format

Cache-Control Caching behaviour

ETag Version identifier for cache validation

Body

The body contains the actual data payload. Used in POST, PUT, PATCH. Not typically used with GET.

POST /login
Content-Type: application/json

{ "username": "bharath", "password": "secret" }

Params (Path & Query)

Type Example When to Use


Path Param GET /users/10 Identify a specific resource (mandatory)

Query Param GET /users?role=admin&page=2 Filter, sort, paginate (optional)

One-liner: Headers define request behaviour, body carries data, path params identify resources, and query params filter/sort/pagina

06 — URI / Endpoint Design

Core Design Rules


Use Nouns, Not Verbs

■ /getUser ■ /createOrder ■ /users ■ /orders

Use Plural Resource Names

■ /user/10 ■ /users/10

Path Params for Identity

Deep • Crisp • Interview-Ready


REST API Interview Guide Page 7

GET /users/10 DELETE /orders/55

Query Params for Filtering

GET /products?category=mobile&sort=price&page=2

Represent Relationships

GET /users/10/orders (orders belong to user 10)

Avoid Deep Nesting (>2 levels)

■ /users/10/orders/5/items/3

Avoid File Extensions

■ /[Link] → Use Accept: application/json

Version the API

/api/v1/users or via Accept header

Good vs Bad (Quick Reference)


■ Bad Design ■ Good Design
/getAllUsers GET /users

/deleteUser?id=5 DELETE /users/5

/updateOrder PUT /orders/10

/users?delete=true DELETE /users/10

Well-Designed REST Endpoint Set


GET /users → list all users
POST /users → create user
GET /users/{id} → get one user
PATCH /users/{id} → partial update
DELETE /users/{id} → delete user
GET /users/{id}/orders → user's orders

Deep • Crisp • Interview-Ready


REST API Interview Guide Page 8

07 — Authentication & Authorization

Concept Question it Answers Happens When


Authentication Who are you? First — verify identity

Authorization What are you allowed to do? After authentication

Authentication Methods

API Key
Authorization: Api-Key abc123

Simple; low-risk or internal APIs. No user identity context.

Basic Auth
Authorization: Basic base64(user:pass)

Sends credentials each request. Must use HTTPS. Rarely used today.

Bearer Token
Authorization: Bearer <token>

Most common. Stateless, scalable, secure with HTTPS.

JWT
{ "sub": "10", "role": "admin", "exp": 1712345678 }

Self-contained token. No server session needed. Perfect for REST.

Authorization Models

Model Description Use Case


RBAC (Role-Based) Roles define permissions (admin, user, editor) Most systems

Permission-Based Fine-grained: [Link], [Link] APIs with complex permissions

ABAC (Attribute-Based) Access based on user + resource attributes Enterprise systems

Best Practices
✔ Always use HTTPS
✔ Tokens in Authorization header, never in URL
✔ Use short-lived access tokens + refresh tokens
✔ Validate token on every request
✔ Never log sensitive tokens

08 — Security: HTTPS & CORS

Deep • Crisp • Interview-Ready


REST API Interview Guide Page 9

HTTPS

HTTPS = HTTP + TLS/SSL. Provides three guarantees: Encryption (data unreadable to attackers), Integrity
(data cannot be altered in transit), Authentication (confirms server identity via certificate).
A REST API without HTTPS is insecure by design — tokens and passwords can be stolen via Man-in-the-Middle
attacks.

CORS (Cross-Origin Resource Sharing)

CORS is a browser security mechanism that controls which frontends are allowed to call your API. An origin =
protocol + domain + port.
The browser blocks requests from a different origin by default. The server must send CORS headers to allow them.

Server response headers:


Access-Control-Allow-Origin: [Link]
Access-Control-Allow-Methods: GET, POST
Access-Control-Allow-Headers: Authorization

Preflight request (browser asks first):


OPTIONS /users → server responds with CORS headers

Aspect HTTPS CORS


Purpose Secure data transmission Control browser access

Protects Data in transit Frontend → API calls

Enforced by Network + server Browser only

Applies to All clients Browsers only

Common CORS Mistakes


• Access-Control-Allow-Origin: * combined with credentials
• Allowing all origins in production
• Confusing CORS with authentication

Deep • Crisp • Interview-Ready


REST API Interview Guide Page 10

09 — HTTP Status Codes

Status codes are 3-digit numbers that tell the client exactly what happened on the server.

2xx — Success
Code Meaning When to Use
200 OK Generic success for GET/PUT/PATCH

201 Created Resource successfully created (POST)

204 No Content Success with no response body (DELETE)

3xx — Redirection
Code Meaning When to Use
301 Moved Permanently Resource URL has changed permanently

304 Not Modified Cached response still valid (ETag match)

4xx — Client Errors


Code Meaning When to Use
400 Bad Request Validation error / malformed request

401 Unauthorized Missing or invalid authentication token

403 Forbidden Authenticated but not authorized

404 Not Found Resource does not exist

405 Method Not Allowed HTTP method not supported on this endpoint

409 Conflict Duplicate resource / state conflict

422 Unprocessable Entity Valid format but business rule violation

429 Too Many Requests Rate limit exceeded

5xx — Server Errors


Code Meaning When to Use
500 Internal Server Error Unexpected server failure

502 Bad Gateway Upstream service failure

503 Service Unavailable Server temporarily down / overloaded

Interview insight: 401 = not authenticated. 403 = authenticated but not permitted. This distinction is commonly tested.

10 — Idempotency

An operation is idempotent if calling it multiple times produces the same result as calling it once.
This is critical for safe retry logic — if a network request fails, should you retry it?

Method Idempotent Safe (Read-only) Why


GET Yes Yes Reads only, no side effects

Deep • Crisp • Interview-Ready


REST API Interview Guide Page 11

Method Idempotent Safe (Read-only) Why


HEAD Yes Yes Same as GET but no body

PUT Yes No Replacing with same data = same result

DELETE Yes No Deleting already-deleted resource = 404, no change

POST No No Creates a new resource each call

PATCH No No Incremental; repeated calls may change state differently

Why Idempotency Matters


• Network retries — safe to retry GET, PUT, DELETE without duplicating data
• Distributed systems — partial failures need safe retries
• Payment APIs — idempotency keys prevent duplicate charges on POST

Idempotency Keys (Advanced)


For POST requests (like payment), pass a unique key to prevent duplicates:

POST /payments
Idempotency-Key: 550e8400-e29b-41d4-a716-446655440000

{ "amount": 500, "currency": "INR" }

Server: if this key was processed before, return same response.

One-liner: Idempotency means repeating the same request produces the same result — GET, PUT, DELETE are idempotent; POST i

Deep • Crisp • Interview-Ready


REST API Interview Guide Page 12

11 — Error Handling

Error handling defines how an API communicates failures clearly and consistently.

Standard Error Response Structure


HTTP/1.1 400 Bad Request
Content-Type: application/json

{
"status": 400,
"error": "Bad Request",
"message": "Email is invalid",
"path": "/users",
"timestamp": "2026-02-05T10:30:00Z"
}

Best Practices
✔ Use correct HTTP status codes — never return 200 for errors
✔ Always return a consistent error response schema
✔ Never expose internal stack traces to clients
✔ Use meaningful human-readable messages
✔ Log detailed errors internally; show safe messages externally

12 — Data Formats: JSON & XML

Aspect JSON XML


Weight Lightweight Verbose

Readability High Medium

Parse Speed Fast Slower

Use Case Modern REST APIs Legacy / SOAP / enterprise

Content-Type application/json application/xml

Content Negotiation
Client requests format; server confirms format:

Request: Accept: application/json


Response: Content-Type: application/json

13 — Caching

Caching stores responses temporarily so repeated requests are served faster without hitting the server. REST
explicitly includes cacheability as a core constraint.

Cache-Control Directives

Deep • Crisp • Interview-Ready


REST API Interview Guide Page 13

Directive Meaning
max-age=3600 Cache for 3600 seconds

no-cache Revalidate with server before using cached response

no-store Never cache this response

public Cacheable by any intermediary

private Cacheable by client only

ETag (Entity Tag) — Cache Validation


1. Server returns: ETag: "abc123"
2. Client sends: If-None-Match: "abc123"
3. If unchanged: 304 Not Modified (no body, saves bandwidth)
4. If changed: 200 OK + new ETag + new body

Request Type Cacheable? Reason


GET Yes Read-only, safe to cache

POST No Creates new resources

PUT/PATCH/DELETE No Mutates state

Sensitive data No Security risk

Best Practices
✔ Cache GET responses aggressively
✔ Use ETag for validation, not Last-Modified (more precise)
✔ Short TTL (max-age) for dynamic data
✔ Never cache sensitive user-specific data publicly
✔ Combine server-side Redis cache + CDN for best performance

Deep • Crisp • Interview-Ready


REST API Interview Guide Page 14

14 — Versioning

APIs evolve. Breaking changes must not affect existing clients. Versioning allows old and new API versions to
coexist.

Strategy Example Pros Cons


URI Versioning (most common) /api/v1/users Simple, visible URI pollution

Header Versioning (REST-pure) Accept: application/[Link].v2+json Clean URIs Less visible

Query Param (avoid) /users?version=2 Simple Not recommended

Best practice: use URI versioning for simplicity in most cases. Use header versioning for strict REST compliance in mature APIs.

15 — Pagination & Filtering

Pagination

Prevents returning thousands of records in one response. Always paginate large collections.

Strategy Example Best For


Offset-based GET /users?page=2&limit=20 Simple, most common

Cursor-based GET /users?cursor=abc&limit=20 Large datasets, infinite scroll

Standard Paginated Response


{
"data": [...],
"page": 2,
"limit": 20,
"totalRecords": 250,
"totalPages": 13
}

Filtering & Sorting

GET /orders?status=completed&date=2026-02-01
GET /products?category=phone&sort=price&order=asc

16 — Rate Limiting

Rate limiting restricts how many requests a client can make within a time window. It protects APIs from abuse,
DoS attacks, and resource exhaustion.

Deep • Crisp • Interview-Ready


REST API Interview Guide Page 15

Standard Rate Limit Response Headers


X-RateLimit-Limit: 100 (max requests per window)
X-RateLimit-Remaining: 34 (requests left in this window)
X-RateLimit-Reset: 1712345678 (when window resets, epoch time)

When limit exceeded:


HTTP/1.1 429 Too Many Requests
Retry-After: 60

Rate Limiting Strategies


Strategy Description Best For
Fixed Window N requests per minute, resets hard Simple use cases

Sliding Window Rolling N requests per last 60s Smoother, more accurate

Token Bucket Tokens replenish over time; burst allowed APIs needing burst capacity

Leaky Bucket Requests processed at fixed rate Strict flow control

Where Rate Limiting is Enforced


• API Gateway (most common — Kong, AWS API Gateway, Nginx)
• Reverse proxy / load balancer
• Application middleware

One-liner: Rate limiting protects APIs from abuse and ensures fair usage by restricting the number of requests per time window, re

Deep • Crisp • Interview-Ready


REST API Interview Guide Page 16

17 — HATEOAS

HATEOAS = Hypermedia As The Engine Of Application State. It is the highest level of REST maturity.
Responses include links that tell the client what it can do next. The client does not need to hardcode URLs — it
discovers them from the response.

Example Response with HATEOAS


{
"id": 10,
"name": "Bharath",
"links": [
{ "rel": "self", "href": "/users/10", "method": "GET" },
{ "rel": "orders", "href": "/users/10/orders", "method": "GET" },
{ "rel": "update", "href": "/users/10", "method": "PATCH" },
{ "rel": "delete", "href": "/users/10", "method": "DELETE" }
]
}

Benefits
• API is self-documenting — clients discover available actions
• Decouples client from hardcoded URLs
• Server can change URLs without breaking clients

Reality Check
HATEOAS is theoretically ideal but rarely fully implemented in practice. Most real-world APIs implement partial
HATEOAS (links in responses). Useful to know for senior-level discussions.

18 — REST vs SOAP

Aspect REST SOAP


Type Architectural style Protocol

Data Format JSON, XML, HTML XML only

Protocol HTTP HTTP, SMTP, TCP

Coupling Loosely coupled Tightly coupled

Performance Lightweight, fast Heavy, verbose

Caching Supported Not natively

Security HTTPS + JWT WS-Security built in

Error Handling HTTP status codes SOAP Fault XML

Standards Flexible Strict (WSDL contract)

Use Cases Web/mobile APIs, microservices Enterprise, banking, legacy

Learning Curve Low High

Deep • Crisp • Interview-Ready


REST API Interview Guide Page 17

One-liner: REST is lightweight, flexible, and uses JSON over HTTP. SOAP is a strict protocol with XML and built-in security — used

Deep • Crisp • Interview-Ready


REST API Interview Guide Page 18

19 — Quick Reference Tables

REST Principles Summary


Principle Core Purpose
Client–Server Independent frontend/backend

Statelessness Scalable, self-contained requests

Uniform Interface Consistent, predictable API design

Resource-Based Noun URIs + HTTP verb actions

Cacheability Performance and scalability

Layered System Security and flexibility

HTTP Methods vs Idempotency


Method Purpose Idempotent Safe
GET Read Yes Yes

HEAD Read metadata Yes Yes

POST Create No No

PUT Replace Yes No

PATCH Partial update No No

DELETE Delete Yes No

Status Code Cheatsheet


Code Meaning Scenario
200 OK Successful GET/PUT/PATCH

201 Created POST success

204 No Content DELETE success

304 Not Modified ETag cache hit

400 Bad Request Invalid input

401 Unauthorized No/bad token

403 Forbidden No permission

404 Not Found Resource missing

409 Conflict Duplicate resource

422 Unprocessable Business rule fail

429 Too Many Requests Rate limit hit

500 Server Error Unexpected failure

REST API Complete Interview Guide • 19 Topics • Deep • Crisp • Interview-Ready

Deep • Crisp • Interview-Ready

You might also like