APIs: Why and how

APIs: Why and how

From a simplistic point of view, software can be seen as a combination of operations performed on data. Data comes in, gets processed through a series of functions and some result comes out.

As an example, here is a simple function that computes the area of a circle from its radius as it would be written in JavaScript:

function area_of_circle(radius){
  return Math.PI * radius * radius
}

With this implementation, this function can be used within other parts of the code. For instance, one could later use it to compute the volume of a cylinder as so:

let cylinder_height = 5
let cylinder_radius = 3 

let cylinder_volume = area_of_circle(cylinder_radius ) * cylinder_height 

However, defining a function in this fashion does obviously not make it available to every single piece of software in the world. In fact, the function can only be used within the scope of the application it is part of. Consequenlty, data flow is also bound the the application scope.

In numerous cases, data needs to be exchanged not only within but also between applications. This requires some form of interface for data to leave and enter the scope of their respective application. Such interface is called an application programming interface, or API.

Enabling the exchange of data between multiple applications requires the establishment of communication standards. Currently, the most widespread method to exchange data between applications is the Hyper Text Transfer Protocol, or HTTP. APIs based on HTTP that follow the proper HTTP usage guidelines are called REST APIs.

Practical examples

Now that we've cleared some basic theory about APIs, let's go through some practical examples. Here, we are going to take our area_of_circle function and expose it using a REST API so that other applications can access it.

JavaScript (Node.js)

Applications written in JavaScript and run in Node.js can be made so as to react to HTTP requests using the Express package.

const express = require('express')
const cors = require('cors')

const app = express()
app.use(cors())

// The function to expose outside the scope of the application
function area_of_circle(radius){
  return Math.PI * radius * radius
}

// Have the application listen to requests on the route '/area_of_circle'
app.get('/area_of_circle', (req, res) => {
  
  // req.query contains data passed in the URL of the request
  const area=area_of_circle(req.query.radius)

  // res.send is used to reply to the request
  res.send({area})

})

// Have the server listen on HTTP requests coming on port 8080
app.listen(8080, () => {console.log('Example API listening on PORT 8080'))

This application responds to HTTP GET requests coming on the URL http://<Server IP>:8080/area_of_circle?radius=2 with 12.566370614359172

Python

Applications written in Python can be made to respond to HTTP requests using, for example, Flask. Here is a simple example:

# Importing modules
from flask import Flask, request
from flask_cors import CORS
import math

# Instanciation of the Flask app
app = Flask(__name__)

# Dealing with the Cross Origin Control headers
CORS(app)

# The function to expose
def area_of_circle(radius):
    return math.pi * radius * radius

# Definition of the API endpoint
@app.route('/area_of_circle')
def get_area_of_circle():
    # Getting the data from the query parameters
    # Data is passed as string so it needs to be converted as an integer
    radius = int(request.args.get('radius'))

    # Apply our function
    area = area_of_circle(radius)

    # Respond with the result
    return {"area": area }

# Start listening on port 8080
if __name__ == '__main__':
    app.run('0.0.0.0', 8080)

Here, Flask creates a development server for testing purposes. This kind of server should not be used in production. Please refer to this page.

Consuming REST APIs

Now that we've exposed our circle area computing function via a REST API, we can use it from other applications through API calls. This section presents examples on how to do so

JavaScript (Node.js)

There are multiple ways to perform HTTP requests in JavaScript. Here is an example that uses the Axios library, which is relatively easy to use:

const axios = require('axios')
const URL = 'http://localhost:8080/area_of_circle'

axios.get(URL,{params: {radius: 2}})
  .then(response => console.log(response.data))

Python

In Python, HTTP requests can be done using the built-in requests module as follows:

import requests
URL = 'http://localhost:8080/area_of_circle'
response = requests.get(URL, params={'radius': 2})
print(response.text)