Consuming APIs - PUT PATCH and DELETE
00:00
PUT
, PATCH
and DELETE
. Beyond GET
and POST
, requests
provide support for all the other HTTP methods you would use with a REST API. PUT
asks the server to process the resource that is sent to the API, and it allows the creation or updating of a resource. It’s most commonly used when updating an existing resource.
00:22
The code you’ll see on screen sends a PUT
request to update an existing to-do with new data. Any data sent with a PUT
request will completely replace the existing values of the to-do.
00:33
You’ll use the same JSON placeholder endpoint you use with GET
and POST
, but this time you’ll append 10
to the end of the URL.
00:41 This tells the REST API which to-do you’d like to update.
00:53
First, you call requests.get()
to view the contents of the existing to-do.
01:03
Next, you call requests.put()
with new JSON data to replace the existing to-do’s values.
01:23
You can see the new values when you call response.json()
. Successful PUT
requests will always return 200
instead of 201
because you aren’t creating a new resource, but just updating an existing one.
01:41
PATCH
is another HTTP method, and it’s similar to PUT
. Once more, it requests that the server processes the resource sent to the API, but it allows partial modification of a resource.
01:53
Here you’ll use requests.patch()
to modify the value of a specific field on an existing to-do. PATCH
differs from PUT
in that it doesn’t completely replace the existing resource.
02:03
It only modifies the value set in the JSON sent with the request. You’ll use the same to-do from the last example to try out requests.patch()
, and here are the current values.
02:16
Now you can update title
with a new value.
02:28
When you call response.json()
, you can see that title
has been updated to `Mow Lawn.
DELETE` is used when you want to remove a resource using an API.
02:40 Note that depending on the way the API is created, this may just mean removing access to a resource such as an image or other uploaded file rather than actually deleting the file from the server.
02:53
Here’s the code to remove a to-do. You call requests.delete()
with an API URL that contains the ID for the to-do you’d like to remove. This sends a DELETE
request to the REST API, which then removes the matching resource.
03:09 After deleting the resource, the API sends back an empty JSON object indicating that the resource has been deleted. The
03:20
requests
library is a great tool for working with REST APIs and an indispensable part of your Python toolkit. In the next section, you’ll change gears and consider what it takes to design a REST API.
Become a Member to join the conversation.