Client-server communication with APIs:
- Client (program) sends a request to a remote (web) server
- Server processes the request and provides a response (with status and data)
- Client (program) receives response and data
- Client processes the data
APIs on the web:
- Communicate using http or https protocols
- APIs are hosted on web servers
- They are essentially web (data) “pages”
- And you can use browser or related tools to test the APIs
- JSON is the common data format
Example web APIs:
- OpenNotify API: http://open-notify.org/
- Using GET request to retrieve information about the international space station
- Multiple endpoints for different data
Example endpoint: iss-now.json
- Gets the current latitude and longitude of the international space station
- Base url at: http://api.open-notify.org
Example Python request to OpenNotify API:
import requests
# Make a get request to get the latest position of
# the international space station from the opennotify api.
response = requests.get("http://api.open-notify.org/iss-now.json")
# Print the status code of the response.
print(response.status_code)
Standard status codes in http:
200
-- everything okay301
-- server redirecting you to a different endpoint401
-- not authenticated.400
-- a bad request.403
-- access is forbidden404
-- the resource not found on the server
Request to a non-existent endpoint:
# the endpoint/url does not exist
response = requests.get("http://api.open-notify.org/iss-pass")
print(response.status_code)
Try the URL in your browser. Why did you get?
Another try:
response = requests.get("http://api.open-notify.org/iss-pass.json")
print(response.status_code)
This hits an available endpoint, but with incorrect parameters (a bad request).
For documentation of the OpenNotify API http://open-notify.org/Open-Notify-API/ISS-Pass-Times/
Documentation shows that the iss-pass.json:
- Returns when (time) the ISS will pass over a given location on earth
- Requires two parameters about the location
lat
: the latitude of the locationlon
: the longitude of the location
Correct endpoint with required parameters
# Set up the parameters we want to pass to the API.
# This is the latitude and longitude of New York City.
parameters = {"lat": 40.71, "lon": -74}
# Make a get request with the parameters.
response = requests.get("http://api.open-notify.org/iss-pass.json", params=parameters)
# Parse the JSON content of the response, from server
print(response.content)
The output data look messy, difficult to read. Let's check the response header
, especially on the content-type
field, to see what format is used for the returned data from server:
response = requests.get("http://api.open-notify.org/iss-pass.json", params=parameters)
print(response.headers)
print("Content type of server response is:", response.headers["content-type"])
Now that it is application/json
, there are a couple of methods to parse the data as JSON:
import json
from pprint import pprint
# parse response content to JSON
data = json.loads(response.content)
print("json.loads: ")
pprint(data)
# OR, use the response.json() to get JSON directly
same_data = response.json()
print("response.json:")
pprint(same_data)
Given the JSON data structure, we can access specific data elements such as message
:
print(data['message'])
Twitter API
Twitter APP Access Please follow the instructions here to create an app to access Twitter API: https://developer.twitter.com/en/docs/basics/getting-started#get-started-app
Twitter Search API Reference Please study Twitter’s standard search API at:
https://developer.twitter.com/en/docs/tweets/search/api-reference/get-search-tweets.html
Access Twitter API:
- Twitter applications need OAuth for autentication
- Token-based authentication to OAuth
Create an application for access token:
- Consumer key
- Consumer secret
- Access token
- Access secret
Python Twitter API (twython)
- Install the twython module with pip (SIMPLE):
pip install twython
- Alternative:
- Download twython from: https://pypi.python.org/pypi/twython
- Unzip and install by:
python3 setup.py install
- Or simply:
easy_install twython
More on Twitter API
- Please refer to Twitter’s developer documentation at: https://developer.twitter.com/en/docs
References
- Python API with JSON: https://www.dataquest.io/blog/python-api-tutorial/
- Chapter 11 Sentiment Analysis of Twitter Data, of Hector Cuesta (2013). Practical Data Analysis. https://ebookcentral-proquest-com.ezproxy2.library.drexel.edu/lib/drexel-ebooks/detail.action?docID=1507840