Thursday, October 3, 2019

Using a Web API

A web API is a part of a website designed to interact with programs. Those programs use very specific URLs to request certain information. This kind of request is called an API call. The requested data will be returned in an easily processed format, such as JSON or CSV. Most apps that rely on external data sources, such as apps that integrate with social media sites, rely on API calls.

I’ll use GitHub’s API to request information about Python projects on the site, and then generate an interactive visualization of the relative popularity of these projects using Plotly. GitHub’s API lets you request a wide range of information through API calls.

The Requests package allows a Python program to easily request information from a website and examine the response. Use pip to install Requests:

pip install requests

This line tells Python to run the pip module and install the Requests package to the current user’s Python installation.

Now let's write a program to automatically issue an API call and process the results by identifying the most starred Python projects on GitHub:

import requests

# Make an API call and store the response.
url = 'https://api.github.com/search/repositories?q=language:python&sort=stars'
headers = {'Accept': 'application/vnd.github.v3+json'}
r = requests.get(url, headers=headers)
print(f"Status code: {r.status_code}")

# Store API response in a variable.
response_dict = r.json()
# Process results.
print(response_dict.keys())


First we import the requests module. Next we store the URL of the API call in the url variable. GitHub is currently on the third version of its API, so we define headers for the API call that ask explicitly to use this version of the API. Then we use requests to make the call to the API. We call get() and pass it the URL and the header that we defined, and we assign the response object to the variable r. The response object has an attribute called status_code, which tells us whether the request was successful. We print the value of status_code so we can make sure the call went through successfully.

The API returns the information in JSON format, so we use the json() method to convert the information to a Python dictionary. We store the resulting dictionary in response_dict. Finally, we print the keys from response_dict as shown in the following output:

Status code: 200
dict_keys(['total_count', 'incomplete_results', 'items'])
------------------
(program exited with code: 0)

Press any key to continue . . .


Because the status code is 200, we know that the request was successful. The response dictionary contains only three keys: 'total_count', 'incomplete_results', and 'items'.

In the next post we'll look into the response dictionary.
Share:

0 comments:

Post a Comment