My goal of the article is to help people who are just getting started with programming to become quickly productive with their newfound skills.
When you start learning to program, one of the hardest obstacles is how you can start applying your new-found knowledge to solve a real problem. Building an API with Python is one of the great places to start seeing the result of your hard work.
This article is for those who have been learning to program with Python, and have a basic understanding of the command line and how the web works.
In this article, we will be using Flask: “Web development one drop at a time”. Flask is a web development library built on Python.
Flask takes advantage of the simplicity of Python as an approach for beginners which makes it easy to get started with building a basic application to complex back-end APIs and micro-services that serve millions of users. Flask is used by tech giants like Netflix, Reddit, Lyft, and more.
For the IDE, I will be using Visual Studio Code. I highly recommend you use this, it’s free with an amazing plugin ecosystem that will make your Python development a joy. For testing our API endpoints, we will be using Postman, you can download it for free.
In this tutorial, I will assume you already know the basic Python syntax, you already have Python installed on your development machine, you know your way around the command line, and the basics of how the internet works.
If you don’t already have this knowledge, I will provide links below to free resources of where you can learn these basics and then you can come back to this tutorial.
“An application programming interface is a computing interface to a software component or a system, that defines how other components or systems can use it. It defines the kinds of calls or requests that can be made, how to make them, the data formats that should be used, the conventions to follow, etc.” — Wikipedia
“HTTP defines a set of request methods to indicate the desired action to be performed for a given resource. Although they can also be nouns, these request methods are sometimes referred to as HTTP verbs.
Each of them implements a different semantic, but some common features are shared by a group of them: e.g. a request method can be safe, idempotent, or cacheable.” — MDN
GET method requests a representation of the specified resource. Requests using
GET should only retrieve data.
POST method is used to submit an entity to the specified resource, often causing a change in state or side effects on the server.
PUT method replaces all current representations of the target resource with the request payload.
DELETE method deletes the specified resource.
PATCH method is used to apply partial modifications to a resource.
What We Are Going to Build
In this tutorial, we are going to be building a back-end service for AA Motors to keep track of their fleet of buses. In this tutorial, to keep things simple, we will be using a basic Python data structure to store our data, we can then add a database to it in a future tutorial.
We don’t need to worry about the complexity of databases yet but get the underlying concept of building APIs and how they work.
Above, I have provided us with common definitions in the API world, as you continue to learn and build APIs, all of this will become even clearer.
Create a new directory and navigate to the newly-created directory. I called mine “
aa-api,” you can call yours whatever you want.
“Pipenv is a tool that aims to bring the best of all packaging worlds (bundler, composer, npm, cargo, yarn, etc.) to the Python world. Windows is a first-class citizen, in our world.
It automatically creates and manages a virtualenv for your projects, as well as adds/removes packages from your
Pipfileas you install/uninstall packages. It also generates the ever-important
Pipfile.lock, which is used to produce deterministic builds.”
pip install --user pipenv
As I mentioned in the technologies section above, we are going to be using Flask, a minimalist Python library for building web applications. We will be using Pipenv to install Flask.
pipenv install flask
This will create a virtual environment and install Flask. It will generate two files for us,
Pipfile.lock. If you have some experience with Node.js, this is similar to a
Package.json file or Ruby Gemfile.
name = "pypi"
url = "https://pypi.org/simple"
verify_ssl = true
flask = "*"
python_version = "3.8"
Flask “Hello Universe” API in six lines of code.
So, that’s it, our very first API in just six lines of code, that's how awesome Flask is. If you are familiar with Python, most of this code will look familiar to you.
@app.route('/) can look a little off. This is called decorators in Python, and this concept is also available in other programming languages, so it is not peculiar to Python.
Decorators take in a function and extend its functionality for our
hello function, it will be invoked when the
/ route is requested and return a JSON
I will put a link after this article to learn more about decorators in Python, although it is not a requirement for this article. Flask has already done the heavy lifting for us.
Running Our App
To run our app, we first need to activate the virtual environment created for us by Pipenv by running
➜ aa-api pipenv shell
Launching subshell in virtual environment…
➜ aa-api . /Users/peterayeni/.local/share/virtualenvs/aa-api-9L89IsJh/bin/activate
(aa-api) ➜ aa-api
Then we run
(aa-api) ➜ aa-api python app.py
* Serving Flask app "app" (lazy loading)
* Environment: production
WARNING: This is a development server. Do not use it in a production deployment.
Use a production WSGI server instead.
* Debug mode: off
* Running on http://127.0.0.1:5000/ (Press CTRL+C to quit)
You will see a development server is now running on our localhost on port 5000. Launch Postman and create a GET request.
To help you understand Postman if you have not used it before, check out this quick tutorial: How to send and capture API requests using Postman.
This is where the definition of the HTTP verbs above will start making sense. By default, our
hello function makes a GET request to the root route
"/", you can see the returned JSON in Postman above.
Good job, now let us extend our app to be able to do more.
For the remainder of this tutorial, we are going to build a CRUD API for managing buses of AA motors. Let’s define the information we need to collect about each bus.
Above is the data that will define each bus. We can create a Python list to help us store each bus’s information.
The above is a list of a dictionary, this is a way in which you will see collections of data being created in most languages to store complex data in memory. We will be using the above list from now on in our application.
Above, I have made a few changes to our code, adding a buses collection and making a few changes to the function.
hello function is now renamed to
get_buses. The name gives us an idea of what the functionality of the function is, it will get us all the buses in our collection.
To see the result of our work, we need to restart the server using
ctr+ c and using
Get one bus
Now, let’s create another endpoint that retrieves just one bus.
Above, we added a new endpoint to get a single bus.
We captured the index of the bus we wanted to retrieve via the URL
'/buses/<int:index>' so, in our URL, we can have
http://127.0.0.1:5000/buses/1 and the “1” will be passed to the
get_bus function, which will be used to get the bus at that location of our
buses array and return it to us.
Add a new bus
Awesome, we’re getting a single bus. Now we are going to create an endpoint that will allow a user to add a new bus using our API.
Above is our code implementation of the endpoint that adds a new bus, you will notice some simple differences here.
The first that will jump into your face is that our
@app.route takes a second argument called methods that specifies the kind of HTTP method we are expecting.
From the definition above for POST, you will remember that anytime we need to create a new resource, we need to use the HTTP method. Also, we import the request method from Flask which allows us to capture the data sent through the request body.
You will also notice that this time, we return the ID of the newly added bus, the ID is just the size of the list and a status code 200 to show that the resource was created successfully.
Let’s update the code to only return the bus we added, that’s better for good user experience and will make the life of our front-end developers better.
Update and delete
As you can see, update and delete follow similar patterns. For the update, we use the PUT HTTP method, we get the content of the update via the request method. We know the data to update by passing it through the URL, as we do for getting a single bus.
Delete is the easiest bit. We take the bus to delete from the URL and use the pop array method to take it out of the list and then return the deleted bus to the user.
You will notice we use
jsonify(), a method from Flask to convert a Python dictionary into JSON which we then send to the user.
There you go, all the code you need to spin up a full CRUD API in Python using Flask.
I hope this gives you the heads-up for when you need to start building back-end services with Python. There are a lot of things we can improve in this code, like error checking, validation, adding a database to persist our data, authentication, testing, and documentation.
Flask provides awesome documentation that you can use to improve this API, and there are many other resources just a Google away for you to continue to learn. I will continue to build on this tutorial to add other layers of improvement.