Preparing for a technical interview involving web services requires a solid grasp of architectural principles, not just syntax memorization. Whether you are a backend developer, a full-stack engineer, or a QA specialist moving into automation, understanding the nuances of RESTful APIs is non-negotiable. This guide covers the most frequently asked restful api interview questions and answers, categorized by difficulty and concept, to help you articulate your knowledge with confidence And that's really what it comes down to..
Understanding the Core Philosophy: REST vs. RESTful
Before diving into specific mechanics, interviewers often test your foundational understanding of the architecture itself.
What is the difference between REST and RESTful? This is a classic opener. REST (Representational State Transfer) is the architectural style—a set of constraints defined by Roy Fielding in his 2000 dissertation. RESTful describes a service or API that adheres to those constraints. Think of REST as the blueprint and RESTful as the building constructed according to that blueprint. An API can be HTTP-based without being truly RESTful if it violates constraints like statelessness or uniform interface.
What are the six architectural constraints of REST? You don't need to recite them verbatim, but you should explain the implication of each:
- Uniform Interface: Resources are identified by URIs, manipulated through representations, self-descriptive messages, and hypermedia as the engine of application state (HATEOAS).
- Stateless: The server stores no client context between requests. Every request contains all information needed to process it. This enables massive scalability.
- Cacheable: Responses must explicitly or implicitly define themselves as cacheable or non-cacheable to improve client performance and reduce server load.
- Client-Server: Separation of concerns. The client handles UI/UX; the server handles data storage and business logic. They evolve independently.
- Layered System: The client cannot ordinarily tell whether it is connected directly to the end server or an intermediary (load balancer, proxy, gateway).
- Code on Demand (Optional): Servers can extend client functionality by transferring executable code (e.g., Java applets, JavaScript).
HTTP Methods and Idempotency: The Mechanics
Interviewers love to probe your understanding of HTTP verbs beyond simple CRUD mapping Surprisingly effective..
Explain the difference between PUT and PATCH. This is arguably the most common "trick" question Small thing, real impact. That's the whole idea..
- PUT is idempotent and replaces the entire resource. If you send a partial object, the missing fields are typically nulled out or reset to defaults. Sending the same PUT request ten times results in the exact same resource state.
- PATCH is used for partial updates. You send only the fields you want to change. While PATCH can be idempotent, the RFC does not require it to be. It is safer for modifying specific attributes without overwriting the whole entity.
Define Idempotency. Which HTTP methods are idempotent? Idempotency means making the same request multiple times produces the same result on the server as making it once. The network effect (sending bytes) happens every time, but the server state changes only once.
- Idempotent:
GET,HEAD,OPTIONS,TRACE,PUT,DELETE. - Not Idempotent:
POST,PATCH(generally).
Why does this matter? It dictates retry logic. If a PUT times out, the client can safely retry. If a POST (create order) times out, retrying might create duplicate orders unless you implement idempotency keys.
When would you use POST vs. PUT for resource creation?
Use POST when the server decides the URI (e.g., POST /users returns Location: /users/123). Use PUT when the client dictates the URI (e.g., PUT /users/123 to create or replace user 123 explicitly).
Status Codes: Speaking the Protocol's Language
Returning 200 OK for everything is a red flag. You must demonstrate precision.
Match the scenario to the correct status code:
- 200 OK: Standard success for
GET,PUT,PATCH. - 201 Created: Successful resource creation via
POST. Must include aLocationheader pointing to the new resource. - 204 No Content: Success with no response body (common for
DELETEorPUT/PATCHwhere the client already has the data). - 400 Bad Request: Client sent malformed syntax or invalid validation data.
- 401 Unauthorized: Authentication missing or invalid (credentials bad).
- 403 Forbidden: Authentication valid, but authorization fails (user lacks permission).
- 404 Not Found: Resource doesn't exist.
- 409 Conflict: Request conflicts with current state (e.g., duplicate unique key, version mismatch in optimistic locking).
- 422 Unprocessable Entity: Semantic errors (validation failed) – often preferred over 400 for API validation logic.
- 429 Too Many Requests: Rate limiting.
- 500 Internal Server Error: Generic server failure.
- 503 Service Unavailable: Server down for maintenance or overloaded.
API Design: Resources, Naming, and Versioning
Design questions reveal your ability to build maintainable, scalable systems.
What are the best practices for URI naming?
- Use nouns, not verbs:
/usersnot/getUsersor/createUser. The HTTP verb provides the action. - Pluralize collections:
/users/123is preferred over/user/123for consistency. - Hierarchy for relationships:
GET /users/123/ordersretrieves orders for user 123. - Lowercase with hyphens:
/order-itemsnot/orderItemsor/Order_Items. - No file extensions: Use
Acceptheaders (Accept: application/json) instead of/users.json.
How do you handle API Versioning? There are three main strategies; know the trade-offs:
- URI Versioning (
/v1/users): Most common, explicit, easy to debug/cache. Breaks URI permanence. - Header Versioning (
Accept: application/vnd.myapp.v1+json): Keeps URIs clean, REST-purist approach. Harder to test in browser, caching complexity. - Query Param (
/users?version=1): Simple but clutters query string; often ignored by caches.
How do you handle filtering, sorting, and pagination? Use query parameters on collection endpoints Surprisingly effective..
- Filtering:
GET /users?role=admin&status=active - Sorting:
GET /users?sort=-createdAt,email(minus for descending). - Pagination: Offset-based (
limit=20&offset=40) is easy to implement but suffers from performance drift and "shifting window" issues on large datasets. Cursor-based (after=opaque_cursor_string) is superior for infinite scroll and large datasets as it points to a specific record position.
Security and Authentication
Explain the difference between Authentication and Authorization.
- Authentication (AuthN): Who are you? Verifying identity (Username/Password, JWT, API Key, OAuth).
- Authorization (AuthZ): What can you do? Verifying permissions (RBAC, ABAC, Scopes).
**Compare JWT (JSON Web Tokens
JWT Deep‑Dive
-
Structure – A JWT consists of three Base64‑URL‑encoded sections:
- Header – metadata such as the signing algorithm (e.g.,
HS256orRS256) and token type. - Payload – claims that convey information about the subject (e.g.,
sub,email,role) and optional custom data. - Signature – a cryptographic hash created with the header’s algorithm and a secret key (HMAC) or a private key (RSA/ECDSA).
- Header – metadata such as the signing algorithm (e.g.,
-
Statelessness – Because the server does not need to look up a session record, JWTs enable true stateless authentication. This is attractive for micro‑service architectures and high‑throughput APIs, but it also means the server must trust the token’s integrity and validity without external checks.
-
Expiration & Renewal – Tokens should carry an
expclaim (expiration timestamp) to limit their lifespan. Short‑lived access tokens paired with long‑lived refresh tokens strike a balance between security and usability. Refresh tokens are typically stored server‑side (in a database or Redis) and can be revoked if suspicious activity is detected. -
Security Considerations –
- Algorithm Choice – Prefer asymmetric algorithms (RS256, ES256) for public‑facing services; they allow key rotation without redistributing secrets.
- Key Management – Store signing keys in a dedicated secret manager (e.g., HashiCorp Vault, AWS KMS) and rotate them regularly.
- Audience & Issuer – Include
aud(intended recipient) andiss(issuer) claims to prevent token misuse across services. - Transport Security – Always transmit JWTs over TLS‑encrypted connections; never send them in clear text over HTTP.
- Storage – When using cookies, mark them
HttpOnly,Secure, andSameSite=Strict/Laxto mitigate XSS and CSRF. If stored in browser local storage, be aware of XSS risks. - Revocation – Because JWTs are immutable, revocation requires a separate mechanism (e.g., a denylist stored in Redis, a token version number in the payload, or short expiration combined with refresh tokens).
-
Common Pitfalls –
- Accepting the
nonealgorithm without proper validation. - Using weak secret keys (e.g., short or guessable strings).
- Relying solely on JWTs for revocation without an auxiliary check.
- Over‑loading the payload with large amounts of data, which inflates token size and may affect URL limits.
- Accepting the
OAuth 2.0 & Scopes
-
Authorization Flows – The framework defines several grant types:
- Authorization Code – Best for web applications; the user authenticates once, and the resulting code is exchanged for tokens.
- Client Credentials – Used for server‑to‑server communication where no user context exists.
- Password – Directly collects user credentials; discouraged except in legacy systems.
- Device Code – Optimized for devices with limited input capabilities (e.g., smart TVs).
-
Scopes – Fine‑grained permissions expressed as space‑separated strings (e.g.,
read:profile write:orders). The client must request the needed scopes during the authorization request, and the authorization server validates that the client is permitted to act on them. -
Token Introspection – When a resource server cannot verify a JWT locally (e.g., in a federated identity scenario), it can call an introspection endpoint to obtain token metadata, including active status, scopes, and expiration.
Defensive Layers Beyond Authentication
| Threat | Mitigation | |--------|
Defensive Layers Beyond Authentication
The core defenses outlined above protect against unauthorized access and token misuse, but dependable security also requires safeguards that address issues far removed from initial login. Below is an expanded view of the most relevant threats and how they can be mitigated within a defense‑in‑depth strategy The details matter here..
| Threat | Mitigation |
|---|---|
| Token Replay / Reuse | Embed a unique jti (JWT ID) claim and keep a short‑term blacklist of issued IDs; reject any token whose jti appears in the list before validation. |
| Man‑in‑the‑Middle (MITM) Interception | Enforce TLS 1.2+ on every hop, enable HTTP Strict Transport Security (HSTS), and consider certificate pinning for high‑value services. |
| Insider Secrets Exposure | Store signing keys and private material exclusively in a hardware security module or cloud KMS; apply role‑based access control so only authorized services can request key rotations. |
iss claims against expected values; reject tokens where the audience does not match the resource server’s identifier or where the issuer is not in the trusted allow‑list. So naturally, |
| Denial‑of‑Service via Introspection | Cache introspection results for the token’s remaining TTL (with a short max‑age), rate‑limit calls per client, and prefer local JWT validation with JWKS caching to reduce round‑trips. |
| Algorithm Confusion | Explicitly configure the validation library to accept only a single algorithm (e.g.And , RS256 or ES256); never fall back to none or symmetric algorithms when asymmetric keys are expected. |
| Refresh Token Theft | Issue refresh tokens with strict rotation policies: rotate on every use, bind to client identity and IP subnet, and revoke the entire chain if a reuse event is detected. |
| Cross‑Site Request Forgery (CSRF) on Token Endpoints | Require SameSite=Strict or Lax cookies for browser‑based flows; for SPA/mobile clients, use PKCE with the Authorization Code flow and avoid storing tokens in cookies altogether.
Operational Hygiene: Logging, Rotation, and Incident Response
Even perfectly implemented cryptography degrades over time without operational discipline. Treat the following practices as non‑negotiable components of the lifecycle:
- Structured Audit Logs – Emit immutable, tamper‑evident logs for every token issuance, refresh, revocation, and validation failure. Include correlation IDs (
jti,sid), client IDs, requested scopes, and the decision outcome. Ship logs to a SIEM with alerts on anomalies: spikes ininvalid_signatureerrors, repeatedjticollisions, or geographic impossibilities. - Automated Key Rotation – Rotate asymmetric signing keys on a fixed schedule (e.g., every 90 days) and immediately upon any suspected compromise. Publish new JWKS entries before retiring old keys; maintain a two‑key overlap window so in‑flight tokens remain verifiable. Automate the rollout via CI/CD pipelines that run integration tests against the new key set.
- Revocation Infrastructure – Maintain a distributed, low‑latency revocation store (Redis, etcd, or a dedicated token‑revocation service) keyed by
jtiandsub. Propagate revocation events via pub/sub so all resource servers invalidate cached introspection results within seconds. - Chaos Testing – Regularly inject failures: expire keys unexpectedly, simulate JWKS endpoint unavailability, and flood introspection endpoints. Verify that services degrade gracefully (serving cached keys, rejecting unknown
kids) rather than failing open. - Post‑Incident Token Forensics – After a breach, replay audit logs to reconstruct the blast radius: which
subs were active, which scopes were exercised, and whether refresh‑token chains were harvested. Use this data to force targeted re‑authentication rather than a global password reset.
Conclusion
Securing modern identity flows is not a checklist item—it is a continuous discipline that spans cryptographic hygiene, protocol correctness, and operational resilience. JWTs and OAuth 2.0 provide powerful, standards‑based primitives, but their safety hinges entirely on how they are wired together: validating every claim, binding tokens to their intended audience, rotating secrets before they stale, and instrumenting every handshake so anomalies become visible in real time But it adds up..
By layering strict validation, short‑lived credentials, PKCE‑protected flows, hardware‑backed key storage, and automated revocation, you transform authentication from a perimeter gate into a verifiable, auditable conversation between mutually suspicious parties. Invest in the plumbing, automate the rotation, and treat every token as a time‑limited capability that must prove its legitimacy on every request. Here's the thing — that conversation—encrypted, signed, scoped, and monitored—is the only reliable foundation for zero‑trust architectures. The result is a system that survives not just the threats we know today, but the ones we have yet to imagine Surprisingly effective..
Some disagree here. Fair enough.