What is an API?
An API is an Application Programming Interface. An API allows us to ask for data from a website or web service. In more advanced cases, we can also post information — to a web service, such as posting a Tweet or updating Facebook from your own application/website.
The API is basically a set of instructions for how to communicate with a service to either get/post data. It uses special URLs called endpoints.
Most APIs require you to register an account with the service, so they can track how you are using their data, and how often, so they can make sure you’re within the limits of their Terms of Service (TOS). When you register with a website, they will often issue you an API Key that keeps track of how you’re using the service.
<!-- Example using Google Maps API -->
Parts of an API
There are a few terms to be familiar with when working with APIs.
- URI This is the same as URL. There is a subtle technical difference, but for our purposes, they are the same thing.
- Query String This is the part of the URI that is after the question mark, and it has parameter/value pairs, each separate by an ampersand
&. It will look like this:
- URL encoding Replacing characters of a URI, like a colon or slash, in order to put them as part of a query string.
- Endpoint The part of the URI that will specify which type of data you are going to retrieve from the service.
- Token or Key A unique scrambled set of characters to serve as an identifier. Similar to keys, but typically more temporary used in place of a password to gain access to a user’s data.
- OAuth Authentication Open standard to Authentication, a way for users to authorize an application without giving their password. It uses tokens instead, and allows a user to revoke access at any time.
Example using NYTimes API
In this example, we will use the New York Time API to call up some articles. You will need to register for a NYTimes.com account if you don’t have one already.
- Sign in or register for a NYTimes.com account.
- Visit https://developer.nytimes.com/
- Under keys, sign up for a Times Article Search API Key
First, look at the documentation for the NYTimes Article Search API, you will see the following example of the URI you can use to make a request.
Following this example, let’s search for the terms “Barack Obama” sorting the oldest articles first.
#paste the following into a browser with your own API key https://api.nytimes.com/svc/search/v2/articlesearch.json?q=barack+obama&page=0&sort=oldest&api-key=####
This will return a JSON file with multiple results, including articles from 1990 when Obama was first elected as president of the Harvard Business Review.