This is an archived version of the course. Please find the latest version of the course on the main webpage.

Chapter 4: HTTP request methods

POST request

face Josiah Wang

Besides GET, the next most used HTTP method is POST. This method is often used to create a new resource.

Like GET, you can pass some parameters in your request. But you do not encode the values inside your URL (http://localhost:5000/articles?author=2&query=future). Instead, you pass them in the optional message body of your HTTP request.

Let us now try to POST (create) a new article to our blog API. Let’s say we want to post a new article with the title "We love Python" and content "What kind of car does a snake drive? An ana-honda.", and let’s say this will be by author ID 4. You will need to pass these to the data keyword argument.

>>> article_title = "We love Python"
>>> article_content = "What kind of car does a snake drive? An ana-honda."
>>> author_id = 4
>>> new_article = {"author": author_id, "title": article_title, "content": article_content}
>>> response = requests.post("http://localhost:5000/articles", data=new_article)
>>> print(response.json())
{'author': 4, 'content': 'What kind of car does a snake drive? An ana-honda.', 'id': 11, 'title': 'We love Python'}
>>> print(response.url)
http://localhost:5000/articles

Note that the server returned a response containing your newly created resource (your new article). Note the ID of the new article is 11 (remember we had 10 articles in total earlier). So this response is also a form of acknowledgement that you have successfully created a new article.

Also note that the parameters are not encoded in the URL this time (last line).

If you query for all articles by author ID 4, you can see your new article in the list!

>>> response = requests.get("http://localhost:5000/articles", params={"author": 4})
>>> print(response.json())
[{'author': 4, 'content': "C'mon. The flux capacitor. Well, what if they didn't like them, what if they told me I was no good. I guess that would be pretty hard for somebody to understand. Hey, hey, I've seen this one, I've seen this one. This is a classic, this is where Ralph dresses up as the man from space. Thanks, thanks a lot.", 'id': 7, 'title': "They can't dance"}, 
 {'author': 4, 'content': 'What kind of car does a snake drive? An ana-honda.', 'id': 11, 'title': 'We love Python'}]