Consider a REST API where a resource at /users/123 currently has the data:
{"name": "Alice", "age": 30, "city": "New York"}A client sends a PUT request to /users/123 with the body:
{"name": "Alice", "age": 31}What will be the state of the resource after this PUT request?
Remember that PUT replaces the entire resource, not just updates parts.
A PUT request replaces the entire resource with the data sent. Since the city field is missing in the PUT body, it will be removed from the resource.
You want to replace an entire resource on the server with new data. Which HTTP method should you use?
One method is designed to replace the entire resource, while another updates parts.
PUT is used to fully replace a resource. PATCH is for partial updates. POST is for creating new resources or other actions. GET is for retrieving data.
A developer sends a PUT request to update a user resource with the following JSON body:
{"name": "Bob", "age": 25}But after the request, the resource still has the old data including city. The server code handling the PUT is:
def put_user(user_id, data):
user = get_user(user_id)
user.update(data)
save_user(user)Why does the resource not get fully replaced?
def put_user(user_id, data):
user = get_user(user_id)
user.update(data)
save_user(user)Think about what update() does to a dictionary.
The update() method merges the new data into the existing resource, so fields not in the new data remain unchanged. This means the resource is not fully replaced as expected by PUT semantics.
You want to send a PUT request to replace a resource. Which JSON body is syntactically valid?
Remember JSON syntax rules for commas and quotes.
Option A is valid JSON. Option A has a trailing comma which is invalid. Option A is missing a comma between fields. Option A uses unquoted keys, which is invalid in JSON.
A REST API requires the fields name, age, and email for a user resource.
A client sends a PUT request with the body:
{"name": "Sam", "age": 40}The email field is missing. What is the expected server behavior according to REST principles?
Think about data validation and the meaning of PUT replacing the entire resource.
Since PUT replaces the entire resource, missing required fields mean the resource would be incomplete. The server should reject the request with a 400 error to enforce data integrity.