Junior
Tell me about the PUT method in REST API.
sobes.tech AI
Answer from AI
The PUT method is used to create or update a resource at a specified URI.
Key features:
- Idempotency: Performing the same PUT request multiple times with the same body will result in the same state of the resource on the server (although the server's response may differ).
- Full replacement: PUT sends a complete new representation of the resource, replacing the existing one.
- Create or update: If the resource at the specified URI does not exist, PUT creates it. If it exists, it updates it. The absence of a resource upon a successful PUT request leads to creation, usually returning a 201 Created status. Updating an existing resource typically returns 200 OK or 204 No Content (if there is no body in the response).
Typical use cases:
- Updating a user's full profile.
- Creating a resource if the client defines its URI.
Example of a PUT request:
PUT /users/123 HTTP/1.1
Host: api.example.com
Content-Type: application/json
{
"id": 123,
"name": "New Name",
"email": "new.email@example.com"
}
The server will receive this request and either create a user with id=123 or completely replace the user's information with the data from the request body.
PUT differs from POST in the following ways:
- PUT is used for updating or creating a resource at a known URI that the client defines. POST is used for creating a resource where the server defines the URI of the new resource, or for other actions that do not fall under other HTTP methods.
- PUT is idempotent, POST is not. Multiple POST requests with the same body can create multiple identical resources or cause different side effects.
Comparison table of PUT and POST:
| Characteristic | PUT | POST |
|---|---|---|
| Purpose | Create or update a resource | Create a resource, send data |
| Idempotency | Yes | No |
| URI definition | By the client | By the server |
| Impact on resource | Fully replaces or creates | Usually adds or triggers an action |