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.
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:
- URI (Uniform Resource Identifier): It provides a unique identifier for each resource in the API.
- HTTP Methods: REST APIs use standard HTTP methods such as GET, POST, PUT, PATCH, and DELETE to perform operations on resources.
- Headers: HTTP headers provide additional information about the request or response.
- Request Body: The request body carries data for operations like creating or updating resources.
- 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:
- GET: Retrieves a representation of a resource or a collection of resources.
- POST: Creates a new resource or performs a specific action on a resource.
- PUT: Updates an existing resource with new data or replaces it entirely.
- DELETE: Removes a resource.
- PATCH: Partially updates a resource with new data.
- OPTIONS: Retrieves the allowed methods, headers, and capabilities of a resource.
- 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 | |
---|---|---|
Purpose | Handles web requests and returns views or HTML content. | Handles web requests and returns data (usually JSON). |
Response Body | Supports returning views and HTML templates. | Automatically serializes objects to JSON/XML. |
@ResponseBody | Required to annotate methods returning data. | Not required, as it is implicitly applied. |
Convenience | Requires 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) | |
---|---|---|
Architecture | REST is an architectural style that uses standard HTTP methods and URIs. | SOAP is a protocol that defines a set of rules for structuring messages. |
Communication | RESTful services communicate using lightweight formats like JSON or XML. | SOAP services use XML for communication. |
Data Format | REST supports various data formats like JSON, XML, HTML, and more. | SOAP uses XML exclusively for data representation. |
Message Format | REST uses plain text or binary messages without a strict structure. | SOAP messages are structured with a specific envelope, header, and body. |
Transport | REST can use any transport protocol, but commonly uses HTTP(S). | SOAP can use various protocols like HTTP, SMTP, or MQ. |
Service Definition | REST services are self-descriptive and don’t require a formal contract. | SOAP services often require a Web Services Description Language (WSDL). |
Scalability | REST services are highly scalable due to their statelessness and simplicity. | SOAP services are less scalable due to the additional overhead and complexity. |
Compatibility | REST is compatible with a wide range of devices and platforms. | SOAP is widely supported but may require specific tooling for integration. |
Error Handling | REST typically uses HTTP status codes for error handling. | SOAP has its own fault mechanism for error reporting and handling. |
Performance | REST 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:
- 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.
- 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.
- 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.
- 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.
- 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. - 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:
- Use meaningful and descriptive resource names.
- Use appropriate HTTP methods (GET, POST, PUT, DELETE) for operations.
- Design resource-oriented APIs following RESTful principles.
- Provide clear and meaningful HTTP status codes.
- Support content negotiation for flexible data formats.
- Implement proper error handling with informative error messages.
- Ensure API security with authentication and authorization.
- Version your API to accommodate future changes.
- Document your API comprehensively for developers.
- Test and validate your API thoroughly.
What are various application integration styles?
- Point-to-Point Integration: Direct integration between two applications, often with custom interfaces and protocols.
- Publish-Subscribe (Messaging) Integration: Applications communicate through an event-based system, where publishers send messages/events and subscribers receive them.
- 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).
- Event-Driven Architecture: Applications communicate and react to events triggered by changes or actions in the system, allowing for loosely coupled and scalable architectures.
- 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:
- GET: Retrieving a resource multiple times does not modify the resource or have any side effects.
- PUT: Updating a resource with the same data multiple times will result in the same final state.
- 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:
- Request Line: Specifies the HTTP method, URI, and protocol version. Example: GET /api/user/123 HTTP/1.1
- 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
- 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:
- Status Line: Specifies the HTTP version, status code, and reason phrase. Example: HTTP/1.1 200 OK
- Response Headers: Provide additional information about the response. Example:
- Content-Type: application/json
- Content-Length: 1024
- Cache-Control: no-cache
- 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:
AJAX | REST | |
---|---|---|
Purpose | Enables asynchronous data retrieval and updates within a web page | Provides guidelines for designing scalable and interoperable APIs |
Functionality | Makes asynchronous requests and updates specific parts of a web page | Defines principles for accessing and manipulating resources over the web |
Scope | Client-side | Server-side |
Technology | Primarily based on JavaScript | Language-agnostic, can be implemented in various programming languages |
Data Exchange | Often uses XML or JSON | Can 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:
- 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.
- Insomnia: Similar to Postman, Insomnia provides a user-friendly interface for testing REST APIs. It supports creating requests, organizing workspaces, and managing environments.
- 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.
- 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.
- 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.
- 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.
- Newman: A command-line tool that works alongside Postman collections, Newman allows for running and automating Postman tests in a CI/CD environment.
- RestSharp: A popular .NET library for testing REST APIs in C#. It simplifies the process of making HTTP requests, handling responses, and performing assertions.
- 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.
- 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-WS | JAX-RS | |
---|---|---|
Purpose | Enables the creation and consumption of SOAP-based web services using XML | Facilitates the development and consumption of RESTful web services |
Protocol | Primarily based on SOAP (Simple Object Access Protocol) | Primarily based on HTTP and follows REST architectural principles |
Architecture | Follows a contract-first approach and is typically used for enterprise-level web services with complex requirements | Embraces a resource-oriented approach and is well-suited for building lightweight, scalable web services |
Development | Requires the creation of WSDL (Web Services Description Language) contract for defining web service operations, data types, and communication protocols | Does not require a separate contract definition. Developers can directly annotate Java classes and methods to define RESTful endpoints and their behavior |
Communication | Supports messaging patterns like RPC-style and document-style for exchanging data between services | Emphasizes the use of HTTP methods like GET, POST, PUT, and DELETE to perform CRUD operations on resources |
Data Format | Supports XML-based data formats like SOAP and XML-RPC | Provides flexibility in data formats, with support for JSON, XML, and others |
Java Standard | Included as part of Java EE (Enterprise Edition) | Included as part of Java EE and also available as a standalone specification called JAX-RS |
Common Implementation | JAX-WS implementation is commonly associated with Java EE application servers like Apache Axis, Apache CXF, and Oracle WebLogic | JAX-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:
- Authentication: Use mechanisms like API keys, JWT, or OAuth to verify client identity.
- Authorization: Implement role-based access control to determine client privileges.
- HTTPS: Encrypt communication with clients using HTTPS.
- Input Validation: Validate and sanitize input data to prevent security vulnerabilities.
- Secure Credential Storage: Store passwords and sensitive information securely.
- Rate Limiting: Set limits on requests to prevent abuse or unauthorized access.
- Logging and Monitoring: Monitor and log activities for security analysis.
- API Versioning: Manage versions to avoid outdated and vulnerable APIs.
- 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:
- 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
- Good:
- 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
- Good:
- 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}
- Good:
- 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.
- 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}
- 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}
- Good:
- Use Hierarchy for Related Resources: If resources have a hierarchical relationship, represent it in the URI structure. For example:
/categories/{categoryId}/products
- 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:
- URI Versioning: In this approach, the version number is included in the URI path. For example:
/api/v1/users
/api/v2/users
- 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
- 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
- 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