40 Frequently Asked REST API Interview Questions and Answers [2023]

REST (Representational State Transfer) has become the standard for building web APIs that allow systems to communicate over HTTP in a simple and flexible way. As REST continues to gain popularity, you can expect more REST API interview questions to come up whether you are applying for backend, full stack or devops roles.

In this comprehensive guide, we have put together 40+ popular REST API interview questions along with detailed answers to help prepare you for your next tech interview.

What is REST?

REST or RESTful web services are a way of providing interoperability between computer systems on the internet. REST is an architectural style for building distributed systems based on hypermedia. It is independent of any underlying protocol and is not necessarily tied to HTTP. However, most common implementations use HTTP as the application protocol, and this guide focuses on the most practical REST over HTTP style.

Here are some key principles of REST:

  • Client-Server – There should be a separation between the client and server.

  • Stateless – No client context is stored on the server between requests. Each request contains all necessary information required to process it.

  • Cacheable – REST responses should define themselves as cacheable or not cacheable to prevent clients from getting stale data.

  • Uniform Interface – There should be a uniform way of interacting with a REST API regardless of the type of resources used.

  • Layered System – REST allows you to use a layered system architecture where you deploy APIs on server clusters for scalability.

  • Code on Demand (Optional) – Servers can also temporarily extend client functionality by transferring logic like Java Applets.

What is a Resource in REST?

A resource is an object or representation of something that has an identifier, metadata, and relationships with other resources. Resources are the fundamental concepts that REST APIs revolve around.

For example, in an e-commerce API, resources can include:

  • Products
  • Categories
  • Cart
  • Orders
  • Customers

Each resource is addressed using a Unique Resource Identifier (URI) that the client uses to perform operations on it. Resources can have multiple representations like JSON, XML, etc.

Explain REST Constraints

Below are the key constraints that define a REST API:

Client–server – The API has to be separate from the client used to access it. This improves portability and scalability.

Stateless – No client state stored on server. Sessions are stored on client.

Cacheable – API responses must clarify if they can be cached or not.

Uniform interface – Single consistent way of interacting with resources through their URIs.

Layered system – Multiple intermediaries can be placed to improve scalability without affecting the API.

What is an HTTP method? List common HTTP methods.

HTTP methods are request types supported by HTTP protocol like GET, POST, PUT, PATCH and DELETE that performs different operation on resources.

Here are some common HTTP methods:

  • GET – Retrieve a representation of a resource.

  • POST – Create a new resource

  • PUT – Update existing resource

  • PATCH – Update part of a resource

  • DELETE – Delete existing resource

What are the main status codes for HTTP response?

HTTP response status codes indicate the status from the server back to the client on whether the requested operation succeeded or not.

Below are the most common HTTP status codes:

  • 2xx – Successful responses like 200 OK and 201 Created
  • 3xx – Redirections
  • 4xx – Client errors like 400 Bad Request and 404 Not Found
  • 5xx – Server errors

What is an HTTP Response? Name key parts of an HTTP Response.

An HTTP response is the data sent back from the server to the client as an answer to an HTTP request.

The key parts of an HTTP response are:

  • Status Line – Includes the status code and status message. Eg. 200 OK
  • HTTP Version
  • Headers – Contains metadata like content-type, caching information, etc.
  • Response Body – The actual data being returned (optional)

What are the core components of an HTTP Request?

The key parts of an HTTP request are:

  • Method – GET, POST, PUT etc.
  • URL – End point being accessed including path and query string.
  • HTTP Version – HTTP 1.1
  • Request Headers – Additional information about request
  • Request Body – Data being sent (optional, depends on method)

Compare REST vs JSON-RPC vs SOAP vs GraphQL

Basis REST JSON-RPC SOAP GraphQL
Architecture Architectural style focused on Resources Protocol for calling methods XML Based protocol Runtime query language
Data Format Agnostic. Mostly JSON JSON XML JSON
Caching Built-in support for caching No native caching Caching if used Caching can be implemented
Contract No fixed contract. Flexible. Set of methods to call Strict contract through WSDL Has schema that defines API
Over Fetching Over fetching possible if API not designed properly Only requested data returned Only requested data returned Precise data requirements means no over fetching
Under Fetching Under fetching possible if data needs change later needing multiple API calls. Breaking changes can happen easily Breaking changes can happen easily No under fetching since you get data shaped exactly how you need. Less API calls overall.
Payload Size Smaller as only required data fetched Small payload size Can have large XML SOAP envelopes No wasted fields so payload sizes are small
Security Stateless so need to implement authentication separately for production systems Authentication to be handled separately by developer Various built-in security protocols Per field authorization possible in schema

What are some alternatives to REST APIs?

Some alternatives to REST APIs are:

  • GraphQL – Allows precise data fetching and mutations.
  • gRPC – Google‘s high performance RPC framework.
  • SOAP – XML heavyweight alternative to REST.
  • Webhooks – User defined callbacks over HTTP.

What are best practices for designing REST URIs?

Here are some best practices for creating URIs for resources in a REST API:

  • Use nouns instead of verbs in URIs.
  • Keep URIs lowercase and use hyphens to improve readability.
  • Don‘t use file extensions like .xml or .json.
  • Keep URIs short yet understandable and expand for hierarchical data.
  • Use path parameters over query strings for key resource identifiers.

Good URI:

/users/1234/orders

Bad URI:

/getUsersOrders?userid=1234

What are Safe and Idempotent methods?

Safe methods are HTTP methods that do not modify resources. Calling them many times produces the same result. For example GET, HEAD, OPTIONS.

Idempotent methods produce the same results regardless of how many times you call them. Multiple identical requests have the same effect as single request.

PUT, GET, HEAD, OPTIONS, DELETE are idempotent whereas POST is not idempotent.

How does REST handle security?

REST does not include any built-in security mechanisms including authentication, authorization and encryption. Hence these have to be implemented separately:

Authentication

  • API keys can be passed as part of headers in each request.
  • OAUTH2 access tokens can be used.
  • Integrate with SSO providers.

Authorization

  • REST APIs should check user roles and permissions before allowing access to resources.
  • User based Access Control Lists (ACL) can be implemented programmatically.

Encryption

  • SSL/TLS should be used to establish secure HTTP connections over SSL i.e. HTTPS. This will encrypt communication between client and server.

What are the pros and cons of using REST APIs?

Pros

  • Better separation of client and server allows for better scalability.
  • Using stateless protocol makes implementation simpler.
  • Caching improves performance and scalability by not repeating network calls.
  • Multiple data formats like JSON, XML, YAML, etc can be used.
  • REST uses open standards so less vendor lock-in.

Cons

  • As stateless, scalable session management needs to be implemented using tokens.
  • Over-fetching of data is possible without proper REST API design.
  • Hard to make data intensive, complex queries unlike GraphQL.
  • No built-in validation checks, security or error handling.

Compare SOAP vs REST API

While both allow communication between systems, there are some key differences between SOAP and REST APIs:

Basis SOAP REST
Protocol SOAP – Simple Object Access Protocol REST can use HTTP, FTP etc. but most implementations use HTTP
Architecture More strict WS-* standards Architectural style
Data Format XML Agnostic – JSON, XML etc.
Caching Not built-in. Must be implemented explicitly REST mandates caching response
Contract and Data Model Strict contract. Required WSDL file mapping all services Loose coupling. No fixed contract
Security Built-in WS-Security Stateless so no security by default. Has to be implemented through API keys, OAuth etc.
Performance SOAP has significant processing overhead reducing performance Better performance and scalability
Usage Mainly for enterprise systems and wireless services needing formal contracts and security Preferred for internet based services, web APIs, mobile applications needing scalability and interoperability

What tools can you use to test REST APIs?

Some popular tools used for testing REST APIs are:

  • Postman – GUI based API testing tool with collection runners.
  • cURL – Make HTTP requests from command line or terminals.
  • SoapUI – Testing and mocking framework for SOAP and REST APIs.
  • JMeter – Load and performance testing for REST APIs.
  • Rest Assured – Java DSL for simpler REST testing.
  • Fiddler – Web debugging proxy to analyze traffic.

How can you secure your REST API?

Some ways to secure a production-grade REST API are:

  • HTTPS – Secure communication channel over SSL/TLS.
  • API Keys – Pass API keys with each request to authenticate clients.
  • OAuth 2.0 – Delegate authentication using industry standard protocols.
  • Rate Limiting – Limit number of requests per client to prevent abuse.
  • Input Validation – Validate all input data to prevent common attacks.

You should also implement access control checks in code to restrict data access as per user roles.

What are common issues faced with REST APIs?

Some common issues seen with REST APIs are:

  • Over fetching and under fetching of data leading to inefficient use of APIs.
  • Lack of documentation around endpoints and expected parameters.
  • No hypermedia links for discoverability.
  • No built-in security requiring extra implementation.
  • Multiple API versions getting created leading to maintenance issues.
  • Fragile interfaces that break with new releases.
  • No built-in monitoring leading to production issues going undetected.

What are HATEOAS and Hypermedia?

HATEOAS stands for Hypermedia as the Engine of Application State. It is a principle to help API clients interact dynamically by serving hypermedia links on each response. This decouples client and servers allowing them to evolve independently.

For example, a GET request returning a book item can contain links for all valid actions like edit, delete in the response. The client just needs to look for the links instead of hardcoding endpoints.

What are the typical status codes returned for REST APIs?

These are some typical status code ranges seen in REST API responses:

  • 200 – Successful GET, PUT, PATCH or DELETE.
  • 201 – Successful resource creation with POST.
  • 204 – Successful operation with no content returned.
  • 400 – Invalid client request, missing required parameters.
  • 401 – Unauthorized due to invalid authentication.
  • 403 – Forbidden due to lack of permissions.
  • 404 – Not found – incorrect URL or resource removed.
  • 500 – Server errors.

What are the best practices for error handling in REST API?

Best practices for error reporting in REST APIs:

  • Use proper HTTP status codes to broadly categorize the error semantic e.g 404 for not found.
  • Include error details in response body instead of just an error code.
  • Provide links or URI to documentation to resolve issues faster.
  • Follow a consistent error response structure using error codes.
  • Do not expose sensitive implementation details in production.
  • Handle generic 500 errors and log exceptions for diagnostics.
  • Set useful CORS headers to enable browser apps to read API error responses.

How can you implement versioning for a REST API?

Some REST API versioning strategies are:

  1. URI Versioning – Include versions in path like v1/food/dishes
  2. Request Parameter Versioning – Pass API version as query string or header parameter.
  3. Content Negotiation – Set version in Accept header and server responds with right version.
  4. Custom Request Header Versioning – Custom headers to pass version.

Ideally versions should not break backwards compatibility else can lead to integration issues for clients.

Explain Richardson Maturity Model.

Leonard Richardson proposed Richardson Maturity Model that breaks down REST API into three steps:

  1. Level 0 – Expose SOAP web services over HTTP protocol using methods like POST passing XML messages.
  2. Level 1 – Expose dedicated resources with proper URIs, however using single HTTP verb like POST for all operations.
  3. Level 2 – Level 1 + Use proper HTTP verbs like GET, POST, PUT and DELETE representing respective CRUD operation.
  4. Level 3 – HATEOAS – Level 2 + include hypermedia controls in responses for self-documenting and discoverability.

Most modern REST APIs try to remain at Level 2 or 3 for best practices.

How can you implement caching in REST API?

Caching helps reduce network calls and improves performance by reusing cached data. Below are some ways caching can be implemented for REST APIs:

  • Set cache control headers like max-age, no-cache, no-store etc.
  • Explicitly state when responses can be cached or not.
  • Cache data on client as well as server side caches like Redis.
  • Use hashes of request parameters appended with resource URIs as cache keys.
  • Notify cache invalidation events on data changes for freshness.

Compare RPC and REST APIs

Basis RPC REST
Design Style Calling style – exposes actions and methods to call Data style – Exposes data as resources over HTTP
Focus Actions Data
Protocol Multiple like JSON-RPC, XML-RPC, SOAP, HTTP etc REST mandates HTTP
Data Format Protocol specific like JSON for JSON-RPC Agnostic – JSON, XML, Text etc
Granularity Single endpoint can perform complex operations Each endpoint has single responsibility, compose endpoints to achieve complex logic
Scale RPC APIs are often designed for internal microservices rather than externals REST APIs better suited for building scalable externally facing APIs

We covered the most frequently asked REST interview questions. I hope this comprehensive guide helps you prepare for your next technical discussion. Let me know in the comments about any other good questions worth including. Cheers!