# Standard library: JSON files and paths
import json
from pathlib import Path
# Web requests, data and plotting
import matplotlib.pyplot as plt
import pandas as pd
import requests
from matplotlib.pyplot import figure
# World Bank indicators API
from pandas_datareader import wb<span style="background: #F2A65A; color: #14213D; font-weight: 700; font-size: 13px; padding: 4px 10px; border-radius: 12px;">Module 3 · Data from the Web</span>
<span style="background: #D7E6E4; color: #14213D; font-weight: 600; font-size: 13px; padding: 4px 10px; border-radius: 12px; margin-left: 6px;">⏱ about TODO minutes</span>
Introduction to Using APIs
| Objective | Use Python to request data from web APIs and turn the responses into pandas DataFrames. |
| You will | Make API requests with requests and check the status code · Extract values from JSON responses · Pull World Bank indicators with pandas-datareader |
| Data | data/raw/city.list.json (TODO size, OpenWeather bulk download) · an OpenWeather API key |
| Core packages | requests · pandas · pandas_datareader · matplotlib |
In this notebook, we will go through a practical example of how to use Python to access an API. For quick demonstration of the concepts, we will use the Open Notify API, openWeather and WBG APIs.
Requirements: requests, pandas, pandas-datareader, matplotlib.
Data: city.list.json in data/raw/; an OpenWeather API key.
0. Setup and Configuration
Lets make sure we import the required libraries
Working Directory and Input Files
# ============================================================
# BASE WORKING DIRECTORIES
# ============================================================
# The course folder is the closest folder, going upwards, that contains environment.yml
DIR_COURSE = next(
(p for p in [Path.cwd(), *Path.cwd().parents] if (p / "environment.yml").exists()), None
)
if DIR_COURSE is None:
DIR_COURSE = Path.cwd()
print("Running outside the course folder (e.g. Colab): upload the datasets to data/raw/.")
DIR_DATA = DIR_COURSE / "data" / "raw"
# ============================================================
# INPUT FILES
# ============================================================
# OpenWeather city list (city names and IDs)
FILE_CITY_LIST = DIR_DATA / "city.list.json"Global Variables for Processing
# ============================================================
# API ADDRESSES
# ============================================================
# Open Notify API (position of the International Space Station)
OPEN_NOTIFY_BASE_URL = "http://api.open-notify.org/"Accessing a Useless API Just to Learn
The Open Notify API is an open source project to provide a simple programming interface for some of NASA’s data related space and spacecrafts. Even though this is a toy example, the process of using APIs is similar for any API you will need to access in the future. For this tutorial, the task is to find the latest position of the Internation Space Station(ISS)
Understanding The API
As mentioned during the introductory lecture, its important to read the API documentation and understand the available endpoints. Also, to determine the exact endpoint for the data we are interested in getting.
- Base URL: For this API, the base url is:
http://api.open-notify.org. So, our full url which we will pass to requests will bebase-url + endpoint - Available Endpoints/Data: You can check here for avaible endpoints
- Target Endpoint: For our task, the endpoint is
iss-now.json
Making the Request
Now, lets request for the data. We create a simple function which makes the requests and prints the status code to see if we got a good result.
base_url = OPEN_NOTIFY_BASE_URL# endpoint for current position of ISS
pos_now = 'astros.json'# Full url
full_url = base_url + pos_now
full_url'http://api.open-notify.org/astros.json'
# Make a request using requests package
response = requests.get(full_url)if response.status_code == 200:
print('Everything is good, continue with data exctraction')
else:
code = response.status_code
print(code)404
response.json()['number']10
Use json() to retrieve the json object/data
# Get the data
dict_obj_from_json = response.json()
type(dict_obj_from_json)
print(dict_obj_from_json){'message': 'success', 'people': [{'name': 'Sergey Prokopyev', 'craft': 'ISS'}, {'name': 'Dmitry Petelin', 'craft': 'ISS'}, {'name': 'Frank Rubio', 'craft': 'ISS'}, {'name': 'Nicole Mann', 'craft': 'ISS'}, {'name': 'Josh Cassada', 'craft': 'ISS'}, {'name': 'Koichi Wakata', 'craft': 'ISS'}, {'name': 'Anna Kikina', 'craft': 'ISS'}, {'name': 'Fei Junlong', 'craft': 'Shenzhou 15'}, {'name': 'Deng Qingming', 'craft': 'Shenzhou 15'}, {'name': 'Zhang Lu', 'craft': 'Shenzhou 15'}], 'number': 10}
geo_info = dict_obj_from_json['iss_position']
geo_info{'latitude': '22.9547', 'longitude': '97.6678'}
lon = geo_info['longitude']
print(lon)
lat = geo_info['latitude']
print(lat)-33.2471
-32.8984
geo_info = dict_obj_from_json['iss_position']
lon = geo_info['longitude']
lat = geo_info['latitude']
print(lat,'--', lon)-32.8984 -- -33.2471
base_url = 'http://api.open-notify.org/'
#endpoint for current position of ISS
pos_now =
# Full url
full_url = base_url + pos_now
# Make a request using requests package
r = requests.get(full_url)
# Get the data
dict_obj_from_json = r.json()
# Extract Lat/Lon
geo_info = dict_obj_from_json['iss_position']
lon = geo_info['longitude']
lat = geo_info['latitude']
print(lat,'--', lon)def request_iss_position(endpoint_url=None):
# Make a get request
response = requests.get(endpoint_url)
# Print the status code of the response.
status_code = response.status_code
if status_code == 200:
print('Hooray!!, it worked')
# access the returned data
dict_obj_from_json = response.json()
print('Type: {}'.format(type(dict_obj_from_json)))
print('This is the nested dictionary returned: \n {}'.format(dict_obj_from_json))
lat = dict_obj_from_json['iss_position']['latitude']
lon = dict_obj_from_json['iss_position']['longitude']
print('ISS is passing on Lat: {}, and Lon: {} right about now'.format(lat, lon))
else:
print('What happened, lets see the code we got: {}'.format(status_code))base_url = OPEN_NOTIFY_BASE_URL
iss_pos = base_url + 'iss-now.json'
request_iss_position(endpoint_url=iss_pos)# Now, try to enter a wrong endpoint and see what happens
iss_pos2 = base_url + 'iss-today.json'
request_iss_position(endpoint_url=iss_pos2)Accessing the Data
Now, lets change our function so that we print the Latitude and Longitude of where ISS is right now.
request_iss_position(endpoint_url=iss_pos)EXERCISE-1:
Using the same API, check how many Astronouts are in space right now?
# base-url is same as above
# end point for this data: please check documentation
num_astros = YOUR CODE
# full_url number of astronouts
num_astros_url = YOUR CODE
# Make request
response = YOUR CODE
# Get data if response is 200
if response.status_code == 200:
# Extract the dict object from the JSON response
res = response.json()
# please print the dict object above so you can inspect it and see how to retrieve the required data
print(res)
# Get the number of people in spacw
YOUR CODE
# print number of people
YOUR CODEAccessing the Open Weather API
You can read all about it here but basically, they provide weather data for cities across the world.
def get_weather(base_url, api_key=None, city_id=None):
"""
Returns weather
:param api_key:
:param city_name:
:return:
"""
# add your API key
url = "{}{}&APPID={}".format(base_url, city_id, api_key)
# use requests to retrieve data from the API
response = requests.get(url)
# retrieve JSON from the response object
json_obj = response.json()
# return the JSON object
return json_objdef get_city_id(city_name=None, city_list_json_file=None):
"""
Since its easier to use city_id rather than name, we extract
city_id using giveen city name
"""
fopen = open(city_list_json_file, encoding="utf8")
city_list = json.load(fopen)
for c in city_list:
if c['name'].lower() == city_name.lower():
city_id = c['id']
print(city_id)
return city_id# Got this base_url from the open-weather API docs
base_url = "http://api.openweathermap.org/data/2.5/forecast?id="
# REPLACE WITH YOUR OWN OR YOU CAN USE MINE
API_KEY = 'cd689df7ce5a01db2aafde528e3d87c4'
# cityt_list json file, please replace with path to file
# hopefully you have this file
city_list_file = FILE_CITY_LIST
city_id = get_city_id(city_name="Lilongwe",
city_list_json_file=city_list_file)
# Now you can call the function to get data from the API
LL_weather = get_weather(base_url=base_url, api_key=API_KEY,
city_id=city_id)927967
When we access API’s, its often a data colleciton exercise:
- Ensure you read the API docs and understand how to make an API call
- Once you have all the required parameters (e.g., city_id and API key to make API call), make the call usingn requests
- Check if you have the data, retrieve JSON object
- Retrieve data/pull data ito dataframe
- Save to file/database
# PUT DATA INTO DATAFRAME
data_dict = LL_weather['list']
data_items = []
for i in data_dict:
temp_min = i['main']['temp_min']
temp_max = i['main']['temp_max']
date = i['dt_txt']
item = {'temp_min': temp_min, 'temp_max': temp_max, 'date': date}
data_items.append(item)
df = pd.DataFrame(data_items)
df| temp_min | temp_max | date | |
|---|---|---|---|
| 0 | 297.74 | 300.26 | 2023-02-02 12:00:00 |
| 1 | 296.06 | 298.86 | 2023-02-02 15:00:00 |
| 2 | 292.82 | 295.30 | 2023-02-02 18:00:00 |
| 3 | 291.58 | 291.58 | 2023-02-02 21:00:00 |
| 4 | 291.42 | 291.42 | 2023-02-03 00:00:00 |
| 5 | 291.06 | 291.06 | 2023-02-03 03:00:00 |
| 6 | 293.67 | 293.67 | 2023-02-03 06:00:00 |
| 7 | 297.27 | 297.27 | 2023-02-03 09:00:00 |
| 8 | 297.44 | 297.44 | 2023-02-03 12:00:00 |
| 9 | 295.76 | 295.76 | 2023-02-03 15:00:00 |
| 10 | 293.24 | 293.24 | 2023-02-03 18:00:00 |
| 11 | 291.87 | 291.87 | 2023-02-03 21:00:00 |
| 12 | 291.23 | 291.23 | 2023-02-04 00:00:00 |
| 13 | 290.79 | 290.79 | 2023-02-04 03:00:00 |
| 14 | 293.54 | 293.54 | 2023-02-04 06:00:00 |
| 15 | 297.56 | 297.56 | 2023-02-04 09:00:00 |
| 16 | 298.50 | 298.50 | 2023-02-04 12:00:00 |
| 17 | 296.85 | 296.85 | 2023-02-04 15:00:00 |
| 18 | 293.40 | 293.40 | 2023-02-04 18:00:00 |
| 19 | 291.48 | 291.48 | 2023-02-04 21:00:00 |
| 20 | 291.55 | 291.55 | 2023-02-05 00:00:00 |
| 21 | 291.42 | 291.42 | 2023-02-05 03:00:00 |
| 22 | 294.43 | 294.43 | 2023-02-05 06:00:00 |
| 23 | 298.02 | 298.02 | 2023-02-05 09:00:00 |
| 24 | 299.92 | 299.92 | 2023-02-05 12:00:00 |
| 25 | 296.85 | 296.85 | 2023-02-05 15:00:00 |
| 26 | 293.11 | 293.11 | 2023-02-05 18:00:00 |
| 27 | 291.73 | 291.73 | 2023-02-05 21:00:00 |
| 28 | 290.95 | 290.95 | 2023-02-06 00:00:00 |
| 29 | 290.37 | 290.37 | 2023-02-06 03:00:00 |
| 30 | 293.89 | 293.89 | 2023-02-06 06:00:00 |
| 31 | 296.72 | 296.72 | 2023-02-06 09:00:00 |
| 32 | 296.83 | 296.83 | 2023-02-06 12:00:00 |
| 33 | 294.49 | 294.49 | 2023-02-06 15:00:00 |
| 34 | 291.86 | 291.86 | 2023-02-06 18:00:00 |
| 35 | 291.26 | 291.26 | 2023-02-06 21:00:00 |
| 36 | 290.67 | 290.67 | 2023-02-07 00:00:00 |
| 37 | 290.23 | 290.23 | 2023-02-07 03:00:00 |
| 38 | 293.83 | 293.83 | 2023-02-07 06:00:00 |
| 39 | 297.45 | 297.45 | 2023-02-07 09:00:00 |
data_dict[0]{'dt': 1675339200,
'main': {'temp': 300.26,
'feels_like': 301.45,
'temp_min': 297.74,
'temp_max': 300.26,
'pressure': 1017,
'sea_level': 1017,
'grnd_level': 898,
'humidity': 61,
'temp_kf': 2.52},
'weather': [{'id': 500,
'main': 'Rain',
'description': 'light rain',
'icon': '10d'}],
'clouds': {'all': 40},
'wind': {'speed': 2.92, 'deg': 82, 'gust': 2.47},
'visibility': 10000,
'pop': 0.99,
'rain': {'3h': 1.87},
'sys': {'pod': 'd'},
'dt_txt': '2023-02-02 12:00:00'}
EXERCISE-2: Save weather data into a CSV
def compile_weather_forecast(city_name=None, output_csv_file=None):
"""
Get weather forecasts for Dakar. Please get only TEMPERATURE and HUMIDITY
Useful Info:
city_details_file: day2-python-for-data-science/data/city.list.json
:param your_api_key:
:param output_csv_file:
:return:
"""
# # copy and paste your API key below
# API_KEY = [YOUR CODE HERE]
#
# # JSON file with city details
# jfile = [YOUR CODE HERE]
#
# # load city details file
# with open(jfile) as f:
# data = json.load(f)
#
# # inspect the data object above
# # use for loop and if statement to find city id
# city_code = None
# [YOUR CODE HERE]
#
# # now get the weather forecast using the
# # "get_weather" function defined above
# weather_json = [YOUR CODE HERE]
#
# # using method for accessing a dictionary
# # put weather items in a list
# weather_items = [YOUR CODE HERE]
#
# # save into a dataframe
# data = [] # will hold our data
#
# for i in weather_items:
# # get forecast time
# ts = [YOUR CODE HERE]
#
# # get temperature, rain and humidity
# temp = [YOUR CODE HERE]
# hum = [YOUR CODE HERE]
#
# # for rains and clouds, use get() method to
# # retrieve required values
# rains = [YOUR CODE HERE]
#
# clouds = [YOUR CODE HERE]
#
# data_item = {'forecastTime': [YOUR CODE HERE], 'tempF': [YOUR CODE HERE],
# 'humidity': [YOUR CODE HERE], "rain": [YOUR CODE HERE],
# 'cloudsPercent': [YOUR CODE HERE]}
#
# # append to list of create earlier on
# [YOUR CODE HERE]
#
# # create dataframe
# [YOUR CODE HERE]
#
# # save dataframe with option index set to False
# [YOUR CODE HERE]dict_keys(['cod', 'message', 'cnt', 'list', 'city'])
Pulling Data World Bank Development Indicators API
We’re using Pandas Datareader: a third-party library that makes it easy to pull data from APIs into a Pandas dataframe.
Use it to pull live data from Yahoo! Finance, World Bank and others.
| Function | Task Performed |
|---|---|
| wb.get_countries() | List available countries, with their country codes, income levels etc. |
| wb.search() | Query the available indicators using a search term. |
| wb.WorldBankReader() | A class for downloading data series. |
Installing Pandas Datareader
Use the terminal to install the package pandas_datareader like so: pip3 install pandas_datareader
# Lets import World Bank module (wb) from pandas_datareaderList of Indicators
See here
# Find the GNI per capita indicator, get its ID number
indicator_name = "GNI per capita, Atlas"
result = wb.search(string=indicator_name, field = 'name')
result# Make a note of the indicator ID
GNI_ID = 'NY.GNP.PCAP.CD'# Get a list of countries and clean it up
countries = wb.get_countries()
countries.head()#Select only those observations and columns we need:
countries2 = countries[countries.incomeLevel != 'Aggregates']countries3 = countries2[['name', 'iso3c','incomeLevel']]
countries3.head()OECD_founders = ['Belgium','France','Germany','Italy','Luxembourg','Netherlands','United States',
'Canada','Japan']countries4 = countries3[countries3.name.isin(OECD_founders)]countries4.name.unique()type(countries4)countries_iso = list(countries4.iso3c.values)
countries_iso# Let's plot GNI per capita since 1960 for the OECD countries
# Create a reader object, pass it the data ID and country codes we want
reader = wb.WorldBankReader(symbols=GNI_ID,
countries = countries_iso,
start=1960)
GNI_capita = reader.read()
GNI_capita.head()GNI_capita = GNI_capita.unstack(level=0)[GNI_ID]
GNI_capita.head()
GNI_capita.plot(figsize=[8,6])
plt.title('GNI per capita for OECD founders since 1960')EXERCISE-2: Using WDI API
You going to generate a table of population for each country in Africa.
Get indicator name and identify indicator id/code
Use the website here to get indicator name for total population.
indicator_id = YOUR CODE HEREGet ISO codes for African Countries
In the data folder, there is a CSV file country_codes_africa.csv. We will use pandas to read the file and extract country names and use them to generate a list of ISO codes for African countries.
# Get ISO codes for African Countries
iso_codes_file = YOUR CODE HERE
# Read CSV into dataframe
df_iso = YOUR CODE HERE
# Check the dataframe using the head function
# Put the ISO codes into a list
countries = wb.get_countries()
names = list(df_iso.NAME_0.values)
afr_iso = countries.iso3c[countries.name.isin(names)]Get the Population Data for 2010
Please use the documentation for the function wb.WorldBankReader to understand how to use the parameters start and end to get data for 2010 only.
reader = wb.WorldBankReader(symbols=,
countries = countries_iso,
start=1960)
pop = YOUR CODE HERE
pop = pop.reset_index()
# display the first 10 rows of the dataframe
YOUR CODE HERE
# Rename the SP.POP.TOTL column. Check pandas documentation
# to see how you can rename a column
YOUR CODE HEREWhich Country Has The Largest Population in Africa?
Please use this method max(list) to find the country with the largest population. Hint: first put the population into a list and then use the method above.
Please answer the same question above this time using a method provided by pandas. Check pandas documentation on how to find a maximum value for a column
Summary
- TODO
- TODO
- TODO
Next: Web Scraping 101