Most Frequently asked rest Interview Questions and Answers
Question: What is the difference between GET, POST, PUT, and DELETE in REST?
Answer:
In RESTful services, the HTTP methods GET, POST, PUT, and DELETE are used to perform various operations on resources, corresponding to the basic CRUD (Create, Read, Update, Delete) operations. Each method serves a specific purpose, and understanding the differences is crucial for designing and interacting with RESTful APIs.
Here’s a breakdown of each method:
1. GET
- Purpose: Retrieve data from the server (i.e., read a resource).
- Action: Fetch the current state of the resource identified by the URI. It does not modify the resource.
- Idempotent: Yes. Multiple identical GET requests will always return the same result, assuming the resource does not change.
- Safe: Yes. GET is a read-only operation and does not have any side effects on the resource.
- Use Case: When you want to read or fetch data, such as retrieving a user’s profile, a product list, or a post.
- Example:
Retrieves the details of the user with IDGET /users/123
123
.
2. POST
- Purpose: Create a new resource or submit data to the server.
- Action: Send data to the server, which typically results in the creation of a new resource or a processing task. POST can also be used for actions other than resource creation (e.g., form submissions).
- Idempotent: No. Multiple identical POST requests can result in different outcomes, such as creating multiple resources.
- Safe: No. POST can change the state of the server (e.g., by creating a resource).
- Use Case: When you want to create a new resource or trigger an action (e.g., creating a new user or submitting a form).
- Example:
Creates a new user based on the data provided in the request body.POST /users
3. PUT
- Purpose: Update or replace an existing resource.
- Action: Replace the entire resource with the data provided in the request body. If the resource does not exist, PUT can create it (depending on the implementation).
- Idempotent: Yes. Repeated PUT requests with the same data will have the same result (i.e., the resource is replaced with the same state).
- Safe: No. PUT modifies the resource, either by updating it or creating it if it does not exist.
- Use Case: When you want to update a resource or replace it entirely (e.g., updating a user’s details).
- Example:
Updates the user with IDPUT /users/123
123
with the data provided in the request body. If the user does not exist, a new user is created (depending on the implementation).
4. DELETE
- Purpose: Remove a resource from the server.
- Action: Delete the resource identified by the URI.
- Idempotent: Yes. Once a resource is deleted, subsequent DELETE requests will not change anything, as the resource no longer exists.
- Safe: No. DELETE modifies the state of the server by removing a resource.
- Use Case: When you want to delete a resource, such as removing a user, post, or product.
- Example:
Deletes the user with IDDELETE /users/123
123
from the server.
Summary of Differences:
HTTP Method | Action | CRUD Operation | Idempotent | Safe | Use Case |
---|---|---|---|---|---|
GET | Retrieve | Read | Yes | Yes | Fetching resource data (e.g., getting user details). |
POST | Create | Create | No | No | Creating a new resource (e.g., submitting a form). |
PUT | Update/Replace | Update | Yes | No | Updating an existing resource (e.g., updating user info). |
DELETE | Remove | Delete | Yes | No | Removing a resource (e.g., deleting a user). |
Key Takeaways:
- GET: Used for reading or fetching a resource without making any changes.
- POST: Used for creating a new resource or submitting data to the server.
- PUT: Used for updating an existing resource or replacing it entirely.
- DELETE: Used for removing a resource.
Understanding the differences between these methods allows for clear and effective communication with RESTful APIs and ensures that the correct HTTP method is used for each operation.
Question: How do you design a REST API?
Answer:
Designing a REST API involves creating a system that is scalable, easy to use, and aligned with best practices in software development. The goal is to ensure that your API is intuitive, efficient, and can handle the necessary operations while adhering to the principles of REST architecture.
Here’s a step-by-step guide to designing a REST API:
1. Identify Resources
- Resources are the key elements in your API. Each resource represents a distinct entity in your system (e.g., a user, product, order, etc.).
- Resources are typically nouns and should be clearly defined in the API. Think of resources as objects or data entities your API will manage.
- Example:
/users
: Represents the collection of users./products
: Represents the collection of products.
2. Define the URIs (Uniform Resource Identifiers)
- In REST, every resource must have a URI. The URI should be intuitive and descriptive of the resource it represents.
- Use plural nouns for collections of resources and singular nouns for individual resources.
- Example:
/users
for the collection of users./users/{id}
for an individual user with a specific ID./products/{id}
for an individual product.
3. Use the Correct HTTP Methods
- Use standard HTTP methods to operate on resources:
- GET: To retrieve a resource.
- POST: To create a new resource.
- PUT: To update an existing resource.
- DELETE: To delete a resource.
- These methods should map directly to CRUD operations (Create, Read, Update, Delete).
- Example:
GET /users/{id}
: Retrieve a specific user by ID.POST /users
: Create a new user.PUT /users/{id}
: Update an existing user.DELETE /users/{id}
: Delete a user.
4. Determine the Request and Response Format
- Use JSON as the standard format for request and response bodies, as it is widely adopted and easy to work with.
- The response should include the resource data, and possibly metadata (e.g., pagination info, status codes).
- Example:
- Request:
{ "name": "John Doe", "email": "[email protected]" }
- Response (on success):
{ "id": 123, "name": "John Doe", "email": "[email protected]" }
- Request:
5. Use HTTP Status Codes Properly
- Use appropriate HTTP status codes to convey the result of the API call:
- 2xx: Successful responses (e.g., 200 OK, 201 Created).
- 4xx: Client errors (e.g., 400 Bad Request, 404 Not Found).
- 5xx: Server errors (e.g., 500 Internal Server Error).
- Example:
201 Created
: When a new resource is successfully created.400 Bad Request
: When the request is malformed or missing required data.404 Not Found
: When the requested resource does not exist.
6. Support Filtering, Pagination, and Sorting
- Filtering: Allow clients to filter resources based on query parameters. For example, retrieving users by a specific status.
- Example:
GET /users?status=active
- Example:
- Pagination: To prevent overloading the client or server with too much data, return results in pages with limits and offsets.
- Example:
GET /users?page=2&limit=50
- Example:
- Sorting: Allow clients to sort the results based on one or more fields.
- Example:
GET /users?sort=name&order=asc
- Example:
7. Version Your API
- As APIs evolve, it’s important to provide versioning to ensure backward compatibility.
- Use the version in the URL or in the headers.
- Example:
/v1/users
/api/v2/products
Versioning strategies:
- URL Versioning:
/v1/products
- Header Versioning: Using
Accept
headers likeapplication/vnd.myapi.v1+json
.
8. Handle Errors Gracefully
- Your API should return clear and consistent error messages. Provide detailed information in the response body.
- Use appropriate HTTP status codes and include a description of the error.
- Example:
{ "error": "User not found", "message": "The user with ID 123 does not exist.", "status": 404 }
9. Implement Authentication and Authorization
- Secure your API by using proper authentication and authorization mechanisms.
- Authentication: Ensure that the user is who they say they are (e.g., using OAuth, JWT tokens, or API keys).
- Authorization: Ensure that the authenticated user has permission to access the resource (e.g., role-based access control).
- Example: Use Bearer tokens in the request header for authentication:
Authorization: Bearer {token}
10. Use HATEOAS (Hypermedia as the Engine of Application State)
- HATEOAS is a REST constraint where the response includes links to related resources or actions the client can take.
- This allows clients to navigate the API dynamically based on the response data, without needing to hardcode URIs.
- Example:
{ "id": 123, "name": "John Doe", "links": [ { "rel": "self", "href": "/users/123" }, { "rel": "friends", "href": "/users/123/friends" } ] }
11. Document the API
- Good documentation is essential for developers who will use your API. Use tools like Swagger or OpenAPI to create interactive and comprehensive API documentation.
- Include details on how to authenticate, the available resources, how to interact with them, and what responses to expect.
12. Consider Caching
- Use HTTP caching headers like
Cache-Control
to optimize performance and reduce load on your servers. - When data doesn’t change frequently, set appropriate cache expiration times to allow clients to reuse data.
Example REST API Design:
Let’s design a simple REST API for managing users:
-
Resources:
- Users:
/users
- Single User:
/users/{id}
- Users:
-
Operations:
GET /users
: Retrieve a list of all users.POST /users
: Create a new user.GET /users/{id}
: Retrieve a specific user by ID.PUT /users/{id}
: Update a user by ID.DELETE /users/{id}
: Delete a user by ID.
-
Example Request and Response:
- Create a new user:
- Request:
POST /users { "name": "Jane Doe", "email": "[email protected]" }
- Response:
{ "id": 1, "name": "Jane Doe", "email": "[email protected]" }
- Request:
- Create a new user:
-
Get a user:
- Request:
GET /users/1
- Response:
{ "id": 1, "name": "Jane Doe", "email": "[email protected]" }
- Request:
Conclusion:
Designing a REST API requires careful planning to ensure the system is intuitive, scalable, and easy to maintain. By following best practices such as using clear resource URIs, appropriate HTTP methods, versioning, and ensuring proper error handling, you can create an API that is both powerful and user-friendly.
Question: What are RESTful resources and how are they represented in a URL?
Answer:
In the context of REST (Representational State Transfer), resources are the key elements that the API interacts with. A resource represents an entity or object in the system, and can be a physical object, a concept, or even a collection of data. Each resource is identified by a unique URL (Uniform Resource Locator), which allows clients to interact with it.
1. What Are RESTful Resources?
-
A RESTful resource refers to any object or data entity that the API can access, manage, or manipulate. These resources could be:
- Entities: Like users, products, or orders.
- Collections: Groups of entities, like a list of all users or all products.
- Services: Specific actions or processes that the server can perform.
-
Resources are noun-based, meaning they usually represent entities or collections of data rather than actions (which are typically represented by HTTP methods like GET, POST, PUT, DELETE).
-
Examples of resources:
- A User resource might represent an individual user in a system.
- A Product resource could represent an individual product in an e-commerce store.
- A Order resource might represent a purchase made by a customer.
2. How Are RESTful Resources Represented in a URL?
In RESTful APIs, resources are represented by URLs (Uniform Resource Locators). These URLs serve as unique identifiers for the resources, allowing clients to access and manipulate them through standard HTTP methods.
The structure of a RESTful resource URL typically follows a hierarchical pattern that is easy to understand and use.
Common Structure of RESTful URLs:
/<resource>/{id}
/
- Indicates the root endpoint of the API.<resource>
- The type of resource, often a plural noun that represents a collection of entities.{id}
- The unique identifier of a specific resource within that collection, represented as a variable part of the URL (typically an integer or string).
Examples of RESTful resource URLs:
/users
- Represents the collection of all users./users/{id}
- Represents an individual user with a unique ID (e.g.,/users/123
for a user with ID 123)./products
- Represents the collection of all products./products/{id}
- Represents an individual product with a unique ID (e.g.,/products/456
for a product with ID 456)./orders
- Represents the collection of all orders./orders/{id}
- Represents an individual order with a unique ID (e.g.,/orders/789
for an order with ID 789).
More Examples:
- GET /users: Retrieves a list of all users.
- GET /users/123: Retrieves the details of the user with ID 123.
- POST /users: Creates a new user.
- PUT /users/123: Updates the details of the user with ID 123.
- DELETE /users/123: Deletes the user with ID 123.
3. Best Practices for RESTful Resource URL Design
To make your API intuitive and follow RESTful principles, consider the following best practices for designing resource URLs:
-
Use nouns: Resource URLs should reflect entities or concepts, so always use nouns (e.g.,
users
,products
,orders
) rather than verbs.- Good:
/users
,/products
,/orders
- Bad:
/getUsers
,/createProduct
- Good:
-
Use plural form for collections: Represent collections of resources with plural nouns, e.g.,
/users
instead of/user
.- Good:
/users
,/products
- Bad:
/user
,/product
- Good:
-
Use HTTP methods for actions: Actions like retrieving, creating, updating, and deleting are defined by HTTP methods (GET, POST, PUT, DELETE), not by the URL.
-
Use meaningful and predictable paths: URLs should be descriptive and self-explanatory, so users know what they represent and can navigate easily.
- Good:
/users/123/orders
(all orders for user 123) - Bad:
/getUserOrders?id=123
- Good:
-
Avoid using verbs in the URL: Instead of representing actions (e.g.,
/getUser
,/createOrder
), use HTTP methods to define actions (e.g.,GET /users
,POST /orders
). -
Use query parameters for filtering, pagination, and sorting: When you need to provide filtering, sorting, or pagination options for a resource collection, do so via query parameters.
- Example:
/users?status=active&age=25
: Fetch users who are active and 25 years old./products?page=2&limit=10
: Paginate products, fetching page 2 with 10 products per page./orders?sort=date&order=desc
: Sort orders by date in descending order.
- Example:
4. Hierarchical Representation of Resources
RESTful resource URLs often have a hierarchical structure that reflects the relationships between resources. This hierarchy allows you to represent sub-resources and nested relationships between entities.
Examples of hierarchical resource representations:
- GET /users/123/orders: Retrieves the list of orders for the user with ID 123.
- GET /users/123/orders/456: Retrieves the details of the specific order (ID 456) placed by the user with ID 123.
- POST /users/123/orders: Creates a new order for the user with ID 123.
5. Other Common RESTful Resource URL Patterns:
- Collections and sub-resources:
/users/{id}/posts
: All posts created by a specific user./posts/{id}/comments
: All comments on a specific post.
- Actions on resources: Some APIs might define custom actions for resources:
/users/{id}/activate
: Activates the user with the given ID./products/{id}/update-price
: A custom action for updating the price of a product.
Conclusion:
In RESTful design, resources are entities or objects that can be accessed and manipulated via standard HTTP methods. These resources are represented in URLs, and their structure is typically hierarchical and intuitive. By using meaningful, noun-based URLs that clearly represent resources, and by leveraging HTTP methods for actions on those resources, you can create a RESTful API that is easy to understand, maintain, and use.
Question: What is the role of status codes in RESTful API design?
Answer:
In RESTful API design, status codes are essential for conveying the result of an API request. They are part of the HTTP response and serve as a way to inform the client about the outcome of their request. Status codes are standardized by the HTTP/1.1 specification and play a crucial role in making RESTful APIs intuitive, reliable, and easy to debug.
Role of Status Codes in RESTful API Design:
-
Indicates the Outcome of a Request: Status codes tell the client whether a request was successful, whether there was an error, or whether further action is needed. The client can use these codes to determine how to handle the response.
- Success: When a request was processed successfully.
- Client Error: When the client has made an invalid request.
- Server Error: When an unexpected error occurs on the server side.
-
Enhances the Clarity of Responses: By including the appropriate HTTP status code, the server helps clients easily understand the nature of the response without needing to parse the entire message body. This is especially useful when dealing with large responses or complex error messages.
- For example, instead of just returning a generic message like “Operation completed successfully”, the API might return
200 OK
, allowing the client to quickly recognize that the operation was successful.
- For example, instead of just returning a generic message like “Operation completed successfully”, the API might return
-
Facilitates Proper Handling of Errors: A clear and accurate status code allows clients to respond appropriately to errors. For instance:
- A 404 Not Found means the requested resource doesn’t exist, and the client might prompt the user to check the URL or try a different query.
- A 401 Unauthorized means the client needs to authenticate or re-authenticate to perform the request.
-
Improves Debugging and Troubleshooting: Properly used status codes make it easier for both developers and automated systems to detect and troubleshoot issues. If the client receives an unexpected status code, it can trigger specific error handling logic.
-
Facilitates API Documentation: Status codes are part of standard REST API documentation, providing users of the API with clear information about what each endpoint does and what kind of responses they should expect. This makes it easier for developers to use the API correctly and handle edge cases.
Categories of HTTP Status Codes:
HTTP status codes are divided into five categories, each representing different kinds of responses:
1. 1xx (Informational):
- These codes indicate that the server has received the request and is processing it.
- Example:
100 Continue
— The client should continue sending the request, or ignore if the request has been completed.
2. 2xx (Successful):
-
These codes indicate that the request was successfully received, understood, and accepted.
-
Common 2xx Codes:
200 OK
: The request was successful, and the server returned the requested data (most common).201 Created
: The request was successful, and a new resource was created (usually after aPOST
request).204 No Content
: The request was successful, but there is no content to return (often used forDELETE
operations).202 Accepted
: The request was accepted, but processing is not yet complete (e.g., background processing).
-
Use Case Example:
200 OK
: When a user successfully logs in or retrieves their profile.201 Created
: When a new user is successfully registered.
3. 3xx (Redirection):
-
These codes indicate that the client needs to take additional action to complete the request (e.g., redirection to another URL).
-
Common 3xx Codes:
301 Moved Permanently
: The requested resource has been permanently moved to a new URL.302 Found
: The resource is temporarily available at a different URL.304 Not Modified
: The resource has not changed since the last request (used for caching purposes).
-
Use Case Example:
301 Moved Permanently
: When an API endpoint has been permanently moved to a new version.
4. 4xx (Client Error):
-
These codes indicate that there was an error in the request sent by the client. It usually means that the client must change the request to proceed.
-
Common 4xx Codes:
400 Bad Request
: The server cannot process the request due to malformed syntax or missing parameters.401 Unauthorized
: The client must authenticate to access the resource.403 Forbidden
: The client is authenticated but does not have permission to access the resource.404 Not Found
: The requested resource could not be found.409 Conflict
: The request could not be completed due to a conflict with the current state of the resource (e.g., attempting to create a duplicate resource).
-
Use Case Example:
404 Not Found
: When a user requests a resource that doesn’t exist (e.g.,/users/123
for a non-existent user).400 Bad Request
: When a client sends invalid data or fails to provide necessary parameters.
5. 5xx (Server Error):
-
These codes indicate that the server has encountered an error and cannot fulfill the request. This typically points to a bug or issue on the server side.
-
Common 5xx Codes:
500 Internal Server Error
: A generic server error, usually indicating an unhandled condition.502 Bad Gateway
: The server is acting as a gateway and received an invalid response from the upstream server.503 Service Unavailable
: The server is temporarily unable to handle the request, usually due to being overloaded or down for maintenance.504 Gateway Timeout
: The server, while acting as a gateway, did not receive a timely response from the upstream server.
-
Use Case Example:
500 Internal Server Error
: When the server encounters an unexpected condition (e.g., database crash or unhandled exception).503 Service Unavailable
: When the API server is temporarily down for maintenance.
Best Practices for Using HTTP Status Codes in RESTful API Design:
-
Choose the appropriate status code for each response: Always select the most accurate status code to convey the result of the request, such as
200 OK
for success,400 Bad Request
for client-side errors, and404 Not Found
when a resource cannot be located. -
Provide clear and helpful error messages: When returning error status codes like
400
,404
, or500
, ensure the response body provides a detailed message to help the client understand the issue. For example, an error message might include details like “Invalid email address format” or “User with ID 123 not found.” -
Be consistent: Use the same status codes across your API to represent the same types of responses. This ensures predictability and ease of use for API consumers.
-
Leverage caching-related status codes (e.g.,
304 Not Modified
): For resources that do not change frequently, use caching status codes to improve performance and reduce server load.
Conclusion:
In RESTful API design, status codes play a critical role in informing the client about the result of their request. By using the correct status codes, you enhance the clarity of the response, make your API easier to use, and provide important information for debugging, error handling, and decision-making. Properly chosen status codes allow for a seamless interaction between the client and server, and ensure that clients know how to proceed based on the response they receive.
Read More
If you can’t get enough from this article, Aihirely has plenty more related information, such as rest interview questions, rest interview experiences, and details about various rest job positions. Click here to check it out.
Tags
- REST
- API Design
- HTTP Methods
- Statelessness
- SOAP vs REST
- GET
- POST
- PUT
- DELETE
- API Versioning
- HATEOAS
- Authentication
- Error Handling
- Idempotent Methods
- Safe Methods
- GraphQL vs REST
- Pagination
- Response Formats
- Rate Limiting
- Middleware
- API Security
- REST Best Practices
- API Resources
- HTTP Status Codes
- RESTful Architecture
- RESTful Services
- Web APIs