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 pyfetch(
    url,
    method="PUT",
    headers={
        "Content-Type": "application/json",
    },
    body=json.dumps(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 update_user(base_url: str, user_id: str, data: User, api_key: str) -> User and get_user_by_id(base_url: str, user_id: str, api_key: str) -> User functions. They should update and retrieve individual user resources respectively. For each pyfetch request:

  • Set the method to match the CRUD action being performed
  • Add Content-Type and X-API-Key headers
  • Return the JSON from the response using the await response.json() method

The update_user function will also have to encode the user data in the body of the request using json.dumps().

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