Understanding the Application Programming Interface. (APIs)

Jenny Zalwango
Jenny’s Tech Blog
7 min readApr 9, 2019
Photo by Fernando Hernandez on Unsplash

Application Programming Interface is a software intermediary that allows two applications to communicate with each other. Basically, an API specifies how software components should interact. In a lay man’s term, an API is a messenger that delivers your request to a service provider and then delivers a response back to you.

Before we go any further let’s dive into knowing the difference between Web Services and Web APIs.

Web Services only support the HTTP protocol and are Simple Object Access Protocol SOAP-based which return data as Extensible Markup Language XML. Web services require a SOAP protocol to receive and send data over the network, so it is not a light-weight architecture.

Web APIs are an HTTP based service that supports the HTTP protocol and returns JSON or XML data. It can be hosted within an application or Internet Information Services (IIS). Both web services and web APIs are used for communication.

How do APIs work?

Imagine you are working with your machine, and as you are still working your battery warns that you need to connect your machine to the power source, right? So you have your power source and your machine, but there is no way your machine will enter into the power source!

You will need a medium of communication between your machine and the power source. That’s where the charger — or the API — enters the picture. You will connect your charger to the power source then your machine will charge.

A real example of an API

How are APIs used in the real world? Here’s a very common scenario — Ordering food Online.

When you search for food online, you have a menu of options to choose from. You choose an online shop to use, the kind of food they have, the orders you can make and what you want as a person.

To make your order you will need to interact with the online shop’s website to access their database to see if any of the orders you want to make are available at that particular time, and how much it would cost.

You need access to that information from the shop’s database, whether you’re interacting with it from the website or an online shop service that aggregates information from multiple shops. Alternatively, you might be accessing the information from a mobile phone. In any case, you need to get the information, and so the application must interact with the shop’s API, giving it access to the shop’s data.

The API is the interface that, like your helpful charger, runs and delivers the data from the application you’re using to the online shop’s systems over the Internet. It also then takes the shop’s response to your request and delivers right back to the shop’s application you’re using e.g Jumia, Amazon. Moreover, through each step of the process, it facilitates the interaction between the application and the online shop’s systems — from order selection to placing the order, payments, and delivery.

Photo by Fatos Bytyqi on Unsplash

How to develop an API?

One may be wondering if the above magic of APIs is developed by humans Yes!!! it let’s dive into it.

Developers develop APIs using different languages like;

  • Javascript
  • Java
  • Python and so on…..

Let’s talk about developing APIs in python. Python has got over ten different web frameworks like Flask, Django, Web2py, TurboGears and so on, But we will look at Flask.

Flask is a Python microframework which supports both function based and method based views. Let's look at method views based on classes instead of functions this makes it simpler to develop an API. As we go further please ensure that python 3.5 and above is installed on your machine for you to have a better flow of this.

Hoping that you have a text editor on your machine lets look at the some of the things we need clearly to kick off;

  • Flask
pip install flask.

This helps to keep dependencies required by different projects. Different operating systems have different ways of creating virtual environments. This below is for Linux users

To create one,

python3 -m venv [the name of the virtual environment you want].
  • then activate it by running
source [the name of the created enviromnet]/bin/activate

PostgreSQL is a powerful, open source object-relational database system that uses and extends the SQL language combined with many features that safely store and scale the most complicated data workloads.

These are variables that are set up in your shell or terminal when you log in. These are set locally on your machine and they are used to store temporary values for reference later in a shell script. A running program can access the values of environment variables for configuration purposes. The environment variables, in this case, are and are put in the config file.

1. Development environment.
2. Testing environment.
3. Production environment.

Let’s look at the folder structure to use. You will create a directory that will include your application we will look at developing an API in a flask and storing our data in the database using Postgres SQL.

You create the application module that will hold all the other submodules for the application, for example, the models, views and the routes.

  • Models

In the models, this is where your class is instantiated, you remember to include an __init__.py file. This file is included in every subfolder which and its importance is to tell python to recognize that folder as a python package. This is done to prevent directories with a common name, such as string, from unintentionally hiding valid modules that occur later (deeper) on the module search path.

  • Views

While dealing with methodViews in the flask, in your views, each HTTP method maps to a class with the same name (just in lowercase). The trick is to take advantage of the fact that you can provide multiple rules to the same view.

class UserAPI(MethodView):

In the code snippet above we create a class called UserAPI which inherits from MethodView. We then create different functions under the same class and the functions will have the main HTTP verbs for example GET, POST, DELETE, PUT. Basically, there are so many HTTP verbs but you choose what is convenient for you depending on what you want to do, and so for this case, we will use the one in the code snippet above

def get(self, user_id):
if user_id is None:
# return a list of users
pass
else:
# expose a single user
pass

In the code snippet above, we create a function with an HTTP verb get which takes two parameters self and the user_id. Self is used to represent the instance of the class and by using the “self” keyword we can access the attributes and methods of the class in python. Note when using methodViews you can use one get HTTP verb to do all the gets, for example, get one order or get all orders that is why we are also specifying the user_id in the second parameter. In case the user_id is none it will return a list of all users else returns a single user.

We go and create a function with an HTTP verb post which takes only one parameter and that’s the self. The post request method is used when requesting a web server to accept the data enclosed in the body of the request message. This is used to create a new user.

def post(self):# create a new userpass

Let’s we go on to creating a method that will help us delete a user and this function takes in two parameters the ‘’self ‘’ as we talked about its importance when explaining the get and the user_id will be needed since we have to specify which user we are to delete hence using the user id because we wouldn’t want to delete anyhow since it will end up crashing the application

def delete(self, user_id):# delete a single user

pass

Just like the delete, Put also takes the same parameters although it works differently. The Put method requests that the enclosed entity be stored under the supplied Request-URI. If the Request-URI refers to an already existing resource, the enclosed entity should be considered as a modified version of the one residing on the origin server.

def put(self, user_id):# update a single userpass
  • routes

In routes, this is where we put the URLs.this is so how do we hook this up with the routing system when dealing with method views. When this is done you are good to go.

user_view = UserAPI.as_view('user_api')app.add_url_rule('/users/', defaults={'user_id': None},view_func=user_view, methods=['GET',])app.add_url_rule('/users/', view_func=user_view, methods=['POST',])app.add_url_rule('/users/<int:user_id>', view_func=user_view,methods=['GET', 'PUT', 'DELETE'])

Then you get to run your application, depending on your file name lets say the file name is called run.py.Our command will be;

python run.py

In conclusion, APIs are just containers that contain some information two applications use to communicate with each other they can be developed in different languages and consumed by anyone.

--

--

Jenny Zalwango
Jenny’s Tech Blog

A Long-life learner passionate about solving real-world problems using tech.