REST API Interview Questions and Answers
Comprehensive Q&A for junior, mid-level, and senior developer interviews — covering HTTP, design principles, security, and real-world patterns.
Fundamentals
Q: What is REST, and what are its core constraints?
A: REST (Representational State Transfer) is an architectural style defined by Roy Fielding in his 2000 dissertation. A RESTful API must satisfy six constraints:
- Client-Server: Separation of concerns between UI/client and data/server
- Stateless: Each request contains all information needed — no server-side session state
- Cacheable: Responses must explicitly declare whether they can be cached
- Uniform Interface: Consistent resource identification, manipulation via representations, self-descriptive messages, and HATEOAS
- Layered System: Clients cannot tell whether they are connected directly to the server or an intermediary
- Code on Demand (optional): Servers can extend client functionality by transferring executable code
Q: What is the difference between REST and HTTP?
A: HTTP is the transport protocol — it defines how messages are sent over the network. REST is an architectural style that uses HTTP as its communication layer. REST leverages HTTP methods (GET, POST, PUT, DELETE), status codes, headers, and URLs, but REST principles (statelessness, uniform interface, etc.) are design constraints, not transport rules.
Q: What is a resource in REST?
A: A resource is any named piece of information that can be addressed with a URL. Resources are nouns (users, orders, products), not verbs. A resource is identified by its URL and may have multiple representations (JSON, XML, HTML). The key distinction: a resource is a concept, not a database row or object instance.
# Resource: a user
GET /users/42 → Returns user 42's representation
PUT /users/42 → Replaces user 42's representation
DELETE /users/42 → Deletes user 42
Q: What is statelessness, and why does it matter?
A: Statelessness means the server does not store any client session state between requests. Every request must contain all information required to process it — authentication credentials, pagination parameters, etc. This makes REST APIs horizontally scalable (any server can handle any request), simpler to cache, and easier to reason about.
The trade-off: clients must send more data per request (e.g., auth tokens on every call) and re-authenticate on each request.
HTTP Methods
Q: What is the difference between PUT and PATCH?
A: PUT replaces the entire resource — you send the complete representation. If a field is missing from the request body, it is removed or reset to its default. PATCH applies a partial update — only the fields you send are modified; everything else stays the same.
# PUT — sends full user object
PUT /users/42
{ "name": "Alice", "email": "alice@example.com", "role": "admin" }
# PATCH — only updates name
PATCH /users/42
{ "name": "Alice Smith" }
Idempotency: PUT must be idempotent. PATCH may or may not be — it depends on implementation (absolute value changes are idempotent; increments like {"views": "+1"} are not).
Q: What does idempotent mean? Which HTTP methods are idempotent?
A: An operation is idempotent if applying it multiple times produces the same result as applying it once. Idempotent HTTP methods:
- GET — Reads data; no side effects
- HEAD — Same as GET but no body
- PUT — Sets resource to the given state; repeating gives the same result
- DELETE — Deletes the resource; deleting again returns 404 but the system state is the same (resource is gone)
- OPTIONS — No side effects
POST is not idempotent — each call typically creates a new resource. This is why retry logic for POST requests requires idempotency keys.
Q: When should you use POST vs PUT?
A: Use POST when the server assigns the resource identifier (most common for creation). Use PUT when the client specifies the resource URL. A simple rule:
POST /users→ server generates ID, returns201 CreatedwithLocation: /users/42PUT /users/42→ client specifies ID, creates or replaces the resource
In practice, most APIs use POST for creation and PUT/PATCH for updates.
Q: What is the purpose of the OPTIONS method?
A: OPTIONS is used to discover what methods and headers are supported for a resource. Browsers automatically send a CORS preflight OPTIONS request before cross-origin requests that use non-simple methods or headers. The server responds with Allow and Access-Control-Allow-* headers indicating what is permitted.
HTTP Status Codes
Q: What is the difference between 401 and 403?
A:
- 401 Unauthorized: The request lacks valid authentication credentials. The client must authenticate (e.g., include a valid token). Despite the name, this is really an authentication failure.
- 403 Forbidden: The client is authenticated but does not have permission to access the resource. No amount of re-authentication will change this response.
Memory aid: 401 = "Who are you?" (authentication). 403 = "I know who you are, but no." (authorization).
Q: What status code should a successful POST return?
A: A POST that creates a new resource should return 201 Created with a Location header pointing to the new resource URL. If the POST performs an action but does not create a persistent resource (e.g., triggering a job), return 200 OK or 202 Accepted (if the processing is asynchronous).
HTTP/1.1 201 Created
Location: /orders/98765
Content-Type: application/json
{ "id": 98765, "status": "pending" }
Q: What is the difference between 404 and 410?
A: 404 Not Found means the resource does not exist at this URL — and it may have never existed or may reappear in future. 410 Gone means the resource existed but has been permanently removed and will not return. Use 410 for intentional deprecation (e.g., deleted user accounts), which signals to crawlers to remove the URL from their index.
Q: When do you use 422 vs 400?
A: 400 Bad Request covers malformed requests — invalid JSON, missing required headers, or a request the server cannot parse at all. 422 Unprocessable Entity (from RFC 9110) applies when the request is well-formed syntactically but fails semantic validation — for example, an end date before a start date, or an email field that contains a non-email string. Many APIs use 400 for both; 422 provides more precision.
Q: What does 429 Too Many Requests mean?
A: 429 indicates the client has exceeded a rate limit. The response should include a Retry-After header (or X-RateLimit-Reset) indicating when the client may retry. Well-designed APIs also include X-RateLimit-Limit and X-RateLimit-Remaining headers on every response so clients can track their usage proactively.
Authentication & Security
Q: What is the difference between authentication and authorization?
A: Authentication is the process of verifying who the caller is (identity). Authorization is the process of determining what the caller is allowed to do (permissions). Authentication happens first. A JWT token, for example, authenticates the caller; the scopes or roles inside the token determine their authorization.
Q: What is a JWT and how does it work?
A: A JSON Web Token (JWT) is a compact, URL-safe token format consisting of three Base64-encoded parts separated by dots: header.payload.signature.
- Header: Token type and signing algorithm (e.g., HS256, RS256)
- Payload: Claims — the data encoded in the token (user ID, roles, expiry)
- Signature: HMAC or RSA signature for tamper detection
JWTs are stateless — the server validates the signature without looking up anything in a database. The trade-off: tokens cannot be revoked before expiry (without a blocklist), so keep expiry times short.
Q: What is OAuth 2.0, and how is it different from API key authentication?
A: API key authentication is simple — the client includes a static key in the request header or query string. It works well for server-to-server communication and internal tools. OAuth 2.0 is a delegated authorization framework. It allows a user to grant a third-party application limited access to their account without sharing their credentials. OAuth 2.0 is the correct choice when:
- A third-party app needs to act on behalf of a user
- You need fine-grained, revocable scopes
- You're building a public API consumed by user-facing apps
Q: Why should API credentials never be sent in the URL?
A: URLs are logged in server access logs, browser history, reverse proxy logs, and Referer headers. Credentials embedded in URLs (e.g., ?api_key=secret) are exposed in all of these locations. Always send credentials in the Authorization header or a custom header, and always over HTTPS.
API Design
Q: What is a RESTful URL, and what makes a URL "good"?
A: Good REST URLs identify resources using nouns (not verbs), use lowercase with hyphens for readability, and represent hierarchical relationships. Key rules:
- Use nouns:
/ordersnot/getOrders - Use plural collections:
/usersnot/user - Model hierarchy:
/users/42/orders - No trailing slashes:
/users/42not/users/42/ - Use hyphens for readability:
/rate-limitingnot/rateLimiting - Actions as sub-resources when needed:
POST /orders/98/cancel
Q: What is HATEOAS?
A: HATEOAS (Hypermedia as the Engine of Application State) is one of REST's uniform interface constraints. A fully HATEOAS-compliant API embeds links in each response that describe available actions and related resources, so clients can discover the API dynamically without hardcoded URLs.
GET /orders/98765
→ 200 OK
{
"id": 98765,
"status": "pending",
"_links": {
"self": { "href": "/orders/98765" },
"cancel": { "href": "/orders/98765/cancel", "method": "POST" },
"items": { "href": "/orders/98765/items" }
}
}
In practice, very few production APIs implement full HATEOAS. Most APIs are "REST-like" and document their URLs in separate API reference docs.
Q: How should REST APIs handle versioning?
A: The three main strategies:
- URL versioning:
/v1/users— Most visible, easy to test, widely adopted (Stripe, GitHub). Simple to route but pollutes the URL. - Header versioning:
Accept: application/vnd.api+json; version=2— Keeps URLs clean; harder to test in a browser. - Query parameter:
/users?version=2— Simple but not RESTful (version is not a filter parameter).
Best practice: use URL versioning for public APIs, deprecate old versions with notice, and always document your deprecation timeline.
Q: What is the difference between a 301 and 302 redirect?
A: 301 Moved Permanently tells clients and crawlers that the resource has moved forever — update your bookmarks and links. 302 Found (temporary redirect) tells clients to go to the new URL for now, but to keep using the original URL in future. For API versioning deprecations and permanent URL changes, use 301. For temporary redirects or A/B testing, use 302.
Advanced Topics
Q: What is idempotency and why does it matter for API reliability?
A: Idempotency means the same operation can be safely retried without side effects. In distributed systems, requests fail and must be retried. Without idempotency, a network timeout on a payment POST could result in double-charging. Best practices:
- Use idempotency keys for non-idempotent operations (e.g.,
Idempotency-Key: uuidheader) - Store request results by key for a time window (e.g., 24 hours)
- Return the same response for duplicate requests instead of re-executing
Stripe, PayPal, and most payment APIs implement idempotency keys. See our Idempotency Guide for a full implementation walkthrough.
Q: What is CORS and how does it work?
A: CORS (Cross-Origin Resource Sharing) is a browser security mechanism that restricts cross-origin HTTP requests. When a browser-based app at app.example.com calls an API at api.other.com, the browser first sends a preflight OPTIONS request. The API server must respond with appropriate Access-Control-Allow-* headers to permit the actual request. Key headers:
Access-Control-Allow-Origin: *or specific originsAccess-Control-Allow-Methods: GET, POST, PUT, DELETEAccess-Control-Allow-Headers: Content-Type, AuthorizationAccess-Control-Max-Age: 86400— cache preflight for 24 hours
Never use Access-Control-Allow-Origin: * with Access-Control-Allow-Credentials: true — this is a security vulnerability.
Q: How do you design pagination for a REST API?
A: Three main strategies:
- Offset pagination:
?page=2&limit=25— Simple, but slow on large offsets and unstable under inserts/deletes - Cursor-based pagination:
?cursor=eyJpZCI6MTAwfQ==— Stable, performant, ideal for real-time feeds (used by Twitter/X, Stripe) - Keyset pagination:
?after_id=100&limit=25— Similar to cursor but uses a sortable field; fast indexed queries
Always include pagination metadata in responses: total_count, next/prev links or cursors, and has_more boolean. See our Pagination Guide for implementation details.
Q: What is the difference between REST and GraphQL?
A: REST uses multiple endpoints, each returning a fixed data structure. GraphQL uses a single endpoint where clients specify exactly which fields they want. REST is simpler to cache (HTTP caching works natively), easier to secure per-endpoint, and better for simple CRUD. GraphQL eliminates over-fetching and under-fetching, is excellent for complex, nested data requirements, and is preferred for client-driven UIs. See our REST vs GraphQL comparison for a full breakdown.
Q: How should REST APIs handle errors consistently?
A: A consistent error response format should include: HTTP status code, machine-readable error code, human-readable message, and where applicable, per-field validation errors. The RFC 7807 Problem Details format is increasingly adopted:
HTTP/1.1 422 Unprocessable Entity
Content-Type: application/problem+json
{
"type": "https://www.restguide.info/errors/validation-error",
"title": "Validation Error",
"status": 422,
"detail": "Request body failed validation",
"errors": [
{ "field": "email", "message": "Must be a valid email address" },
{ "field": "age", "message": "Must be 18 or older" }
]
}
Q: What is rate limiting, and which headers should your API return?
A: Rate limiting restricts how many requests a client can make in a given time window, protecting the API from abuse and ensuring fair usage. Standard response headers:
X-RateLimit-Limit: Maximum requests allowed in the windowX-RateLimit-Remaining: Requests remaining in the current windowX-RateLimit-Reset: Unix timestamp when the window resetsRetry-After: Seconds to wait before retrying (on 429 responses)
Common algorithms: token bucket (smooth), fixed window (simple), sliding window (accurate). See our Rate Limiting Guide for implementation details.
Related Topics
HTTP Methods
Deep dive into GET, POST, PUT, PATCH, DELETE and when to use each.
HTTP Status Codes
Complete reference for 2xx, 3xx, 4xx, and 5xx codes.
Authentication
JWT, OAuth 2.0, API keys, and security best practices.
Idempotency
Idempotency keys and safe retry patterns for reliable APIs.
Best Practices
URL design, naming conventions, versioning, and design patterns.
REST API Tutorial
Complete beginner's guide from first API call to design principles.