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.

More GET options

GET 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’.

Let’s say we want to find all posts by userId=1.

>>> query = {"userId": 1}
>>> response = requests.get("https://jsonplaceholder.typicode.com/posts", params=query)
>>> print(response.json())

In our real Github REST API, we could for example search for repositories about requests in our favourite programming language python. The following should return 30 results.

>>> parameters = {"q": "requests+language:python"}
>>> response = requests.get("https://api.github.com/search/repositories", params=parameters)
>>> print(response.json().keys())  
## dict_keys(['total_count', 'incomplete_results', 'items'])

>>> print(len(response.json()["items"])) 
## 30

>>> print(response.url)
## https://api.github.com/search/repositories?q=requests%2Blanguage%3Apython

You can also pass multiple parameters. For example, you might be building a search engine interface to Github, and you might want to also limit the number of results per page. Let’s say 10 for this example.

>>> parameters = {"q": "requests+language:python", "per_page": 10}
>>> response = requests.get("https://api.github.com/search/repositories", params=parameters)

>>> print(len(response.json()["items"])) 
## 10

>>> print(response.url)
## https://api.github.com/search/repositories?q=requests%2Blanguage%3Apython&per_page=10

GET with timeout

Sometimes you might get stuck waiting forever for the server to respond. You counter this by including a timeout (in seconds) to your get request.

Here we abort the request if we do not receive a response within 1 second. The function will raise a TimeOut exception.

requests.get('https://api.github.com', timeout=1)