Requesting data from an API

Photo by RetroSupply on Unsplash

Requesting data from an API

·

2 min read

My aim is to write short articles on the seemingly 'simple' things with the hope that it helps someone out there become a little bit better at the 'simple' things.

If you are here today, it means you want to know how to retrieve data using an API. API stands for Application Programming Interface. It is basically server A telling server B what it wants and then Server B sending it to Server A. In today's example, your machine, laptop or whatever (server A) will be telling the World Bank data bank (Server B) the data it wants with the help of a simple API

The most common python library used to get data using APIs is the requests library. If you haven't installed requests on your system, use the code below

pip install requests

In the example below, we use the World Bank API.

''' 
The requests and pandas libraries were imported
A request was made to the world bank using the World Bank API and the response was stored in a variable called res.
'''

import requests
import pandas as pd

url = "http://api.worldbank.org/v2/country/CH/indicator/SP.RUR.TOTL?date=1985:2001&format=json"

res = requests.get(url)
'''
 Run this cell to see if the response was successful
 an ouput of 200 means that the request was successful
'''

res.status_code
'''
Converting the response to a JSON object.
Print the data to understand the structure
'''

res_json = res.json()
res_json
'''
The pd.json_normalize() is used to flatten out nested json data.
You can skip this normalizing step if your data is not nested

I used 'res_json[1]' because all of the data is present in the second element. 
I found this out by printing the data in the previous step

''' 

res_normalized = pd.json_normalize(res_json[1], sep='_')
''' 
Convert the JSON file into a dataframe.
'''

df = pd.DataFrame(res_normalized)
'''
Print out the first 5 rows to inspect your data
'''

df.head()

Many big organizations have publicly accessible APIs which can be used by developers or data professionals. One of my favorites to play around with is the Yelp Fusion

I hope this article was worth your time and it helped you out.

Till I write about something simpler,

Komoni