Thursday, 31 October 2024

HTTP Verbs (GET, POST, PUT, DELETE, PATCH) in WebAPI

In web APIs, HTTP verbs are crucial for defining the operations that can be performed on resources. Here’s a breakdown of the primary HTTP verbs and common interview questions related to them.

1. HTTP Verbs Overview

HTTP VerbDescriptionTypical Use
GETRetrieves data from the server.Used to fetch data without altering it.
POSTSends data to the server to create a new resource.Used to create new entries.
PUTUpdates a resource on the server, usually replacing it entirely.Used to fully update or replace an existing resource.
DELETERemoves a resource from the server.Used to delete a resource.
PATCHPartially updates an existing resource.Used for partial updates.

HTTP Verb Details

  1. GET

    • Description: Used for retrieving data. It is a read-only operation and should be idempotent (making the same request multiple times should yield the same result without side effects).
    • Status Code: Typically returns 200 OK for success, 404 Not Found if the resource is unavailable, and 400 Bad Request for malformed requests.
  2. POST

    • Description: Used for creating a new resource. Data is sent in the request body, and the server generates a new resource.
    • Status Code: Generally returns 201 Created for a successful creation, 400 Bad Request if data is malformed, or 409 Conflict if there is a duplicate.
  3. PUT

    • Description: Used for updating a resource, often replacing it entirely. If the resource does not exist, it might create a new one (depending on the API).
    • Status Code: Typically 200 OK or 204 No Content for successful updates, and 404 Not Found if the resource is missing.
  4. DELETE

    • Description: Used to delete a resource from the server. Should be idempotent (multiple deletions should have the same effect).
    • Status Code: 200 OK or 204 No Content on success, 404 Not Found if the resource is missing.
  5. PATCH

    • Description: Partially updates a resource. Only the data that needs changing is sent in the request body.
    • Status Code: 200 OK for success, 204 No Content for no content in response, or 404 Not Found if the resource doesn’t exist.

Common Interview Questions and Sample Answers

  1. What is the difference between PUT and PATCH?

    • Answer: PUT is used for complete updates, often replacing the entire resource. If fields are missing, they may be replaced with default values. PATCH is used for partial updates, changing only specific fields without affecting the rest.
  2. Is it safe to use GET requests to modify data? Why or why not?

    • Answer: No, GET requests should only retrieve data without making any modifications. Using GET for data modification violates the principle of safe operations, which expects that GET requests do not have side effects.
  3. When would you use PUT over POST?

    • Answer: PUT is used when updating or replacing an existing resource, where the client specifies the resource location. POST is for creating a new resource, and the server determines its location.
  4. Can you use PUT for creating a resource?

    • Answer: Technically, yes. Some APIs allow PUT to create a resource if it doesn’t exist, but this is non-standard. Usually, POST is preferred for creating resources.
  5. Explain idempotence in HTTP methods with examples.

    • Answer: An idempotent HTTP method means making multiple identical requests has the same effect as making a single request. For example, GET, PUT, and DELETE are idempotent:
      • GET /items/1 retrieves the same data each time.
      • PUT /items/1 updates the item similarly, regardless of how many times it is called with the same data.
      • DELETE /items/1 removes the item once, so further requests have no additional effect.
  6. Why might a DELETE request return a 404 status?

    • Answer: A DELETE request may return 404 Not Found if the resource was already deleted or never existed. This helps confirm that the resource does not exist in the system.
  7. Is PATCH idempotent?

    • Answer: This depends on the implementation, but generally, PATCH can be idempotent if the partial update is applied the same way each time with the same input. However, PATCH can also be non-idempotent if it makes incremental changes on each request.

These answers can help in handling both basic and nuanced interview questions about HTTP verbs in web APIs, demonstrating a solid understanding of RESTful principles and practical API design.


Here are more advanced interview questions on HTTP verbs and REST APIs, along with explanations and suggested answers:

Advanced Interview Questions on HTTP Verbs

  1. What status code would you expect if a PUT request was successful, and why?

    • Answer: Typically, a PUT request returns 200 OK if it includes a response body or 204 No Content if the server does not return a body. These indicate a successful update. If the PUT creates a new resource (in some cases), it might return 201 Created.
  2. When should you use a POST request instead of PUT for updating resources?

    • Answer: POST is used for updates in cases where the update operation modifies the resource in a non-idempotent way or when a new resource could be created (e.g., submitting a form that may generate multiple entries). PUT is typically preferred for updates that replace or update a specific resource in an idempotent manner.
  3. If an API endpoint is designed to only update specific fields, which HTTP method should it use, and why?

    • Answer: It should use PATCH, as PATCH is designed for partial updates, only modifying the specified fields without affecting the rest of the resource. This contrasts with PUT, which is intended for full updates or replacements.
  4. Why are GET requests not recommended for sensitive data submissions?

    • Answer: GET requests append parameters in the URL, making them visible in the browser history, logs, and server caches. This could expose sensitive information unintentionally, violating security best practices. Instead, sensitive data should be sent via POST, as the data is sent in the request body, not in the URL.
  5. What is the difference between a safe and an idempotent HTTP method? Give examples.

    • Answer:
      • Safe methods do not modify resources on the server (e.g., GET and HEAD), meaning they are read-only operations.
      • Idempotent methods produce the same outcome no matter how many times they’re called with the same parameters (e.g., GET, PUT, DELETE).
      • Example: DELETE is idempotent (deleting the same resource multiple times has the same effect), but it’s not considered safe since it modifies the resource.
  6. How would you handle a case where a DELETE request on a non-existing resource should return success?

    • Answer: Returning 204 No Content is often a good approach, as it indicates the operation has no additional content to return. Alternatively, 200 OK could also be used to signal that the request was processed without errors, even though the resource was already non-existent.
  7. Can PUT requests have a response body? If so, what should it contain?

    • Answer: Yes, PUT requests can return a response body, although it’s optional. If included, it usually contains the updated resource or confirmation details, which might help the client verify the changes. However, many APIs use 204 No Content for successful PUT requests to indicate that no body is provided.
  8. What HTTP status code would you use for a PATCH request with invalid data, and why?

    • Answer: A 400 Bad Request status code should be returned if the request contains invalid data. This indicates to the client that the data format or content does not meet the server’s requirements, thus blocking the request.
  9. Explain when you would use 405 Method Not Allowed and give an example.

    • Answer: 405 Method Not Allowed is returned when the server supports a certain resource but does not allow the HTTP method used in the request. For example, if POST /items/1 is used but POST is not permitted on the /items/1 resource (perhaps only GET and PUT are allowed), the server would respond with 405.
  10. Can you explain OPTIONS requests in REST APIs and why they’re used?

    • Answer: The OPTIONS method is used to discover what HTTP methods and headers are supported by a server on a particular resource. This is especially common in CORS (Cross-Origin Resource Sharing) scenarios, where the browser checks which HTTP methods and headers are allowed before sending actual requests.
  11. What should be the expected response code and message body if a PATCH request tries to modify a non-existent resource?

    • Answer: 404 Not Found is typically returned to indicate that the resource does not exist and cannot be updated. Some APIs may return 204 No Content if they choose to treat non-existence as a no-op, but 404 is more standard and explicit.
  12. Explain the concept of “upsert” in relation to HTTP verbs. Which verb is most suitable for this operation?

    • Answer: “Upsert” (update or insert) is a combination operation where the resource is updated if it exists or created if it doesn’t. PUT is typically used for upsert operations, as it is idempotent, meaning repeating the operation has no further effects after the first time.
  13. Why might a RESTful API endpoint that follows REST principles still need to include query parameters in a GET request?

    • Answer: Query parameters in a GET request are useful for filtering, sorting, or paginating results without altering the resource. This maintains the RESTful principle of statelessness while providing flexible data retrieval options for clients.

These questions can test both conceptual understanding and practical application of HTTP methods in RESTful APIs, helping candidates demonstrate their expertise in API design and best practices.

Share:

0 comments:

Post a Comment