What is a web API… and how can I create one with Python?

Prince Igwenagha
8 min readFeb 23, 2022

We hear it every time… the meaning of “API” is Application Programming Interface; but what exactly is an API? What is it all about?

So many people give their own description of what an API is. The first scenario that gave me an idea of what it is (of which it is still popular today in programming memes), is the idea of a restaurant. The customer, which is the frontend client wants to have something to eat, which can be seen as the resource. This resource is gotten from some back-end logic code or some database, which is the chef or the cook in this case. Then there’s the waiter, always ready to serve and deliver (at least most of the time, but not where I’m from. You get your food yourself ). The waiter here is the API. Now, the waiter approaches the customer with the menu, and the customer makes a request on any food choice. The waiter, takes this request to the chef(back-end architecture), the chef makes the food(data) ready, and passes it to the waiter(API), which gives the food(response in this case), back to the customer(frontend client).

So basically, the API is some type of communication point between the front-end(customer) and the back-end(chef) worlds.

Another scenario I was able to come up with is(disclaimer: I’m not some electrical engineering geek, so I may be wrong here)… with the idea of wall sockets, right? Electricity is created, and made ready for us to use. Now we have our gadgets we use everyday, that needs to be powered, at least daily. But without these wall sockets, we can’t use the electricity. So I see the API as the wall socket, that connects to the electricity(back-end point), and passes that current to the “external world”, which makes it possible to charge our gadgets…Yeah. I think we get the point now.

In today’s tech era, most applications, if not all, depend on APIs. This is because millions of data is transferred from one point to another every second, and these data needed to be readily available at any point in time. We use APIs everyday, even though we don’t know we use them. We use them when we check our bank account balance, when we watch YouTube videos or post tweets, even in our weather apps. APIs are everywhere.

Types of web APIs architecture:

  • Remote Procedure Call(RPC)
  • Representational State Transfer(REST)
  • SOAP
  • gRPC
  • GraphQL

(Now, to be honest, it is only the REST architecture I have worked with. **whispers “disappointment”. I may try out GraphQL next).

So, what is a REST API ? A REST API is an API that follow the guidelines of the REST architecture. The REST architecture is one, whose main purpose is to transfer data from one component to another, with some level of manipulation. This guideline was defined by Roy Fielding. For an API to be called a REST(ful) API, it has to follow certain guidelines, which are:

  1. Client-Server Communication
  2. Statelessness
  3. Cacheable
  4. Uniform interface
  5. Layered systems
  6. Code on demand

You can read up on these concepts here.

In REST API, communication is between the client and the server. This client sends a request for specific resource data to the server, through an endpoint (API resource URL), the server fetches the data from database, and sends it to the client as a response. For communication between the client and the server through the endpoint, there are HTTP methods. These methods specify the type of action that should be executed in a request. There are many HTTP methods, but the most popular ones look like the CRUD(Create Read Update Delete) operations; they are:

POST = The method used to create a new resource with a unique ID (Create)… (Note: Wherever you see “resource”, it is “data”. Don’t get confused)

GET = The method used to get a group of objects from an endpoint (Read).

GET(id) = The method used to get a specific resource based on its ID.

PUT = It is used to update or edit an existing resource.

DELETE = The method is used to delete a specific resource based on its ID.

When these methods are sent with a request, the server responds with the necessary response status code. These status codes are classified into five groups:

  1. Informational codes: Tells us that the request was received.
  2. Success codes: Tells us that whatever action we wanted to do, was executed successfully.
  3. Redirection codes: There was a URL redirection in our request.
  4. Client error codes: They throw error messages based on what the client is doing wrong.
  5. Server error codes: These are codes that show up because of an error from the server-side. It can be a bug in the code.

There are a lot of HTTP status codes out there, like… A LOT. But if you want to checkout every single one, you can find them here.

Now we have a basic idea of a REST API… how do we create one?

In as much as the topic is on creating one with Python, APIs can be created with almost any programming language we can think of; Java, JavaScript, Kotlin, PHP, Go, HTML… no, not HTML, but you get the point. If it can be used in back-end web development, then it can create an API.

CREATING AN API WITH PYTHON

We already know that Python is a general purpose programming language, meaning it can be used to create almost any type of project. An API can be created with Python, from scratch. But there are frameworks that makes it easier for us. The most popular ones are Django( Django Rest Framework ), Flask( Flask-RESTful ), and FastAPI.

We will be creating on with Django Rest Framework. Our scope of API is a gallery web-based API, whereby we can save (post/edit) pictures, view them whenever we want, and delete too.

To get the complete code, you can clone the repo from the url.

Django Rest Framework is a package that can be used to create RESTful APIs in Python. The package can be installed with a simple command like ‘pip install djangorestframework’ or ‘pipenv install djangorestframework’, (depending on which package manager you are using) in your django project folder. This should be done after install Django web framework, and creating the actual Django project.

$ mkdir <DRFproject_folder>$ cd <DRFproject_folder>$ pipenv install Django$ django-admin startproject DjngoImgAPI .$ pipenv install djangorestframework$ python manage.py startapp images

Django Rest Framework is a 3rd party app, so it should be included in the “INSTALLED_APPS” list as “rest_framework”, with newly created images app.

Django Rest Framework and images app in INSTALLED_APPS list.

This makes it possible for you to call libraries in the package. This Images app for the image resource can be created after this and too added to the apps’ list as shown above.

We should not forget about the image app url that’s to be added to the urls.py file of the Django project, along with the rest_framework ‘s url.

Rest Framework and Images apps added to the project URL patterns.

(Yeah, you’re to create a urls.py file in the images app, and it should be similar to what is below..)

# images/urls.py
from django.urls import path
app_name=”images”urlpatterns = []

By doing these, any URL path added to the images/urls.py will be registered in the Django application.

We can go ahead and create the Image model for our image resource.

Image model that represents image resource.

(You can decide to add your own image properties…)

Then we make our migrate our model.

$ python manage.py makemigrations$ python manage.py migrate

This should migrate your Image model along with other migrations, if you didn’t migrate at the start of the project.

The upload_to=’media/’ of the image property of the Image model, specifies where our image files will be stored, when we make our requests in our local server. You can set this up by doing the following:

$ mkdir media

Then in the settings.py file:

Media path setup.

Up next, create the serializers. The serializers make it possible to transfer our image data in a suitable format, to be used in any client application. We can serialze our image data with the rest framework serializers library. A serializers.py file should be created in the images app.

Serializer class in serializers.py

Now, we create the VIEWS of the API (*** exhales in a meditative posture). These views are what we used to specify HTTP methods for our image resources. I see the API views as the normal views you create when working on an ordinary Django application. There are different types of API views in the Django Rest Framework. There are Class-based views, Function-based Views, Generic Views, and Viewsets. I wouldn’t decide on the best type of view to use, it just depends on your taste and how you want to structure your code. So below, I used the Generic Views.

• CreateAPIView (HTTP POST)

• DestroyAPIView (HTTP DELETE)

• ListAPIView (HTTP GET)

• ListCreateAPIView (HTTP GET | POST)

• RetrieveAPIView (HTTP GET{id})

• RetrieveDestroyAPIView (HTTP GET{id} | DELETE{id})

• RetrieveUpdateAPIView (HTTP GET{id} | PUT{id})

• RetrieveUpdateDestroyAPIView (HTTP GET{id} | PUT{id} | DELETE{id})

  • UpdateAPIView (PATCH{id})
Defined API views in images.views.py

The parser_classes allows you to accept requests with various media types. In this case we use the MultiPartParser which supports file uploads (since we would be uploading an image with a POST request).

(And then we move to the end of points, endpoints…pun intended) These are basically just the URL paths that will be used to make HTTP requests, nothing serious. So how do we create them?… Yes, in the urls.py file of the images app.

Defined endpoints in images.urls.py

Just like in the normal Django project 🙂

Now paste the endoints in your favourite API client [mine is Insomnia 🚫 😴] and try them out.

GET request on endpoint

To add some query parameters for swag to your work, we can use the django-filter 3rd party app for filtering field values in our API:

$ pipenv install django-filter

The following should be done in the settings.py file.

REST_FRAMEWORK = {‘DEFAULT_FILTER_BACKENDS’: [‘django_filters.rest_framework.DjangoFilterBackend’] # the filter back-end
}

Then in our Image API View:

class ImageListCreate(ListCreateAPIView): # POST/GET methods
queryset = Image.objects.all()
serializer_class = ImageSerializer
parser_classes = [MultiPartParser] # to accept any media type during POST request
filterset_fields = [‘title’, ‘caption’] ## the filter feature for filtering fields

Then query the edpoint by adding the query parameters after a “?

0.0.0.0:8000/images/list-images?title=Banana…(Note: 0.0.0.0 is my set localhost)

GET request with query parameters

APIs are useful in our daily lives, and we can’t really do without them, not anytime soon. I hope this article was easy to follow. If you’re stuck, or have any suggestions, or you just want to connect with me, I’m just a URL away.

Till then… Happy coding.

--

--