simple url_based APIs tutorial
simple url_based APIs
What is an API?¶
- Set of protocols and routines
- Bunch of code
- Allows two so!ware programs to communicate with each other
In [7]:
import requests
url = 'http://www.omdbapi.com/?t=Split'
r = requests.get(url)
json_data = r.json()
for key, value in json_data.items():
print(key + ':', value)
with open("a_movie.json", 'w+') as save:
save.write(r.text)
Loading and exploring a JSON¶
- with open(file_path) as file:
In [9]:
import json
# Load JSON: json_data
with open("a_movie.json") as json_file:
json_data = json.load(json_file)
# Print each key-value pair in json_data
for k in json_data.keys():
print(k + ': ', json_data[k])
API requests¶
- pull some movie data down from the Open Movie Database (OMDB) using their API.
- he movie you'll query the API about is The Social Network
- The query string should have one argument t=social+network
- Apply the json() method to the response object r and store the resulting dictionary in the variable json_data.
In [20]:
# Import requests package
import requests
# Assign URL to variable: url
url = 'http://www.omdbapi.com/?t=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)
print type(r.text)
print type(r.json())
# Decode the JSON data into a dictionary: json_data
json_data = r.json()
print
# Print each key-value pair in json_data
for key in json_data.keys():
print(key + ': ', json_data[key])
Wikipedia API¶
In [2]:
# Import package
import requests
# Assign URL to variable: url
url = 'https://en.wikipedia.org/w/api.php?action=query&prop=extracts&format=json&exintro=&titles=machine+learning'
# Package the request, send the request and catch the response: r
r = requests.get(url)
# Decode the JSON data into a dictionary: json_data
json_data = r.json()
# Print the Wikipedia page extract
pizza_extract = json_data['query']['pages']['233488']['extract']
print(pizza_extract)
In [ ]: