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 Verb | Description | Typical Use |
|---|---|---|
| GET | Retrieves data from the server. | Used to fetch data without altering it. |
| POST | Sends data to the server to create a new resource. | Used to create new entries. |
| PUT | Updates a resource on the server, usually replacing it entirely. | Used to fully update or replace an existing resource. |
| DELETE | Removes a resource from the server. | Used to delete a resource. |
| PATCH | Partially updates an existing resource. | Used for partial updates. |
HTTP Verb Details
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 OKfor success,404 Not Foundif the resource is unavailable, and400 Bad Requestfor malformed requests.
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 Createdfor a successful creation,400 Bad Requestif data is malformed, or409 Conflictif there is a duplicate.
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 OKor204 No Contentfor successful updates, and404 Not Foundif the resource is missing.
DELETE
- Description: Used to delete a resource from the server. Should be idempotent (multiple deletions should have the same effect).
- Status Code:
200 OKor204 No Contenton success,404 Not Foundif the resource is missing.
PATCH
- Description: Partially updates a resource. Only the data that needs changing is sent in the request body.
- Status Code:
200 OKfor success,204 No Contentfor no content in response, or404 Not Foundif the resource doesn’t exist.
Common Interview Questions and Sample Answers
What is the difference between PUT and PATCH?
- Answer:
PUTis used for complete updates, often replacing the entire resource. If fields are missing, they may be replaced with default values.PATCHis used for partial updates, changing only specific fields without affecting the rest.
- Answer:
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.
When would you use PUT over POST?
- Answer:
PUTis used when updating or replacing an existing resource, where the client specifies the resource location.POSTis for creating a new resource, and the server determines its location.
- Answer:
Can you use PUT for creating a resource?
- Answer: Technically, yes. Some APIs allow
PUTto create a resource if it doesn’t exist, but this is non-standard. Usually,POSTis preferred for creating resources.
- Answer: Technically, yes. Some APIs allow
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, andDELETEare idempotent:GET /items/1retrieves the same data each time.PUT /items/1updates the item similarly, regardless of how many times it is called with the same data.DELETE /items/1removes the item once, so further requests have no additional effect.
- Answer: An idempotent HTTP method means making multiple identical requests has the same effect as making a single request. For example,
Why might a DELETE request return a 404 status?
- Answer: A
DELETErequest may return404 Not Foundif the resource was already deleted or never existed. This helps confirm that the resource does not exist in the system.
- Answer: A
Is PATCH idempotent?
- Answer: This depends on the implementation, but generally,
PATCHcan be idempotent if the partial update is applied the same way each time with the same input. However,PATCHcan also be non-idempotent if it makes incremental changes on each request.
- Answer: This depends on the implementation, but generally,
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
What status code would you expect if a PUT request was successful, and why?
- Answer: Typically, a
PUTrequest returns200 OKif it includes a response body or204 No Contentif the server does not return a body. These indicate a successful update. If thePUTcreates a new resource (in some cases), it might return201 Created.
- Answer: Typically, a
When should you use a POST request instead of PUT for updating resources?
- Answer:
POSTis 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).PUTis typically preferred for updates that replace or update a specific resource in an idempotent manner.
- Answer:
If an API endpoint is designed to only update specific fields, which HTTP method should it use, and why?
- Answer: It should use
PATCH, asPATCHis designed for partial updates, only modifying the specified fields without affecting the rest of the resource. This contrasts withPUT, which is intended for full updates or replacements.
- Answer: It should use
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.
- 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
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.,
GETandHEAD), 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:
DELETEis idempotent (deleting the same resource multiple times has the same effect), but it’s not considered safe since it modifies the resource.
- Safe methods do not modify resources on the server (e.g.,
- Answer:
How would you handle a case where a DELETE request on a non-existing resource should return success?
- Answer: Returning
204 No Contentis often a good approach, as it indicates the operation has no additional content to return. Alternatively,200 OKcould also be used to signal that the request was processed without errors, even though the resource was already non-existent.
- Answer: Returning
Can PUT requests have a response body? If so, what should it contain?
- Answer: Yes,
PUTrequests 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 use204 No Contentfor successfulPUTrequests to indicate that no body is provided.
- Answer: Yes,
What HTTP status code would you use for a PATCH request with invalid data, and why?
- Answer: A
400 Bad Requeststatus 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.
- Answer: A
Explain when you would use 405 Method Not Allowed and give an example.
- Answer:
405 Method Not Allowedis returned when the server supports a certain resource but does not allow the HTTP method used in the request. For example, ifPOST /items/1is used butPOSTis not permitted on the/items/1resource (perhaps onlyGETandPUTare allowed), the server would respond with405.
- Answer:
Can you explain OPTIONS requests in REST APIs and why they’re used?
- Answer: The
OPTIONSmethod 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.
- Answer: The
What should be the expected response code and message body if a PATCH request tries to modify a non-existent resource?
- Answer:
404 Not Foundis typically returned to indicate that the resource does not exist and cannot be updated. Some APIs may return204 No Contentif they choose to treat non-existence as a no-op, but404is more standard and explicit.
- Answer:
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.
PUTis typically used for upsert operations, as it is idempotent, meaning repeating the operation has no further effects after the first time.
- Answer: “Upsert” (update or insert) is a combination operation where the resource is updated if it exists or created if it doesn’t.
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
GETrequest 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.
- Answer: Query parameters in a
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.
0 comments:
Post a Comment