from IPAs to APIs

Moving from Denver to San Francisco, my interest has shifted rapidly from IPAs to APIs - application programming interfaces. Sounds fancy. APIs offer a level of abstraction when integrating with existing services such as uploading an image with Imgur’s photo upload API or retrieving step by step directions with Mapbox’s directions API. You won’t need to learn the intricate details of how Imgur or Mapbox do what they do, but you must send a complete request and interpret the response.

Simply put, token based authentication consists of 3 steps:

  1. Token: a user requests access, and the application provides a signed token to the user, now called the client.
  2. Request: the client will store the token and send it along with every request
  3. Response: the server will verify the token and respond with data

For this example, I’m using Mapbox’s public access token, but for many APIs, you will request access and use your personal token. For demonstration purposes, let’s pretend the Mapbox public access token is super secret and I don’t want the general public to see it in my git repository.

Create a shell file called secrets.sh and add your secrets that you do NOT want shared in your git repository.

# secrets for your app, this file should never go in your github
export MAPBOX_API_KEY=”pk.eyJ1Ijoiam95Y2VsaW43OSIsImEiOiJjaW8zNzk5bHcwMDA5dzFrcXd6anpnY2xoIn0.ovObS9ODfNsnaa8ie--fKQ”

Add the name of this file to another file called .gitignore. This makes it so you do NOT push the secrets.sh file to your git repository and make your secrets public. Let’s use wildcard formatting to include any file that contains ‘secrets’ in the file name.

*secrets*

Load your secret info into your environment every time you open a new shell environment. This will allow us to call upon this variable in the local, or virtual, environment when needed.

$ source secrets.sh

Now, to the code! In most cases, you can use string formatting to pull in your access token to every server request. Every API will have its own quirks, so it’s important to review the documentation. It’s convention for parameters to follow a question mark (?) and multiple parameters joined by the ampersand (&).

Many APIs will be well documented with explicit data structures and examples, but it’s equally likely that there are errors in the documentation or changes were made without the documentation being updated. With the latter, it’s helpful to use something like the Chrome DevTools to explicitly confirm both the request and response to help troubleshoot errors that arise from handling unexpected data types or variability in data structures.

If you’re ready to take the plunge and ease into the world of APIs, pop open a refreshingly hoppy IPA, and take a peek at this list of common Python API wrappers.