In this lesson, we explore how to implement the Update operation in a RESTful API, specifically focusing on adjusting the balance of a Cash Card by updating the amount on an existing database record. The key steps involve creating a new endpoint to receive HTTP requests with the appropriate verb (PUT), URI, and body, and returning suitable responses for success and error conditions.
PUT and PATCH:
- PUT is used to create or completely replace a resource at a specific URI. It means the client provides the full updated resource, and the server replaces the existing one.
- PATCH is used for partial updates of a resource. It allows the client to send only the fields that need to be updated, which can be more efficient for large resources.
- For our application, we decide not to implement partial updates and will use PUT for full updates.
PUT and POST:
- POST is typically used to create a new resource where the server generates the URI (e.g., creating a new Cash Card where the server assigns the ID).
- PUT can also be used to create a resource when the client supplies the URI, but in our case, we don't need this functionality.
Implementation Decisions:
- We will use PUT for updating existing Cash Cards but will not allow PUT to create new Cash Cards.
- The Update endpoint will accept a Cash Card object and replace the existing one with it.
- On success, it will return a 204 NO CONTENT status with an empty body.
- If the Cash Card does not exist or the user is unauthorized to update it, the endpoint will return a 404 NOT FOUND status.
Security Considerations:
- Similar to the GET requests, for unauthorized access or non-existent IDs, we return a 404 NOT FOUND to prevent leaking information about the existence of resources.
- This approach enhances security by not revealing whether a resource exists when the user is not authorized to access it.
Summary Table of HTTP Methods and CRUD Operations:
HTTP Method |
Operation |
Definition of Resource URI |
What does it do? |
Response Status Code |
Response Body |
POST |
Create |
Server generates URI |
Creates a sub-resource under the given URI |
201 CREATED |
The created resource |
PUT |
Update |
Client supplies URI |
Replaces the resource at the given URI completely |
204 NO CONTENT |
(empty) |
Bold rows indicate the methods we are implementing.
Conclusion: