10 02 Interacting with APIs to import data from the web - HannaAA17/Data-Scientist-With-Python-datacamp GitHub Wiki
Much of the data we'll get from
APIs
are actually packaged in JSON.
Introduction to APIs and JSONs
APIs
- Application Programming Interface
- Protocols and routines -Building and interacting with software applications
JSONs
- JavaScript Object Notation
- Real-time server-to-browser communication
- Human readable
- like a Python dictionary
Loading and exploring a JSON
import json
# Load JSON: json_data
with open("a_movie.json") as json_file:
json_data = json.load(json_file) # a dictionary
# Print each key-value pair in json_data
for k in json_data.keys():
print(k + ': ', json_data[k])
# or
for key, value in json_data.items():
print(key + ':', value)
APIs and interacting with the world wide web
What is an API
- Set of protocols and routines
- Bunch of code
- Allows two software programs to communicate with each other
Connect to APIs : requests
the URL
- http - making an HTTP request
- www.omdbapi.com - querying the OMDB API
?apikey=72bc447a&t=the+social+network
- Query string
- Return data for a movie with API key 72bc447a & title (t) ‘Hackers’
- Described in official documentation
# Import requests package
import requests
# Assign URL to variable: url
url='http://www.omdbapi.com/?apikey=72bc447a&t=the+social+network'
# Package the request, send the request and catch the response: r
r = requests.get(url)
# Print the text of the response
print(r.text) # and actually a json
JSON–from the web to Python
- the response got is actually a JSON
.json()
: built-in JSON decoder
# Decode the JSON data into a dictionary: json_data
json_data = r.json()
# Print each key-value pair in json_data
for k in json_data.keys():
print(k + ': ', json_data[k])