Top 30 REST API Interview Questions 2023

Welcome to our comprehensive guide on REST API interview questions.To help you prepare for REST API-related interviews, we have categorized the REST API interview questions into three levels: Beginners, Intermediate, and Advanced.

REST API Interview Questions

Beginners Level: REST API Interview Questions

In this section, we will cover basic REST API Interview Questions.

What do you mean by REST?

REST stands for Representational State Transfer. It is an architectural style for designing networked applications. In lay man terms REST means to “Transfer the representation of the State of the Resource from Server to Client

What do you mean by REST API ?

REST API (Representational State Transfer Application Programming Interface) is an implementation of the REST principles.

It is a specific implementation that allows systems to communicate over the internet using REST principles and HTTP methods, exchanging data in formats like JSON or XML.

REST is the architectural style, while a REST API is the concrete implementation that adheres to the REST principles.

What are the main components of a REST API?

The main components of a REST API are as follows:

  1. URI (Uniform Resource Identifier): It provides a unique identifier for each resource in the API.
  2. HTTP Methods: REST APIs use standard HTTP methods such as GET, POST, PUT, PATCH, and DELETE to perform operations on resources.
  3. Headers: HTTP headers provide additional information about the request or response.
  4. Request Body: The request body carries data for operations like creating or updating resources.
  5. Response Body: The response body contains the data or representation of the requested resource.

 What is a Resource in REST API?

In a REST API, a resource is a key concept that represents any entity or piece of information that can be accessed, manipulated, or interacted with. It can be a user, a product, a document, or any other logical or physical entity.

 What is a URI?

URI (Uniform Resource Identifier): It provides a unique identifier for each resource in the API. The URI is used to locate and access the resources.

Here is an example of a URI (Uniform Resource Identifier) in a RESTful API:

URI: https://api.example.com/users/123

In this example, the URI represents a resource related to users and identifies a specific user with the ID “123”. The URI structure typically consists of a base URL followed by a path that uniquely identifies the resource. It provides a way for clients to access and interact with specific resources in the API.

Which markup languages are used in REST APIs?

Markup languages used in REST APIs are XML (eXtensible Markup Language) and JSON (JavaScript Object Notation).

Which HTTP request methods are supported by REST?

REST supports several HTTP request methods, including:

  1. GET: Retrieves a representation of a resource or a collection of resources.
  2. POST: Creates a new resource or performs a specific action on a resource.
  3. PUT: Updates an existing resource with new data or replaces it entirely.
  4. DELETE: Removes a resource.
  5. PATCH: Partially updates a resource with new data.
  6. OPTIONS: Retrieves the allowed methods, headers, and capabilities of a resource.
  7. HEAD: Retrieves only the headers of a resource without fetching the response body.

What is the difference between PUT and POST?

The main difference between PUT and POST is that PUT is used to update an existing resource at a specific URI by replacing it with new data, while POST is used to create a new resource or perform an action on a resource without necessarily replacing it.

What is payload in REST API?

In REST API, the payload refers to the data that is transmitted in the body of an HTTP request or response. It carries the actual information being transferred between the client and server. The payload can be in various formats such as JSON, XML, or binary data.

Example

Here’s an example of a payload in a REST API is when creating a new user. Suppose you want to create a new user and send the user’s information to the server. The payload, in this case, would be a JSON object containing the user’s details, such as name, email, and password.

POST /api/users

Payload:
{
  "name": "John Doe",
  "email": "johndoe@example.com",
  "password": "secret123"
}

In this example, the payload carries the user’s information in JSON format, which will be processed by the server to create a new user entity in the system.

Which protocols are used by REST APIs?

REST APIs use the HTTP (Hypertext Transfer Protocol) and HTTPS (HTTP Secure) protocols for communication.

@Controller vs @RestController

Here’s a comparison between @Controller and @RestController:

@Controller@RestController
PurposeHandles web requests and returns views or HTML content.Handles web requests and returns data (usually JSON).
Response BodySupports returning views and HTML templates.Automatically serializes objects to JSON/XML.
@ResponseBodyRequired to annotate methods returning data.Not required, as it is implicitly applied.
ConvenienceRequires additional @ResponseBody for JSON responses.Saves effort, as methods return data as JSON by default.

REST vs SOAP

Here’s a comparison between REST and SOAP:

REST (Representational State Transfer)SOAP (Simple Object Access Protocol)
ArchitectureREST is an architectural style that uses standard HTTP methods and URIs.SOAP is a protocol that defines a set of rules for structuring messages.
CommunicationRESTful services communicate using lightweight formats like JSON or XML.SOAP services use XML for communication.
Data FormatREST supports various data formats like JSON, XML, HTML, and more.SOAP uses XML exclusively for data representation.
Message FormatREST uses plain text or binary messages without a strict structure.SOAP messages are structured with a specific envelope, header, and body.
TransportREST can use any transport protocol, but commonly uses HTTP(S).SOAP can use various protocols like HTTP, SMTP, or MQ.
Service DefinitionREST services are self-descriptive and don’t require a formal contract.SOAP services often require a Web Services Description Language (WSDL).
ScalabilityREST services are highly scalable due to their statelessness and simplicity.SOAP services are less scalable due to the additional overhead and complexity.
CompatibilityREST is compatible with a wide range of devices and platforms.SOAP is widely supported but may require specific tooling for integration.
Error HandlingREST typically uses HTTP status codes for error handling.SOAP has its own fault mechanism for error reporting and handling.
PerformanceREST is lightweight and generally performs better due to its simplicity.SOAP can have more overhead and may be slower due to XML parsing.

What do you mean by CRUD in context of REST API?

In the context of REST API, CRUD stands for Create, Read, Update, and Delete. It represents the four basic operations that can be performed on data in a persistent storage system.

  • Create: It refers to the operation of creating a new resource. In REST API, it is typically done by sending a POST request to the appropriate URI.
  • Read: It involves retrieving or reading the existing resource data. In REST API, it is accomplished by sending a GET request to the specific URI.
  • Update: It pertains to modifying or updating an existing resource. In REST API, it is done by sending a PUT or PATCH request to the URI of the resource.
  • Delete: It refers to removing or deleting a resource. In REST API, it is achieved by sending a DELETE request to the URI of the resource.

CRUD operations form the foundation of data manipulation in RESTful systems, allowing clients to create, retrieve, update, and delete resources using the standard HTTP methods in a consistent and uniform manner.

Intermediate Level: REST API Interview Questions

In this section, we will cover Intermediate level REST API Interview Questions.

What are the principles of REST?

The principles of REST define a set of guidelines and best practices for designing RESTful APIs. These principles include:

  1. Client-Server Architecture: The client and server are separate entities that communicate over a network. The client is responsible for the user interface, while the server handles the storage and processing of data.
  2. Statelessness: Each request from a client to a server must contain all the necessary information for the server to understand and process the request. The server does not maintain any client-specific state between requests.
  3. Uniform Interface: The API should have a uniform and consistent interface, including the use of standard HTTP methods (GET, POST, PUT, DELETE) for specific operations on resources, and a consistent naming convention for URIs.
  4. Resource Identification: Each resource should be uniquely identified using a URI (Uniform Resource Identifier). The URI provides a logical address for accessing and manipulating the resource.
  5. Representation: Resources are represented in different formats, such as JSON or XML. The client and server can negotiate the representation format based on the Accept header in the request and the available representations.
  6. Hypermedia as the Engine of Application State (HATEOAS): The API should include hyperlinks in the response, allowing clients to discover and navigate to related resources dynamically.

By following these principles, RESTful APIs can achieve scalability, simplicity, and interoperability, making it easier for clients to interact with and consume the API.

What are the best practices to develop REST API?

Here are some key best practices:

  1. Use meaningful and descriptive resource names.
  2. Use appropriate HTTP methods (GET, POST, PUT, DELETE) for operations.
  3. Design resource-oriented APIs following RESTful principles.
  4. Provide clear and meaningful HTTP status codes.
  5. Support content negotiation for flexible data formats.
  6. Implement proper error handling with informative error messages.
  7. Ensure API security with authentication and authorization.
  8. Version your API to accommodate future changes.
  9. Document your API comprehensively for developers.
  10. Test and validate your API thoroughly.

What are various application integration styles?

  1. Point-to-Point Integration: Direct integration between two applications, often with custom interfaces and protocols.
  2. Publish-Subscribe (Messaging) Integration: Applications communicate through an event-based system, where publishers send messages/events and subscribers receive them.
  3. Service-Oriented Architecture (SOA): Applications are designed as a collection of loosely coupled services that communicate with each other using standardized interfaces (e.g., SOAP, REST).
  4. Event-Driven Architecture: Applications communicate and react to events triggered by changes or actions in the system, allowing for loosely coupled and scalable architectures.
  5. Microservices Architecture: Applications are decomposed into small, independent services that can be developed, deployed, and scaled independently, communicating through lightweight protocols like REST.

Which HTTP methods are idempotent and why?

In the context of RESTful APIs, certain HTTP methods are considered idempotent, meaning that making multiple identical requests has the same effect as making a single request. The idempotent HTTP methods are:

  1. GET: Retrieving a resource multiple times does not modify the resource or have any side effects.
  2. PUT: Updating a resource with the same data multiple times will result in the same final state.
  3. DELETE: Deleting a resource multiple times will have the same outcome of the resource being deleted.

What are HTTP various status codes?

HTTP status codes are three-digit numbers returned by a server in response to an HTTP request. They provide information about the status of the request and the outcome of the server’s processing. Here are some commonly used HTTP status codes:

1xx (Informational):

  • 100 Continue: The server has received the initial part of the request and is waiting for the client to send the rest.
  • 101 Switching Protocols: The server agrees to switch protocols specified in the Upgrade header.

2xx (Success):

  • 200 OK: The request was successful, and the server has returned the requested data.
  • 201 Created: The request has been fulfilled, and a new resource has been created.
  • 204 No Content: The server has successfully processed the request, but there is no content to return.

3xx (Redirection):

  • 301 Moved Permanently: The requested resource has been permanently moved to a new location.
  • 302 Found: The requested resource has been temporarily moved to a different location.
  • 304 Not Modified: The client’s cached copy of the resource is still valid.

4xx (Client Errors):

  • 400 Bad Request: The server cannot understand the request due to invalid syntax or other client-side errors.
  • 404 Not Found: The requested resource could not be found on the server.
  • 401 Unauthorized: The client must authenticate itself to get the requested response.

5xx (Server Errors):

  • 500 Internal Server Error: The server encountered an unexpected condition that prevented it from fulfilling the request.
  • 503 Service Unavailable: The server is currently unavailable, often due to maintenance or overload.
  • 504 Gateway Timeout: The server acting as a gateway or proxy did not receive a timely response from an upstream server.

What are the main parts of a HTTP Request?

The main parts of an HTTP request are:

  1. Request Line: Specifies the HTTP method, URI, and protocol version. Example: GET /api/user/123 HTTP/1.1
  2. Request Headers: Provide additional information about the request. Example:
    • Host: api.example.com
    • User-Agent: Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/91.0.4472.124 Safari/537.36
    • Content-Type: application/json
    • Accept: application/json
  3. Request Body (Optional): Contains data sent by the client, usually for POST or PUT requests. For Example:
{
"name": "John Doe",
"email": "johndoe@example.com"
}

These parts together form an HTTP request, which is sent from the client to the server to initiate a specific action or retrieve a resource.

What are the main parts of a HTTP Response?

The main parts of an HTTP response are:

  1. Status Line: Specifies the HTTP version, status code, and reason phrase. Example: HTTP/1.1 200 OK
  2. Response Headers: Provide additional information about the response. Example:
    • Content-Type: application/json
    • Content-Length: 1024
    • Cache-Control: no-cache
  3. Response Body: Contains the data or content sent by the server. For Example:
{
"id": 123,
"name": "John Doe",
"email": "johndoe@example.com"
}

These components make up an HTTP response, which is sent from the server to the client in response to an HTTP request.

How does the HEAD method in REST APIs differ from other methods like GET?

The HEAD method in REST APIs performs a similar function to the GET method but retrieves only the response headers, without retrieving the actual content of the resource.

Here’s an example of a HEAD request using cURL:

curl -I -X HEAD https://api.example.com/api/user/profile

Sample Response:

HTTP/1.1 200 OK
Content-Type: application/json
Content-Length: 256
Last-Modified: Mon, 12 Jul 2023 15:30:00 GMT
ETag: "e8e8a6f9d4a5ca6f8b19d8ac"

In this example, the response status code is 200 OK, indicating that the request was successful. The response headers provide metadata about the resource, such as the Content-Type, which indicates that the content is in JSON format. The Content-Length specifies the size of the resource in bytes. The Last-Modified header indicates the date and time when the resource was last modified. The ETag header provides an identifier that represents the current state or version of the resource.

AJAX vs REST

Here’s a comparison between AJAX and REST:

AJAXREST
PurposeEnables asynchronous data retrieval and updates within a web pageProvides guidelines for designing scalable and interoperable APIs
FunctionalityMakes asynchronous requests and updates specific parts of a web pageDefines principles for accessing and manipulating resources over the web
ScopeClient-sideServer-side
TechnologyPrimarily based on JavaScriptLanguage-agnostic, can be implemented in various programming languages
Data ExchangeOften uses XML or JSONCan use various data formats, including JSON and XML

 List out some tools testing REST APIs?

There are several tools available for testing REST APIs that offer various features and capabilities. Here are some popular tools for testing REST APIs:

  1. Postman: A widely-used and feature-rich API testing tool that allows you to create and send HTTP requests, analyze responses, write tests, and generate documentation.
  2. Insomnia: Similar to Postman, Insomnia provides a user-friendly interface for testing REST APIs. It supports creating requests, organizing workspaces, and managing environments.
  3. cURL: A command-line tool for making HTTP requests, cURL is widely available on various platforms. It allows for testing REST APIs by specifying request headers, parameters, and payload directly in the command line.
  4. REST Assured: A Java-based library that provides a domain-specific language (DSL) for testing REST APIs. It integrates with popular Java testing frameworks and offers features like request specification, response validation, and authentication support.
  5. SoapUI: Originally designed for testing SOAP web services, SoapUI also supports testing RESTful APIs. It allows for creating test cases, managing assertions, and generating reports.
  6. JMeter: Primarily used for load testing, Apache JMeter can also be utilized for functional testing of REST APIs. It offers features for simulating concurrent requests, measuring response times, and analyzing server performance.
  7. Newman: A command-line tool that works alongside Postman collections, Newman allows for running and automating Postman tests in a CI/CD environment.
  8. RestSharp: A popular .NET library for testing REST APIs in C#. It simplifies the process of making HTTP requests, handling responses, and performing assertions.
  9. Karate: A Java-based open-source tool for testing REST APIs with built-in support for testing JSON and XML payloads. Karate offers a simple syntax and integrates with popular testing frameworks.
  10. HTTPie: A command-line tool similar to cURL but with a more user-friendly interface. It allows for making HTTP requests, handling headers, and examining responses.

JAX-WS vs JAX-RS

Here’s a comparison between JAX-WS (Java API for XML Web Services) and JAX-RS (Java API for RESTful Web Services):

JAX-WSJAX-RS
PurposeEnables the creation and consumption of SOAP-based web services using XMLFacilitates the development and consumption of RESTful web services
ProtocolPrimarily based on SOAP (Simple Object Access Protocol)Primarily based on HTTP and follows REST architectural principles
ArchitectureFollows a contract-first approach and is typically used for enterprise-level web services with complex requirementsEmbraces a resource-oriented approach and is well-suited for building lightweight, scalable web services
DevelopmentRequires the creation of WSDL (Web Services Description Language) contract for defining web service operations, data types, and communication protocolsDoes not require a separate contract definition. Developers can directly annotate Java classes and methods to define RESTful endpoints and their behavior
CommunicationSupports messaging patterns like RPC-style and document-style for exchanging data between servicesEmphasizes the use of HTTP methods like GET, POST, PUT, and DELETE to perform CRUD operations on resources
Data FormatSupports XML-based data formats like SOAP and XML-RPCProvides flexibility in data formats, with support for JSON, XML, and others
Java StandardIncluded as part of Java EE (Enterprise Edition)Included as part of Java EE and also available as a standalone specification called JAX-RS
Common ImplementationJAX-WS implementation is commonly associated with Java EE application servers like Apache Axis, Apache CXF, and Oracle WebLogicJAX-RS implementations include Jersey, Apache CXF, and RESTEasy

Advanced Level : REST API Interview Questions

In this section, we will cover advanced level REST API Interview Questions.

What is Cache-Control response header?

The Cache-Control response header is an HTTP header that allows a server to provide caching instructions to the client and intermediary caches. It specifies various directives that control how the response should be cached, stored, and used.

Some commonly used directives include:

  • public: Indicates that the response can be cached by any cache.
  • private: Specifies that the response is intended for a specific user and should not be cached by shared caches.
  • max-age=<seconds>: Sets the maximum time in seconds that the response can be cached.
  • no-cache: Requires caches to revalidate the response with the server before using a cached copy.
  • no-store: Instructs caches not to store a cached copy of the response.

Example usage of Cache-Control header:

Cache-Control: public, max-age=3600

In this example, the response is marked as public and can be cached by any cache, and the maximum age of the cache is set to 3600 seconds (1 hour).

Regarding caching of HTTP methods, by default, only safe methods like GET and HEAD are considered cacheable. However, with appropriate caching directives (e.g., Cache-Control), other methods like POST or PUT can also be cached under certain conditions. It depends on how the server and caching infrastructure handle those methods and their associated data.

Can you explain the principle of statelessness in REST APIs?

Statelessness in REST APIs means that the server does not store any client-specific information or session state. Each request from the client must contain all the necessary data for the server to process it.

Advantages of statelessness in REST APIs include simplified server implementation, improved scalability, enhanced reliability, efficient caching, better interoperability, and clear client-server separation.

Authentication tokens and hypermedia links are often used to maintain statelessness in REST APIs.

How do you secure the REST APIs?

To secure REST APIs, follow these key practices:

  1. Authentication: Use mechanisms like API keys, JWT, or OAuth to verify client identity.
  2. Authorization: Implement role-based access control to determine client privileges.
  3. HTTPS: Encrypt communication with clients using HTTPS.
  4. Input Validation: Validate and sanitize input data to prevent security vulnerabilities.
  5. Secure Credential Storage: Store passwords and sensitive information securely.
  6. Rate Limiting: Set limits on requests to prevent abuse or unauthorized access.
  7. Logging and Monitoring: Monitor and log activities for security analysis.
  8. API Versioning: Manage versions to avoid outdated and vulnerable APIs.
  9. Security Testing: Regularly test and assess for vulnerabilities and weaknesses.

What are the best practices for naming the URIs?

Here are some recommended best practices for naming URIs:

  1. Use Nouns to Represent Resources: URIs should generally be named after the resources they represent. Use nouns in the URI path to clearly identify the specific resource being accessed or manipulated. For example:
    • Good: /users, /products, /orders
    • Avoid: /getUserData, /createNewProduct
  2. Use Plural Nouns for Collections: When representing a collection of resources, use plural nouns in the URI path. This helps indicate that the URI refers to multiple instances of a resource. For example:
    • Good: /users, /products
    • Avoid: /user, /productList
  3. Use Specific Names for Resource Instances: When referring to a specific instance of a resource, use a unique identifier in the URI path. This could be an ID, a slug, or any other appropriate identifier. For example:
    • Good: /users/{userId}, /products/{productId}
    • Avoid: /users/getUserById/{userId}, /products/{productName}
  4. Keep URIs Short and Readable: URIs should be concise and readable to enhance understandability and ease of use. Avoid long and overly complex URIs that may be difficult to comprehend or remember.
  5. Use Hyphen or Underscore as Word Separators: When using multiple words in a URI, you can separate them using hyphens or underscores for improved readability. Choose one consistent approach and stick to it throughout your URIs. For example:
    • /product-reviews/{reviewId}
    • /product_reviews/{reviewId}
  6. Avoid Including Action Verbs: URIs should focus on identifying resources, not actions. Avoid using action verbs in URIs, as actions can be conveyed through the appropriate HTTP methods. For example:
    • Good: /orders/{orderId}/cancel
    • Avoid: /cancelOrder/{orderId}
  7. Use Hierarchy for Related Resources: If resources have a hierarchical relationship, represent it in the URI structure. For example:
    • /categories/{categoryId}/products
  8. Use Versioning in the URI: If you need to introduce versioning in your API, include it in the URI path to differentiate between different versions of the API. For example:
    • /v1/users, /v2/users

What is the purpose of the ETag header in REST?

The ETag header in REST serves the purpose of enabling caching and supporting conditional requests. It provides a unique identifier for a specific version of a resource, allowing clients to make efficient use of caching and perform conditional operations based on the resource’s ETag value.

Here’s a example of how the ETag header can be used:

Suppose we have a REST API endpoint for retrieving a product’s information at /api/product/{productId}. When a client makes a GET request to this endpoint, the server includes the ETag header in the response.

Response headers:

HTTP/1.1 200 OK
Content-Type: application/json
ETag: "abcd1234"

In subsequent requests, the client can include the ETag value received in the If-None-Match header to check if the resource has been modified since the last request:

Request:

GET /api/product/{productId}
If-None-Match: "abcd1234"

If the resource hasn’t changed (as indicated by the matching ETag value), the server responds with a “304 Not Modified” status code, indicating that the client’s cached version of the resource is still valid.

Response:

HTTP/1.1 304 Not Modified

This allows the client to avoid unnecessary data transfer and use the cached representation of the resource, improving performance.

What is the use of the OPTIONS method in REST?

It is used to retrieve the communication options available for a target resource. It provides information about the allowed methods, headers, and other capabilities of the resource.

The main uses of the OPTIONS method in REST are:

  • The OPTIONS method in REST is used to retrieve the communication options available for a target resource.
  • It provides information about the allowed methods, headers, and other capabilities of the resource.
  • It helps clients understand which operations they can perform on the resource without making unnecessary requests.
  • It is commonly used in CORS to determine whether a cross-origin request is allowed.
  • The server can include additional information about its capabilities or supported features in the OPTIONS response.
  • It can be used for API discovery by providing metadata or documentation links in the response headers or body.
  • Not all resources may support the OPTIONS method, and its implementation depends on the server and application configuration.

How do you handle versioning in REST APIs?

There are several approaches to handle versioning in REST APIs:

  1. URI Versioning: In this approach, the version number is included in the URI path. For example:
    • /api/v1/users
    • /api/v2/users
  2. Query Parameter Versioning: In this approach, the version number is included as a query parameter in the API request. For example:
    • /api/users?version=1
    • /api/users?version=2
  3. Header Versioning: In this approach, the version number is specified in a custom header of the API request. For example:
    • GET /api/users
    • Version: 1
  4. Content Negotiation Versioning: In this approach, the version is negotiated based on the requested content type in the API request, typically using the Accept header. Different versions are represented by different content types.
    • GET /api/users
    • Accept: application/vnd.myapi.v1+json

What is HATEOAS concept in REST API ?

HATEOAS, which stands for “Hypermedia as the Engine of Application State” promotes a self-descriptive and discoverable design for web services.

HATEOAS suggests that a client interacting with a REST API should be able to navigate the available functionality entirely through hypermedia links dynamically provided in the API responses. In other words, the API should not only return the requested data but also include links to related resources and actions that the client can perform next.

Here’s an example to illustrate the concept:

GET /api/users/123

Response:
{
    "id": 123,
    "name": "John Doe",
    "links": [
        {
            "rel": "self",
            "href": "/api/users/123"
        },
        {
            "rel": "orders",
            "href": "/api/users/123/orders"
        },
        {
            "rel": "update",
            "href": "/api/users/123",
            "method": "PUT"
        },
        {
            "rel": "delete",
            "href": "/api/users/123",
            "method": "DELETE"
        }
    ]
}

In this example, the API response includes hypermedia links that describe the available actions for the user resource. The client can use the “orders” link to retrieve the user’s orders, the “update” link to update the user’s details, and the “delete” link to remove the user from the system. The links provide a level of discoverability and guide the client’s interaction with the API.

Conclusion

In conclusion, the “REST API interview questions” guide provides a comprehensive resource for individuals preparing for interviews related to REST API development.

By studying and practicing these interview questions, you can gain a deep understanding of REST API concepts, design principles, and best practices. I

Leave a Reply

Your email address will not be published. Required fields are marked *