We're sorry but this app doesn't work properly without JavaScript enabled. Please enable it to continue.

This lesson's interactive features are locked, please to keep using them

PUT

The HTTP PUT method creates or more commonly, updates a representation of the target resource with the contents of the request's body. In short, it updates a resource's properties.

await fetch(url, {
  method: "PUT",
  mode: "cors",
  headers: {
    "Content-Type": "application/json",
  },
  body: JSON.stringify(data),
});

POST vs. PUT

While POST and PUT are both used for creating resources, PUT is more common for updates and is idempotent, meaning it's safe to make the request multiple times without changing the server state. For example:

POST /users/bob (create bob user)
POST /users/bob (create duplicate bob user)
POST /users/bob (create duplicate bob user)
PUT /users/bob (create bob user if it doesn't exist)
PUT /users/bob (update bob user with the same data)
PUT /users/bob (update bob user with the same data)

Assignment

Complete the updateUser() and getUserById() functions. They should update and retrieve individual user resources respectively. For each fetch request:

  • Set the method to match the CRUD action being performed
  • Add Content-Type and X-API-Key headers
  • Set the mode to cors
  • Return a promise that gives the JSON from the response using the .json() method of the Response object

The updateUser function will also have to encode the user data in the body of the request using JSON.stringify.

We've included the fullURL creation logic for you in both functions, we'll be talking more about URL building in the next chapter.