Fundamentals of REST APIs — Interview Questions & Answers

50 essential REST API interview questions covering HTTP methods, status codes, authentication, versioning, statelessness, and best practices.

Meritshot17 min read
REST APIHTTPBackendInterview QuestionsWeb Development
Back to Interview Guides

REST Fundamentals

1. What is a REST API?

A REST API (Representational State Transfer Application Programming Interface) is an architectural style for designing networked applications that communicate over HTTP. It exposes resources—such as users, orders, or products—through URLs, and clients interact with those resources using standard HTTP methods like GET, POST, PUT, and DELETE. REST emphasizes a uniform interface, statelessness, and a clear separation between client and server.

2. What does "REST" stand for and who introduced it?

REST stands for Representational State Transfer, and it was introduced by Roy Fielding in his 2000 doctoral dissertation. The term describes the way the state of a resource is transferred between client and server through representations such as JSON or XML. Fielding defined REST as a set of architectural constraints rather than a strict protocol or standard.

3. What are the core architectural constraints of REST?

REST defines six guiding constraints: client-server separation, statelessness, cacheability, a uniform interface, a layered system, and optional code-on-demand. These constraints work together to produce scalable, loosely coupled, and maintainable systems. An API that satisfies all of these constraints (except the optional code-on-demand) is considered truly RESTful.

4. What is a resource in REST?

A resource is any piece of information or entity that can be named and addressed, such as a user, a document, or a collection of products. Each resource is identified by a unique URI, for example /users/42, and clients act on it through HTTP methods. Resources are conceptual; what travels over the wire is a representation of the resource's current state, typically formatted as JSON.

5. What is the difference between REST and SOAP?

REST is an architectural style that primarily uses lightweight formats like JSON over HTTP, while SOAP is a strict protocol that relies on XML messaging and a rigid contract defined in WSDL. REST is generally simpler, faster, and more flexible, making it well-suited for web and mobile applications. SOAP offers built-in standards for security and transactions, which can be valuable in enterprise systems with stringent reliability requirements.

6. What does it mean for a REST API to be stateless?

Statelessness means the server does not store any client session information between requests, so each request must contain all the information needed to process it. This includes authentication tokens, query parameters, and request bodies. Statelessness improves scalability because any server instance can handle any request without relying on previously stored context.

7. What is the uniform interface constraint in REST?

The uniform interface constraint requires that resources be manipulated in a consistent, predictable way across the entire API. It is built on principles such as identifying resources through URIs, manipulating them through representations, using self-descriptive messages, and applying hypermedia as the engine of application state (HATEOAS). A uniform interface decouples clients from the server implementation and simplifies the overall architecture.

8. What is HATEOAS?

HATEOAS, or Hypermedia As The Engine Of Application State, is a REST principle in which responses include links that guide the client to related actions and resources. For example, a response for an order might include links to cancel it or view its invoice. This allows clients to navigate the API dynamically without hardcoding every endpoint, reducing tight coupling between client and server.

9. What is an idempotent operation in REST?

An idempotent operation produces the same result on the server no matter how many times it is repeated with the same input. For example, calling PUT /users/42 with identical data multiple times leaves the resource in the same final state. Idempotency is important for reliability because clients can safely retry failed requests without causing unintended side effects.

10. What is the difference between a resource and a representation?

A resource is the abstract entity or concept, such as "the user with ID 42," while a representation is a concrete snapshot of that resource's state at a point in time. The same resource can have multiple representations, for instance JSON for an API client and HTML for a browser. Clients exchange representations with the server, and the server uses them to read or modify the underlying resource.

HTTP Methods & Status Codes

11. What are the most common HTTP methods used in REST APIs?

The most common methods are GET for retrieving data, POST for creating resources, PUT for replacing or updating resources, PATCH for partial updates, and DELETE for removing resources. Each method has a well-defined semantic meaning that clients and servers agree upon. Using these methods correctly keeps an API intuitive and aligned with HTTP standards.

12. What is the difference between PUT and PATCH?

PUT replaces an entire resource with the payload provided, so the request should contain the complete representation of the resource. PATCH applies a partial update, modifying only the fields included in the request body. As a result, PUT is idempotent while PATCH may or may not be, depending on how the partial update is defined.

13. What is the difference between POST and PUT?

POST is typically used to create a new resource where the server assigns the identifier, and it is not idempotent because repeated calls create multiple resources. PUT is used to create or replace a resource at a known URI specified by the client, and it is idempotent. In short, use POST to add to a collection and PUT when you control the resource's location.

14. Which HTTP methods are considered safe?

Safe methods are those that do not modify server state, meaning they are read-only operations. GET, HEAD, and OPTIONS are safe because they only retrieve information or metadata without causing side effects. Safe methods can be cached and prefetched by browsers and proxies without risk of altering data.

15. What does the HTTP status code 200 mean?

The 200 OK status code indicates that the request succeeded and the server is returning the requested data or confirmation. It is the most common response for successful GET and PUT requests. The exact meaning depends on the method, but in all cases it signals that the operation completed without error.

16. What does the HTTP status code 201 mean?

The 201 Created status code indicates that a request succeeded and a new resource was created as a result, most commonly in response to a POST. The response should typically include a Location header pointing to the URI of the newly created resource. This code gives the client clear confirmation that its create operation worked.

17. What does the HTTP status code 204 mean?

The 204 No Content status code indicates that the request succeeded but there is no body to return in the response. It is commonly used for successful DELETE operations or PUT updates where returning the resource is unnecessary. The client should not expect a payload and can proceed knowing the action completed.

18. What does the HTTP status code 400 mean?

The 400 Bad Request status code signals that the server could not process the request due to a client error, such as malformed syntax or invalid input data. It tells the client that the request should not be retried without modification. A good API includes a descriptive error message explaining what was wrong so the client can fix it.

19. What does the HTTP status code 401 versus 403 mean?

401 Unauthorized means the request lacks valid authentication credentials, so the client must log in or provide a valid token. 403 Forbidden means the client is authenticated but does not have permission to access the requested resource. In short, 401 is about identity while 403 is about authorization.

20. What does the HTTP status code 404 mean?

The 404 Not Found status code indicates that the server could not find the requested resource at the given URI. It may mean the resource never existed or has been removed. APIs sometimes use 404 deliberately to avoid revealing whether a protected resource exists for security reasons.

21. What does the HTTP status code 500 mean?

The 500 Internal Server Error status code indicates that an unexpected condition prevented the server from fulfilling the request. It is a generic server-side error, signaling a problem with the application rather than the client's request. Well-designed APIs log the underlying cause and return a safe, non-revealing message to the client.

22. What are the five categories of HTTP status codes?

HTTP status codes are grouped into five ranges based on their leading digit: 1xx for informational responses, 2xx for success, 3xx for redirection, 4xx for client errors, and 5xx for server errors. This grouping lets clients quickly classify the outcome of a request. For example, any code in the 4xx range signals that the client must change something before retrying.

23. When should you return a 429 status code?

The 429 Too Many Requests status code is returned when a client has sent too many requests in a given time frame and has hit a rate limit. The response often includes a Retry-After header indicating when the client may try again. This code protects the server from abuse and ensures fair usage across all consumers.

24. What is the purpose of the OPTIONS method?

The OPTIONS method asks the server which communication options or HTTP methods are available for a given resource. It is also central to CORS preflight requests, where the browser checks whether a cross-origin request is permitted before sending it. The server responds with headers like Allow to describe the supported operations.

Request & Response Design

25. What is the difference between path parameters and query parameters?

Path parameters identify a specific resource and are part of the URL path, such as 42 in /users/42. Query parameters appear after the ? and are used to filter, sort, or paginate collections, such as /users?role=admin&page=2. As a rule, use path parameters for resource identity and query parameters for optional modifiers.

26. What data formats are commonly used in REST APIs?

JSON is by far the most common format because it is lightweight, human-readable, and natively supported in JavaScript and most languages. XML was historically popular and is still used in some legacy and enterprise systems. APIs may also return formats like CSV, plain text, or binary data depending on the use case and the client's Accept header.

27. What is content negotiation in REST?

Content negotiation is the mechanism by which a client and server agree on the format of the data exchanged. The client sends an Accept header indicating preferred formats, such as application/json, and the server responds with the matching representation and a corresponding Content-Type header. This allows a single resource to serve multiple representations to different clients.

28. What is the purpose of the Content-Type header?

The Content-Type header tells the recipient the media type of the body being sent, such as application/json or multipart/form-data. On a request, it informs the server how to parse the incoming payload, and on a response it tells the client how to interpret the returned data. Setting it correctly prevents parsing errors and ensures predictable communication.

29. How should errors be structured in a REST API response?

Errors should use the appropriate HTTP status code and include a consistent, structured body, typically JSON with fields like an error code, a human-readable message, and optional details. A predictable error format lets clients handle failures programmatically. Including a request identifier or timestamp also helps with debugging and support.

30. What is the difference between a collection and a singleton resource?

A collection resource represents a group of items, such as /users, and typically supports listing and creating members. A singleton or item resource represents one specific entity, such as /users/42, and supports retrieving, updating, or deleting that entity. Designing clear URIs around this distinction makes an API intuitive and consistent.

31. Why should REST endpoints use nouns rather than verbs?

REST models actions through HTTP methods rather than through the URL, so endpoints should name resources with nouns like /orders rather than verbs like /getOrders. The method GET /orders already conveys the action of retrieval, keeping the design clean and predictable. Using nouns also makes the API more uniform and easier for developers to learn.

Nested resources are expressed by reflecting their relationship in the URI hierarchy, for example /users/42/orders to represent the orders belonging to a specific user. This makes ownership and context clear at a glance. However, deeply nested URIs should be avoided beyond two levels, as they become hard to maintain and can be replaced with query parameters or links.

33. What is the role of the Accept header in a request?

The Accept header lets the client specify which media types it can handle in the response, such as Accept: application/json. The server uses this to perform content negotiation and return the best matching representation. If the server cannot satisfy the requested type, it may respond with 406 Not Acceptable.

34. What is request validation and why is it important?

Request validation is the process of checking incoming data for correctness, completeness, and proper format before processing it. It prevents malformed or malicious input from reaching business logic, reduces errors, and improves security. Failed validation should return a 400 Bad Request with clear details about which fields were invalid.

Authentication & Security

35. What is the difference between authentication and authorization?

Authentication verifies who a user is, typically by validating credentials like a password or token. Authorization determines what an authenticated user is allowed to do, such as accessing a specific resource or performing an action. An API usually authenticates a request first and then checks authorization before granting access.

36. What is API key authentication?

API key authentication uses a unique secret string that a client includes with each request, often in a header like X-API-Key, to identify and authorize the caller. It is simple to implement and commonly used for server-to-server communication or public APIs with usage tracking. However, API keys alone provide limited security and should always be transmitted over HTTPS and rotated regularly.

37. What is token-based authentication?

Token-based authentication issues a client a token after successful login, which the client then sends with subsequent requests, usually in the Authorization header. The server validates the token instead of requiring credentials on every call, which fits REST's stateless nature. Tokens can be revoked or expired, giving fine-grained control over access.

38. What is a JWT and how is it used in REST APIs?

A JWT (JSON Web Token) is a compact, self-contained token that encodes claims about a user, signed to ensure integrity. It typically contains three parts—a header, a payload, and a signature—separated by dots. In REST APIs, the client sends the JWT in the Authorization: Bearer <token> header, and the server verifies the signature without needing to store session state.

39. What is OAuth 2.0 and when would you use it?

OAuth 2.0 is an authorization framework that lets a third-party application access a user's resources without exposing their credentials, using access tokens issued by an authorization server. It is widely used for delegated access, such as letting an app post on a user's behalf or signing in with Google. OAuth 2.0 is ideal when you need secure, scoped, and revocable access across different services.

40. Why is HTTPS important for REST APIs?

HTTPS encrypts the data exchanged between client and server using TLS, protecting sensitive information like tokens, passwords, and personal data from interception. Without it, credentials and payloads travel in plain text and can be read or modified by attackers performing man-in-the-middle attacks. HTTPS is considered mandatory for any production API handling authentication or private data.

41. What is CORS and why does it matter?

CORS (Cross-Origin Resource Sharing) is a browser security mechanism that controls whether a web page from one origin can make requests to an API on a different origin. The server uses headers like Access-Control-Allow-Origin to declare which origins are permitted. Configuring CORS correctly is essential for letting trusted front-end applications call your API while blocking unauthorized ones.

42. How can you protect a REST API against common attacks?

Protecting an API involves enforcing HTTPS, validating and sanitizing all input to prevent injection, and applying authentication and authorization on every protected endpoint. Additional measures include rate limiting to deter abuse, using security headers, and never exposing sensitive details in error messages. Regularly updating dependencies and conducting security reviews further reduces vulnerabilities.

43. What is rate limiting and how does it improve security?

Rate limiting restricts how many requests a client can make within a defined time window, typically tracked by API key, IP address, or user. It protects the API from abuse, brute-force attacks, and accidental overload, helping maintain availability for all users. When a limit is exceeded, the server returns a 429 Too Many Requests response, often with a Retry-After header.

Versioning, Pagination & Best Practices

44. Why is API versioning necessary?

API versioning lets you introduce breaking changes without disrupting existing clients that depend on the current behavior. By maintaining multiple versions, you give consumers time to migrate at their own pace. This is critical for public APIs where you cannot control or force updates on every client.

45. What are the common strategies for versioning a REST API?

Common strategies include URI versioning (e.g. /v1/users), header versioning using a custom or Accept header, and query parameter versioning (e.g. /users?version=1). URI versioning is the most visible and widely adopted because it is easy to test and cache. The best choice depends on your clients, tooling, and how strictly you want to follow REST principles.

46. What is pagination and why is it important?

Pagination splits large result sets into smaller, manageable chunks so a single request does not return an overwhelming amount of data. It improves performance, reduces memory usage, and speeds up response times for both server and client. Without pagination, listing endpoints can become slow and unreliable as the underlying data grows.

47. What are common pagination techniques in REST APIs?

The two most common techniques are offset-based pagination, using parameters like ?page=2&limit=20, and cursor-based pagination, which uses a pointer to the next set of results. Offset pagination is simple but can become inefficient or inconsistent on large, frequently changing datasets. Cursor-based pagination is more stable and performant for high-volume data, making it a strong choice for large-scale APIs.

48. How does caching improve REST API performance?

Caching stores copies of responses so repeated requests can be served without recomputing or refetching the data, reducing latency and server load. REST leverages HTTP caching through headers like Cache-Control, ETag, and Last-Modified to control freshness and validation. Effective caching is one of the most impactful ways to scale a read-heavy API.

49. What is the purpose of the ETag header?

The ETag header is a unique identifier, often a hash, that represents a specific version of a resource. Clients can send it back in an If-None-Match header so the server can respond with 304 Not Modified when the resource is unchanged, avoiding unnecessary data transfer. ETags also support optimistic concurrency control, preventing clients from overwriting changes they have not seen.

50. What are some best practices for designing a maintainable REST API?

Best practices include using consistent and intuitive resource naming, applying the correct HTTP methods and status codes, and returning structured, predictable error responses. You should also enforce security through HTTPS and authentication, support pagination and filtering for large collections, and provide clear, up-to-date documentation. Versioning your API and following established conventions ensures it remains stable, scalable, and easy for developers to adopt.