This is an archived version of the course and is no longer updated. Please find the latest version of the course on the main webpage.

Request Methods

As mentioned, the four most commonly used HTTP methods (or verbs) are POST, GET, PUT, and DELETE. The verbs usually corresponds to the actions CREATE, READ, UPDATE, and DELETE.

Requests provides an easy and elegant way to make these specific requests.

We will use the API on JSONPlaceholder instead of Github for this example, since the Github API requires authentication to perform these actions (for obvious reasons: you do not want a stranger to suddenly delete your repo, do you?).

First, let us GET (read/retrieve) the post with ID 1.

>>> response = requests.get("https://jsonplaceholder.typicode.com/posts/1")
>>> print(response.json())

Let us now try to POST (create) a new post with the title “My new title” and body “My new content”. You will need to pass the parameters with the data keyword argument. Observe the response JSON: If successful, what is the ID of your new post? This server had 100 posts before you ‘created’ yours. It will also return the title and body of your new post. In real life, this is an acknowledgement that you have successfully created a new post. This did not actually happen on this server as it is a fake API for testing purposes.

>>> new_post = {"title": "My new title", "body": "My new content"}
>>> response = requests.post("https://jsonplaceholder.typicode.com/posts", data=new_post)
>>> print(response.json())

Now, let us PUT (update) the post with ID 1 (the first post we retrieved earlier). Let’s say we want to rename the title to a better one. Again, examine the response. What is the ID? In real life, you would have successfully modified the first post (but again this is faked on the server)

>>> updated_post = {"title": "A better title", "body": "A much better story"}
>>> response = requests.put("https://jsonplaceholder.typicode.com/posts/1", data=updated_post)
>>> print(response.json())

Finally, let us DELETE the post with ID 1. Again, this is faked on the server side.

>>> response = requests.delete("https://jsonplaceholder.typicode.com/posts/1")
>>> print(response.json())  # should be an empty dictionary