More API Examples

This notebook contains EVEN MORE API examples so you can get an idea of the types of services available. There's a world of API's out there for the taking, and we cannot teach them all to you. We can only teach you how they work in general... the details are 100% up to you!

You should get your own API keys as appropriate. No guarantees my keys will work for you

Caller Id/ Get a location for a Phone number

This uses the cosmin phone number lookup API as found on https://market.mashape.com/explore

This api requires headers to be passed into the get() request. The API key and the requested output of json are sent into the header.

Enter a phone number as input like 3154432911 and then the API will output JSON data consisting of caller ID data and GPS coordinates.


In [1]:
import requests

phone = input("Enter your phone number: ")
params = { 'phone' : phone }
headers={ "X-Mashape-Key": "sNi0LJs3rBmshZL7KQOrRWXZqIsBp1XUjhnjsnYUsE6iKo14Nc",
    "Accept": "application/json" }
response = requests.get("https://cosmin-us-phone-number-lookup.p.mashape.com/get.php", params=params, headers=headers )

phone_data = response.json()
phone_data


Enter your phone number: 3154439696
Out[1]:
{'phone_number': {'npa': '315', 'nxx': '443', 'xxx': '9696'},
 'opencnam': 'Please use "opencnam-sid" and "opencnam-auth-token" to see OpenCNAM results.',
 'type': 'Landline',
 'city': 'Syracuse',
 'state': 'New York',
 'latitude': 43.051,
 'county': 'Onondaga',
 'longitude': -76.1481,
 'time_zone': 'Eastern (GMT -05:00)',
 'cbsa_code': '45060',
 'carrier': 'Verizon New York Inc.'}

Get current exchange rates

This example uses http://fixer.io to get the current currency exchange rates.


In [2]:
import requests
apikey = '159f1a48ad7a3d6f4dbe5d5a71c2135c' # get your own at fixer.io
params = { 'access_key': apikey } # US Dollars
response = requests.get("http://data.fixer.io/api/latest", params=params )
rates = response.json()
rates


Out[2]:
{'success': True,
 'timestamp': 1584617946,
 'base': 'EUR',
 'date': '2020-03-19',
 'rates': {'AED': 3.947085,
  'AFN': 82.199509,
  'ALL': 121.066357,
  'AMD': 530.100983,
  'ANG': 1.935688,
  'AOA': 544.066073,
  'ARS': 67.949712,
  'AUD': 1.878476,
  'AWG': 1.934215,
  'AZN': 1.823789,
  'BAM': 1.9267,
  'BBD': 2.183509,
  'BDT': 91.732693,
  'BGN': 1.950031,
  'BHD': 0.405764,
  'BIF': 2041.744735,
  'BMD': 1.074564,
  'BND': 1.556017,
  'BOB': 7.445371,
  'BRL': 5.487584,
  'BSD': 1.081411,
  'BTC': 0.000192,
  'BTN': 80.262285,
  'BWP': 12.626192,
  'BYN': 2.66444,
  'BYR': 21061.447303,
  'BZD': 2.179844,
  'CAD': 1.56572,
  'CDF': 1833.205526,
  'CHF': 1.053862,
  'CLF': 0.034153,
  'CLP': 942.288688,
  'CNY': 7.651326,
  'COP': 4468.035606,
  'CRC': 612.38276,
  'CUC': 1.074564,
  'CUP': 28.475936,
  'CVE': 108.620245,
  'CZK': 27.576204,
  'DJF': 190.971384,
  'DKK': 7.472849,
  'DOP': 58.081406,
  'DZD': 131.840287,
  'EGP': 16.920687,
  'ERN': 16.118838,
  'ETB': 35.45797,
  'EUR': 1,
  'FJD': 2.505455,
  'FKP': 0.931042,
  'GBP': 0.930712,
  'GEL': 3.320642,
  'GGP': 0.931042,
  'GHS': 6.141841,
  'GIP': 0.931042,
  'GMD': 54.696895,
  'GNF': 10318.115812,
  'GTQ': 8.270762,
  'GYD': 225.505882,
  'HKD': 8.342536,
  'HNL': 26.758929,
  'HRK': 7.606812,
  'HTG': 102.525858,
  'HUF': 358.098009,
  'IDR': 17139.290024,
  'ILS': 3.946439,
  'IMP': 0.931042,
  'INR': 80.825989,
  'IQD': 1291.011165,
  'IRR': 45244.502239,
  'ISK': 152.297885,
  'JEP': 0.931042,
  'JMD': 146.3324,
  'JOD': 0.761904,
  'JPY': 117.968847,
  'KES': 112.872294,
  'KGS': 78.331472,
  'KHR': 4370.069358,
  'KMF': 488.335403,
  'KPW': 967.147847,
  'KRW': 1377.848381,
  'KWD': 0.334716,
  'KYD': 0.901216,
  'KZT': 479.699726,
  'LAK': 9620.111563,
  'LBP': 1635.35111,
  'LKR': 200.817902,
  'LRD': 212.76358,
  'LSL': 18.386092,
  'LTL': 3.172907,
  'LVL': 0.649993,
  'LYD': 1.496445,
  'MAD': 10.446257,
  'MDL': 19.298128,
  'MGA': 4037.750993,
  'MKD': 61.273646,
  'MMK': 1545.363925,
  'MNT': 2972.541417,
  'MOP': 8.649924,
  'MRO': 383.619548,
  'MUR': 42.444614,
  'MVR': 16.549267,
  'MWK': 795.434861,
  'MXN': 26.203341,
  'MYR': 4.744205,
  'MZN': 71.227467,
  'NAD': 18.407231,
  'NGN': 394.365226,
  'NIO': 36.479113,
  'NOK': 12.304232,
  'NPR': 128.430643,
  'NZD': 1.897109,
  'OMR': 0.413604,
  'PAB': 1.081469,
  'PEN': 3.832393,
  'PGK': 3.745703,
  'PHP': 55.367431,
  'PKR': 172.109677,
  'PLN': 4.584315,
  'PYG': 7116.897081,
  'QAR': 3.912494,
  'RON': 4.843277,
  'RSD': 117.524788,
  'RUB': 87.214798,
  'RWF': 1029.473228,
  'SAR': 4.041478,
  'SBD': 8.884484,
  'SCR': 14.724514,
  'SDG': 59.421471,
  'SEK': 11.203917,
  'SGD': 1.563227,
  'SHP': 0.931042,
  'SLL': 10436.697016,
  'SOS': 630.768478,
  'SRD': 8.01406,
  'STD': 23697.107196,
  'SVC': 9.463364,
  'SYP': 553.399006,
  'SZL': 18.425285,
  'THB': 35.101678,
  'TJS': 10.533457,
  'TMT': 3.760973,
  'TND': 3.133965,
  'TOP': 2.571162,
  'TRY': 7.030424,
  'TTD': 7.306867,
  'TWD': 32.767207,
  'TZS': 2476.440087,
  'UAH': 29.536314,
  'UGX': 4087.337156,
  'USD': 1.074564,
  'UYU': 48.080386,
  'UZS': 10290.177228,
  'VEF': 10.732205,
  'VND': 24978.769044,
  'VUV': 133.999445,
  'WST': 3.055009,
  'XAF': 646.205049,
  'XAG': 0.089581,
  'XAU': 0.000726,
  'XCD': 2.904062,
  'XDR': 0.790288,
  'XOF': 646.222821,
  'XPF': 117.48483,
  'YER': 268.959563,
  'ZAR': 18.686557,
  'ZMK': 9672.358796,
  'ZMW': 17.924532,
  'ZWL': 346.009492}}

GeoIP lookup: Find the lat/lng of an IP Address

Every computer on the internet has a unique IP Address. This service when given an IP address will return back where that IP Address is located. Pretty handy API which is commonly used with mobile devices to determine approximate location when the GPS is turned off.


In [3]:
import requests
ip = "128.230.182.170"
apikey = 'f9117fcd34312f9083a020af5836e337' # get your own at ipstack.com
params = { 'access_key': apikey } # US Dollars
url = f"http://api.snoopi.io/{ip}"
response = requests.get( url, params=params )
rates = response.json()
rates


Out[3]:
{'ip': '128.230.182.17',
 'type': 'ipv4',
 'continent_code': 'NA',
 'continent_name': 'North America',
 'country_code': 'US',
 'country_name': 'United States',
 'region_code': 'NY',
 'region_name': 'New York',
 'city': 'Syracuse',
 'zip': '13224',
 'latitude': 43.03828048706055,
 'longitude': -76.10877227783203,
 'location': {'geoname_id': 5140405,
  'capital': 'Washington D.C.',
  'languages': [{'code': 'en', 'name': 'English', 'native': 'English'}],
  'country_flag': 'http://assets.ipstack.com/flags/us.svg',
  'country_flag_emoji': '🇺🇸',
  'country_flag_emoji_unicode': 'U+1F1FA U+1F1F8',
  'calling_code': '1',
  'is_eu': False}}

An API for sentiment analysis...

Process some text and more here: http://text-processing.com


In [4]:
# sentiment
message = input("How are you feeling today? ")
url = 'http://text-processing.com/api/sentiment/'
options = { 'text' : message}
response = requests.post(url, data = options)
sentiment = response.json()
print(sentiment)


How are you feeling today? very sad
{'probability': {'neg': 0.7177103703784351, 'neutral': 0.0723048266852646, 'pos': 0.28228962962156484}, 'label': 'neg'}

Searching iTunes

Here's an example of the iTunes search API. I'm searching for "Mandatory fun" and printing out the track names.


In [5]:
term = 'Mandatory Fun'
params = { 'term' : term }
response = requests.get('https://itunes.apple.com/search', params = params)
search = response.json()
for r in search['results']:
    print(r['trackName'])


Foil
Sports Song
Word Crimes
NOW That's What I Call Polka!
Lame Claim to Fame
Inactive
Handy
Tacky
Mission Statement
Jackson Park Express
First World Problems
My Own Eyes
Mandatory Fun
Mandatory Fun
Mandatory Fun
Mandatory Fun
Cash
Good as Gone
Take Me Home
Down
Fool's Gold
Believe
Heaven Help Me
The Truth
Spinning Round
Country Soul
Air Traffic Control
Boom Spider
Jack Shit
Sad Horse
Dance in the Moonlight
Strawberry Jam
Spruce Willis
Koala
On the Hillside
Spib
Waterfall
On a Rock
Drinks In the Air (feat. Mack)
Mandatory Fun Day
Heaven on Earth

Earthquakes anyone?

Here's an example of the significant earthquakes from the past week. Information on this API can be found here:

http://earthquake.usgs.gov/earthquakes/feed/v1.0/geojson.php


In [6]:
response = requests.get('https://earthquake.usgs.gov/earthquakes/feed/v1.0/summary/significant_week.geojson')
quakes = response.json()
for q in quakes['features']:
    print(q['properties']['title'])


M 5.2 - 15km W of Petrolia, CA
M 4.6 - 5km NE of Magna, Utah
M 6.2 - 246km S of Kangin, Indonesia
M 4.5 - 7km NNE of Magna, Utah
M 5.7 - 6km NNE of Magna, Utah
M 6.3 - 298km NE of Raoul Island, New Zealand

Spotify

The spotify example shows you how to call an API which uses the OAUTH2 prococol. This is a two step process. The first request, you request a token, and in the second request you call the api with that token. Twitter, Facebook, Google, and many other services use this approach.

Typically you will use the client credentials flow, which does not explicitly require the user to consent. https://developer.spotify.com/documentation/general/guides/authorization-guide/

API's that use this approach will issue you a client id and a client secret. The id is always the same but the secret may be changed.

We use that client id and client secret to get an bearer access token. Notice how we pass into the post a named argument auth= which authenticates with the client id/secret.

Next we use the bearer access token to make subsequent calls to the api.


In [ ]:
from base64 import b64encode
# USE YOUR OWN CREDENTIALS THESE ARE EXAMPLES
client_id = "413fe60240a7ad1881bcca301a345"
client_secret = "f6eae3c49a8a9a5c82cb00cfb153"

# Step one, get the access token
payload = { 'grant_type' : 'client_credentials'}
response = requests.post("https://accounts.spotify.com/api/token", auth=(client_id,client_secret),data=payload)
token = response.json()['access_token']
print(f"Access token: {token}")

# Step two and beyond, use the access token to call the api
url = "https://api.spotify.com/v1/tracks/2TpxZ7JUBn3uw46aR7qd6V"
header = {"Authorization" : f"Bearer {token}"}
response = requests.get(url, headers=header)
response.json()