Advanced Lesson 3
HTTP Requests
Chapter 4: HTTP request methods
GET request with parameters
You can also make a GET request with some parameters. You might have sometimes seen this passed in a URL (e.g. https://www.google.com/search?q=python). This is essentially making a GET request with the key "q"
and value "python"
.
Back to our blog API, let’s say we want to find all posts by the author
with ID 2
. You can pass this in as an argument to the params
parameter.
>>> parameter = {"author": 2}
>>> response = requests.get("http://localhost:5000/articles", params=parameter)
>>> print(len(response.json()))
3
>>> print(response.json())
[{'author': 2, 'content': 'Ronald Reagon. ...
>>> print(response.url)
http://localhost:5000/articles?author=2
You can see that your argument is formatted inside the URL (last line). In fact, if you check your server logs, you will see that this was actually what is passed to your server. You can actually just encode your parameters in your URL directly, i.e. requests.get("http://localhost:5000/articles?author=2")
. But it is better to do it the way we did above, as requests
will automatically escape characters that are not allowed in a URL (say a quotation mark "
). It’s more readable too.
You can also pass multiple parameters. For example, you might want to filter the articles so that you only get those from the author with ID 2
and where the article mentions the word "future"
.
>>> parameters = {"author": 2, "query": "future"}
>>> response = requests.get("http://localhost:5000/articles", params=parameters)
>>> print(len(response.json())) # Only 2 articles now instead of 3!
2
>>> print(response.json())
[{'author': 2, 'content': "Listen, this is very important, ...
>>> print(response.url)
http://localhost:5000/articles?author=2&query=future