X
Popular Searches

What is an “API”, and How Do You Use One?

API image
Andrey Suslov/Shutterstock

An “API” is the middleware that sits in between two applications, and allows them to communicate using predefined rules. In practice, APIs are typically used to allow client-side applications to access an otherwise protected database.

What Do APIs Do?

At a high level, APIs simply establish communication between two applications. They can’t communicate directly, since they don’t have access to each other’s code, so they have to run a wire between them and send signals down the line. The API defines how those signals should be sent. Nearly every application running on your computer uses an API of some sort to talk to thousands of other things.

In practice, the term “API” is commonly used to refer to web-based APIs that form the link between server and client, or between server and a backend service. These APIs act as the access point for whatever service is behind them.

For example, imagine you have a client side application that needs to talk to a server with a database. You obviously can’t give the client full access to the database, as this presents a number of issues. First of all, it’s probably the worst security mistake you could make, but besides that, it also breaks the whole client-server model. The client should not have to worry about talking to a database or storing data; it should communicate with the server and let the server do the heavy lifting.

Instead of allowing the client full access, you can create another service that will talk to the database on behalf of the client. This is the API application, and it sits directly in front of the database (or whatever other service is behind it).

The client sends requests to the API application, typically over HTTP using GET and POST requests. This may be a URL on your server, such as “api.yoursite.com.” If the client wanted search the database with a specific query, the API would ask the database to perform the search, and then return the results. Usually, APIs communicate over JSON, which returns the results as an object with strictly defined types, for example:

{
  "name": "MyAPI",
  "search_results": [...]
}

This is another benefit of APIs—standardizing the structure of data. Your API should always return the same format and type of data every time, which makes it easy to utilize it in different applications. Most major tech companies have publicly available APIs, and extensive documentation on the structure of the API and how it is used.

How Do I Use An API?

APIs are fairly standardized. They will almost always be accessible over HTTP, and usually return JSON data, meaning any programming language that can make HTTP requests and decode JSON can talk to an API and get data from it. Even something as simple as curl or wget that can download web-based content can access an API.

You can make use of publicly available APIs in any application you want, though they are sometimes rate limited to prevent abuse. For example, KeyCDN runs an API for getting location information from an API address, but you’re limited to three requests per second. You can use this in any application by making an HTTP GET request to the API endpoint with the IP address passed as a URL parameter. For example:

https://tools.keycdn.com/geo.json?host={IP_ADDRESS}

Would return something like:

{
  "status": "success",
  "description": "Data successfully received.",
  "data": {
    "geo": {
      "host": "173.79.254.254",
      "ip": "173.79.254.254",
      "rdns": "pool-173-79-254-254.washdc.fios.verizon.net",
      "asn": 701,
      "isp": "MCI Communications Services, Inc. d/b/a Verizon Business",
      "country_name": "United States",
      "country_code": "US",
      "region_name": "Virginia",
      "region_code": "VA",
      "city": "Alexandria",
      "postal_code": "22309",
      "continent_name": "North America",
      "continent_code": "NA",
      "latitude": 38.719,
      "longitude": -77.1067,
      "metro_code": 511,
      "timezone": "America/New_York",
      "datetime": "2019-08-22 17:30:48"
    }
  }
}

You could store this result in a variable named response. Then, if you wanted to know the ZIP code of the address, you could access that by using response.data.geo.postal_code.

There are libraries for most languages that make this process easier, and many languages have built in tools as well. We’ll show a few common ones, but a quick search for  “___ HTTP Request” should display results for the language you’re working with.

JavaScript

JavaScript can make HTTP requests out of the box using the XMLHttpRequest() object:

const Http = new XMLHttpRequest();
const url='https://api.github.com/';
Http.open("GET", url);
Http.send();

Http.onreadystatechange = (e) => {
  console.log(Http.responseText)
}

However, this syntax is quite clunky, so it’s commonly handled using other libraries unless you strictly need vanilla JS. For example, jQuery has the ajax method which takes care of this:

$.ajax('https://api.github.com/', {
    dataType: 'json',
    success: function (data, status, xhr) { ... }
});

And there is the axios library, which handles it using promises:

axios.get('https://api.github.com/')
  .then((data) => {
    console.log(data);
  }
)

In any case, JSON objects can deserialize directly to JavaScript objects using JSON.parse(), which will allow you to store the results for use elsewhere.

PHP

PHP can make GET requests natively by using the file_get_contents function, which can be used alongside json_decode to read the API result into a variable:

$json = file_get_contents('https://api.github.com/');
$obj = json_decode($json);

If you want to make a POST request, or need extra configuration, you can create a special context for file_get_contents using stream_context_create:

$url ='https://api.github.com/';
$data = 'something';

$options = array(
  'http' => array(
    'header' => "Content-type: application/x-www-form-urlencoded\r\n",
    'method' => 'POST',
    'content' => http_build_query($data)
  )
);

$context = stream_context_create($options);
$result = file_get_contents($url, false, $context);
if ($result === FALSE) { //error }

Python

Python doesn’t have a great way to do this natively, so you’ll have to install the requests library from pip.  After that, you can make requests like so:

import requests
r = requests.get("https://api.github.com/")

This returns an object representing the entire HTTP transaction, so to get the actual content you’ll have to use r.content. You’ll likely also need the JSON library to decode the response into a Python-readable object.

import json
import requests
r = requests.get("https://api.github.com/")
decoded = json.loads(r.content)

How Do I Make My Own Web API?

If you’ve got some data that you’d like to make available, you can put an API in front of it to access it over the Internet.

To do this, you’ll need to create an API server. The only requirement is that it can listen over HTTP and respond to requests, so you can use any programming language you like. You’ll likely also need a library for connecting to your database of choice from that language, and you may also want to implement some sort of authentication like OAuth 2.0 so you can keep track of users and their permissions.

Express is a Node.JS library commonly used to make simple web APIs using JavaScript. The Express server listens over HTTP and is able to forward different routes to handler functions. You can use this alongside a Node MySQL client (or any other database) to make data-rich APIs. For Python, you’ll similarly need a web framework like Flask that can listen and respond to requests.

Anthony Heddings Anthony Heddings
Anthony Heddings is the resident cloud engineer for LifeSavvy Media, a technical writer, programmer, and an expert at Amazon's AWS platform. He's written hundreds of articles for How-To Geek and CloudSavvy IT that have been read millions of times. Read Full Bio »

The above article may contain affiliate links, which help support CloudSavvy IT.