Introduction to APIs


Lesson Objectives

After this lesson, you will be able to…

  • Describe what an application programming interface (API) is and why we might use one.
  • Identify common APIs on the web.
  • Call an API.

Discussion: Web Magic

Have you seen…

  • A website with Google Maps on the page (like Yelp)?
  • A program that had live stock market info?
  • A website that isn’t Twitter but shows a live Twitter feed?
  • Any app that pulls info from somewhere else?

How did they do this?


APIs (Application Program Interfaces)

An API is a service that provides raw data for public use.

APIs give us data, maps, anything!

What’s the API? Sample URL — put this in a new tab!
The Star Wars API: Request R2-D2 info http://swapi.co/api/people/3
Markit Digital’s API: Request current Apple stock info http://dev.markitondemand.com/Api/Quote/xml?symbol=AAPL
OpenWeatherMap: The current weather in London https://samples.openweathermap.org/data/2.5/weather?q=London,uk&appid=b6907d289e10d714a6e88b30761fae22

Do you think you’ve been on websites that call an API?

Does the JSON look unreadable in the browser? If you’re using Chrome, install the JSONView plugin.


How Do We Use an API?

We’ll use the requests module.

This works, but there’s one very helpful line missing!

Before we see this in action, let’s look at what the API might return.


JSON vs. XML

Imagine: You write code for a list.

But then, my_list is unexpectedly a dictionary, or an int, or even a class! The code we wrote won’t work.

APIs can give data back in two ways: JSON or XML. Depending on what the API does, we need to write our program a different way.


How Do APIs Give Us Info? Option 1: JSON

Here’s a potential return from an API:

Looks like a dictionary with a list of dictionaries inside it, right?

But it’s not a dictionary! It’s JSON (JavaScript Object Notation).

The requests module has a built-in JSON decoder to turn JSON into a Python dictionary.

We can decode JSON with decoded_data = response_from_request.json().


How Do APIs Give Us Info? Option 2: XML

Instead of JSON, we might get XML:

JSON is certainly easier to read!

  • We’ll stick with JSON whenever we can.

Pro tip: Most of you don’t need to know about XML, but if you’re working with legacy code or an older API, you may have to use it. In that case, look up Element Tree XML.


Let’s Choose an API

To recap: APIs give us data we can use in either XML or JSON.

Let’s call one!

Check out http://api.open-notify.org/astros.json, which tells us the people currently aboard the International Space Station (ISS).


Calling an API

  • Import the request module.
  • Call the API (requests.get()).
  • Parse the response with response.json().

You Do: Calling an API

Open a new file, my_api.py. Type and run the code:


We Do: A New API

Awesome! Go back to your file. Let’s instead call this URL:

http://dev.markitondemand.com/Api/Quote/xml?symbol=AAPL

Why does it break? We can’t parse XML like JSON.


Quick Review

We’ve called an API! Great job. We did this with the get() function in the requests module. APIs are made available by other websites or applications. They give us data we can use in either XML or JSON.

JSON:


Quick Review

XML:


You Do: Back to JSON

Back in your file, change the API call back to http://api.open-notify.org/astros.json.

Once it’s decoded, it’s a dictionary!

Replace your print statement:

Can we go further? Try to only print the names of the astronauts.


Name Printing: Solution

Working backward, we have a:

  • Dictionary (key: name).
  • Which is inside a list (the value of people).
  • Which is inside a dictionary (key: people).
For message the value is success.

For people the value is [{'craft': 'ISS', 'name': 'Oleg Artemyev'}, {'craft': 'ISS', 'name': 'Andrew Feustel'}, .....].

For number the value is 6.

You Do: Shakespeare

In your file, call the Shakespeare API http://ShakeItSpeare.com/api/poem.

Print only the poem.


Shakespeare: Solution

Print only the poem.


Quick Review

When we convert JSON, it keeps the same format, only in a Python structure.

When parsing an API’s return, look through the JSON to find the exact structure you need. Is it the string value from the poem key? Or the value from each name key in a list of dictionaries, which is the value of the people key?

Think it through before writing your code.


I Do: API Authentication

Many APIs are free but require a key. This identifies the developer requesting access.

If we call the Giphy API:

  • With no key, http://api.giphy.com/v1/gifs/search?q=funny+cat, we get Error - Unauthorized!

  • With a key, http://api.giphy.com/v1/gifs/search?q=funny+cat&api_key=dc6zaTOxFJmzC, it works!


I Do: API Authentication

Syntax Notes:

  • The main API URL is http://api.giphy.com/v1/gifs/search.
  • ? always delineates a URL and its parameters.
    • (The ? is a standard for every URL! Searching Google for “banana,” with q short for “query:” https://www.google.com/search?q=banana).
    • (Here’s another one! Searching Amazon for “banana:” https://www.amazon.com/s?field-keywords=banana.)

Most importantly, never publish your key for a backend service, including on GitHub! (This is an example.) There are other ways to provide your key to a server in order to keep that key safe. However, if your code is using JavaScript, that’s ok as that provides only read access in general (assuming you have your permissions properly configured.) This is a sticking point for developers coming to Python from a front-end perspective.


You Do: OpenWeather API

Read about the API here.

Use this key: &appid=052f26926ae9784c2d677ca7bc5dec98.

Call this URL: http://api.openweathermap.org/data/2.5/weather?zip=<ZIP_CODE_HERE>,us&appid=052f26926ae9784c2d677ca7bc5dec98.

Note the parameters:

  • zip=<ZIP_CODE_HERE>
  • appid=<KEY HERE>

Enter any zip code you choose (e.g., 60614).

  • Display the current temperature, high and low temperature, current weather description, and the name of the city that came back from the API.

OpenWeather API Solution


Summary

APIs:

  • Handy URLs from which we can get information.
  • Sometimes require keys.
  • Usually free.
  • Call with the requests() module.

XML and JSON:

  • Two formats in which APIs might return information to us.
  • XML is legacy.
  • JSON looks like a dictionary.

Additional Resources