Introduction to
Using APIs with Python
NaLette Brodnax
Indiana University Bloomington
School of Public & Environmental Affairs
Department of Political Science
www.nalettebrodnax.com
what is an API?
An application programming
interface (api) is a tool that allows
computers to exchange information.
uses of APIs
• Social – Twitter, Facebook, etc.
• Internet – bit.ly, domain registration
• Mapping – Google Maps, Bing Maps, etc.
• Search – Google, Yahoo, etc.
APIs make information transferred across the web digestible
for a computer.
what we’ll cover in this workshop
1 2 3
python simple complex
review example example
getting the tools for today
• Use Python 3 on SSRC computer
• Search for IDLE, a basic Python IDE
• requests library already installed
• Use Python on your machine
• Download Python 3.6 from www.python.org
• Use IDLE (or IDE of choice)
• Install the requests library using pip (or pip3 on
Mac OSX). See docs.python-requests.org
part 1: python review
data types: sequences
String—ordered ‘happy’
sequence of characters
List—ordered sequence [‘Leia’, ‘Rey’, ‘Maz’]
of items
Dictionary—unordered {‘name’:‘Kylo’, ‘side’:‘dark’}
sequence of key-value
pairs
referencing sequences
mystring = ‘happy’
Reference
print(mystring[0])
by index
print(mystring[2:4])
number,
starting
mylist = [‘Leia’, ‘Rey’, ‘Maz’]
with zero
print(mylist[-1])
Reference mydict = {‘name’:‘Kylo’, ‘side’:‘dark’}
by key print(mydict[‘name’])
modules
Import import csv
statements import json
allow you to import requests
add functions
csv – read and/or write csv files
json – decode or encode data in json (javascript object
notation) format
requests – use the HTTP protocol to exchange data over the
web
functions v. methods
Function-–named block of code that can accept any
number of arguments
my_string = ‘aBcDe’
print(my_string)
Method—a function with a built-in parameter for the object
being acted on
print(my_string.lower())
part 2: geocode an address
files for part 2
www.nalettebrodnax.com/python/
maps_api.py
Review • Access • Parse • Transform • stORe
RAPTOR
Web Server Web Server + API
Review HTML structure (tags, Parameters and
attributes, etc.) structure from
documentation
Access No registration, no Registration and
authentication sometimes
authentication
Parse HTML JSON or XML
Transform Nested tables, lists Nested dictionary
StORe Text, CSV Text, CSV
next steps
Google Maps API
Web Services APIs: Google Maps Geocoding API
Steps
• Register as a developer
• Create an application
• Create an authentication document
• Use the API - RAPTOR
https://developers.google.com/maps
your application
Save API key to a text file
Save API key to a text file
Review • Access • Parse • Transform • stORe
review
review
format
host = 'https://maps.googleapis.com/maps/api/geocode/json'
web server
access
import csv
import json
import requests
string
local_file = 'google_auth.txt' containing the
with open(local_file) as txtfile: name of the
my_key = txtfile.read() text file with
your api key
print("API Key: " + my_key)
access
the address to search
address = "1350 E 10th St, Bloomington, IN 47405"
url = host + "?address=" + address + "&key=" + my_key
response = requests.request('GET', url)
print(response)
check the response code (see https://httpstatuses.com/)
our GET request
https://maps.googleapis.com/maps/api/geocode/json?
address=1350+E+10th+St,+Bloomington,+IN+47405&key=
<my_api_key>
you can enter your GET request string into a browser
parse
convert JSON data to a Python object
geo = response.json()
transform
"pretty print" to see the nested structure
print(json.dumps(geo, indent = 4, sort_keys = True))
transform
save only what you need
print(type(geo)) # geo is a dictionary
print(geo.keys()) # check the dictionary keys
results = geo['results'][0]
print(results.keys())
store
longitude = results['geometry']['location']['lng']
latitude = results['geometry']['location']['lat']
run your script
From IDLE
• F5 or Run à Run Module
From the Command Line
Terminal (Mac OS X) Example
• Use ls to see a list of files in the directory
• Use cd to move to the directory that contains your script
149-160-200-169:~nbrodnax$ ls
149-160-200-169:~nbrodnax$ cd Documents
149-160-200-169:~nbrodnax$ python3 maps_api.py
let’s take a 5-minute break!
part 3: geocode a list of addresses
files for part 3
www.nalettebrodnax.com/python/
maps_api_loop.py
charter_schools.csv
review – access
import csv
import json
import requests
host = 'https://maps.googleapis.com/maps/api/geocode/json'
local_file = 'google_auth.txt'
with open(local_file) as txtfile:
my_key = txtfile.read()
print("API Key: " + my_key)
automate: access – parse – transform
def get_coordinates(address, api_key):
"""Returns a list with latitude and longitude for a given address
str, str -> list"""
url = host + "?address=" + address + "&key=" + api_key
response = requests.request('GET', url)
geo = response.json()
results = geo['results'][0]
return [results['geometry']['location']['lat'],\
results['geometry']['location']['lng']]
store
[{'NAME': 'Academy of Communications and Technology (ACT) Charter School,
'ADDRESS': '4319 W. Washington Blvd.', 'CITY STATE ZIP': 'Chicago, IL 60624},
{'NAME': 'Chicago International Charter School – Bucktown Campus, 'ADDRESS': '2235 N.
Hamilton', 'CITY STATE ZIP': 'Chicago, IL 60647}]
store
csvfile = open("charter_schools.csv", 'r')
header = csvfile.readline()
csvfile.close()
# print(header)
header = header.strip('\n')
fieldnames = header.split(',')
store
with open("charter_schools.csv", "r") as infile, \
open("charter_schools_geo.csv", "w") as outfile:
reader = csv.DictReader(infile, fieldnames)
next(reader, None)
fieldnames.append('LATITUDE')
fieldnames.append('LONGITUDE')
writer = csv.DictWriter(outfile, fieldnames)
writer.writeheader()
store
with open("charter_schools.csv", "r") as infile, \
.
.
.
for school in reader:
school_address = school['ADDRESS'] + ", " +
school['CITY STATE ZIP']
location = get_coordinates(school_address, my_key)
school['LATITUDE'] = location[0]
school['LONGITUDE'] = location[1]
writer.writerow(school)
run your script
From IDLE
• F5 or Run à Run Module
From the Command Line
Terminal (Mac OS X) Example
• Use ls to see a list of files in the directory
• Use cd to move to the directory that contains your script
149-160-200-169:~nbrodnax$ ls
149-160-200-169:~nbrodnax$ cd Documents
149-160-200-169:~nbrodnax$ python3 maps_api_loop.py
❓
Review • Access • Parse • Transform • stORe
Thank You!
www.nalettebrodnax.com
email: nbrodnax@indiana.edu
linkedin: nalettebrodnax
github: nmbrodnax
twitter: @nbrodnax