It is important to know how to create an API. Nowadays is very common to encounter micro services to perform small but specialized tasks.
Flask allows you to create an API very easily. You can also create a web application which can consume services with APIs.
I have been an intern in Nearsoft for almost three months. We were given the task of contributing to open source repositories. I chose Flask to create an API and build a web app.
I’d like to share what I learned and point out the kind of things you can accomplish with it.
What Is Flask?
Flask is a micro framework used to create web applications.
It is considered micro-framework, because it doesn’t depend on anything else. This means that as developer you should take care of what database or tools you want to use.
We can do a simple Hello World exercise to cover the main characteristics of Flask. You don’t even need to install lots of things.
This will show you how easy it is to develop an API and a web app with Flask.
Creating an API with Flask
The first thing you have to do is install the necessary libraries to work with Flask. Run the following commands in the console,
pip install -U Flask
pip install flask_restful
Create a file called
api.py and import the libraries you just installed. Like this,
from flask import Flask
from flask_restful import Resource, Api
You can create an API with the main Flask library, but in the long run it is easier to use the Flask library specialized in creating APIs.
Add the following lines of code. You’ll create a Flask instance and pass that instance to the API,
app = Flask(__name__)
api = Api(app)
To make a Hello World do this,
def get(self, name):
The Hello class inherits the Resource class. This is what Flask uses to know which route is associated with each class. We also declared a get method which indicates what kind of REST operation has to be used in order to execute the method.
In this example we only required a get method, but the same logic applies to whichever method we want to use, put, post, etc.
Now we simply add a resource to the API. We also associate the class with the route, as well as any parameters used in the route,
Add the following to run it with python
if __name__ == ‘__main__’:
You can pass a debug parameter set as True if you want to make changes without restarting the program.
Now, to run in your console, you only have to do this,
You can verify the API works by writing this in your browser,
It will give you the following output,
Great! Now we have our API working. As you see it is a very simple example but it can get more complex than that.
Creating a Web Application with Flask
Now we will make a web application with Flask. This is going to consume the API we just made.
In another project create a file called
webapp.py in which we’ll export Flask to create an instance of it.
Then import the requests library in order to consume the API.
pip install requests
Import the necessary libraries to our
from flask import Flask
In Flask the routes are generally set with decorators, in which we will pass the REST methods as parameters (GET, POST, PUT, DELETE). The route will be accessed by the user in the browser.
A decorator takes the function below and adds more functionality to it. This is done with the purpose of making it more readable and understandable.
If you want to make a method that return us the result of our API, you should write the following code,
info = requests.get('http://localhost:5000/hello/'+name)
The @app.route decorator has the route that will be accessed in the browser. You can also include additional parameters in it.
In this case we don’t specify the methods because we will only use the GET method. Within the hello method we use the requests library to consume our API (i.e., a GET method). In this case, we just pass the URL of where our API is running.
As before, we add the following.
if __name__ == '__main__':
app.run(debug=True, host='0.0.0.0', port=80)
But this time is a little bit different because we will have two different files running with Flask. In this one we’ll assign a different port, otherwise one of the application won’t run because the port is being used by the other. Now run the file,
If you get a "permission denied" run it with
Access your localhost through your browser with the port you assigned (e.g., 80) and you should get the following result,
But Wait, There's More!
Well, we just finished with the creation of our API and web application.
But wait, this exercise is kind of boring, isn’t it?
So we can give a little bit more functionality in order to make it more fun and also to explain the benefits of dividing services.
Let’s try a fun exercise involving the Tweepy API to get the timeline from a Twitter user.
The following exercises consists of searching for a Twitter user in our web application that will consume our API. This will return the user’s timeline, as well as some other general information.
The only thing you have to do is generate keys in order to authenticate with Twitter. You can generate your keys by accessing https://apps.twitter.com/ and registering an application. It will give you your access and token keys, four in total.
Creating an API Using Twitter
We will add two more files to our API project,
twitter_tools.py will get the user information from Twitter and
models.py has the model Person in order to store the user’s information.
The structure is as follows,
In the main file
api.py add the resource that uses the function to retrieve the user’s information. It ends as follows,
Before running the application make sure of installing the
pip install tweepy
Now run python
api.py in the console and go to your browser and write the following,
@spotgabbiani is the user I use as an example, but you can use any other user. The following should appear,
We have our API working, now we should do our web application.
Creating a Web Application Using Twitter
Most of what is added in this section is to make the application look good. It has the following structure,
forms.py we will add a class which inherits from FlaskForm. Using this we can make the forms structures in a very easy way as well as making validations.
Now, regarding Flask we will add two more methods. One of them will give the user the form and the other one will consume our API service. The file
webapp.py ends as follows,
It is important to mention that in order to use the Flask forms we had to add a secret key. This is wrong in a real project, you should use an environment variable. But for practical purposes you can use whatever string you want.
Finally, we finish with the code part. We now need to run them in the same way as before. Remember that you will run it in different consoles and for the web application you may have to use sudo.
sudo python webapp.py
Access your localhost through your browser and you should get this,
We can search the Twitter username we want. The first time it will take its time, depending on the number of tweets the person has made. After that, it won’t take even a second. This is because we store in memory what we retrieve from Twitter. But we don’t have a database so the information will be lost every time you restart the API.
If you had an error, you can check the code in the following repositories on Github,
Flask has a very basic set of commands that will allow you to create an API and a web application very easily. The intention of this post was to show the importance in dividing a project into different services.
In this exercise, one service is in charge of the user interface and how the user interacts with the application. The other is in charge of retrieving the information from Twitter.
Instead of having everything in a big project, dividing them into micro services will make the continuous integration easier.
I know it was a long post, but I appreciate that you took the time to read it. I hope you learned from this as I did.