Create a rest API with Flask in less than 10 minutes
Installing Flask and a little bit more
Assuming that you have python installed in your machine. If not, follow this tutorial before continuing:
- Download python: https://www.python.org/downloads/
- Install modules: https://packaging.python.org/guides/installing-using-pip-and-virtual-environments/
Create a folder for your project, and inside of the folder, execute the following code.
Let’s create your primary file type the imports and initial code as demonstrated below.
Create some methods
First, the class Employee is created, extending Resource to act as a front for the rest API. The Employee’ methods become immediately available for calls when the route is defined. Check the complete documentation here: https://flask-restful.readthedocs.io/en/latest/intermediate-usage.html
As you can see, the method has a path, and you can test this path with Postman. Before executing your code, don’t forget the add the port.
In our example, it will listen to port 5002.
Run your rest API
Send a request using Postman.
That is it
Now, with only this code, you already created your rest API.
Do you want to increment it a little more by using a database?
SQLAlchemy is a toolkit for relational databases that will help you connect, create, and execute queries in a database. See more here: https://www.sqlalchemy.org/
You can also use another database, depending on what your project requires.
- Flask with Firestore: https://cloud.google.com/community/tutorials/building-flask-api-with-cloud-firestore-and-deploying-to-cloud-run
- Flask with MongoDB: https://docs.mongoengine.org/projects/flask-mongoengine/en/latest/
Create your database or get one already done and populated
For our purpose, we will use the sample from the above link, saving the database file in the root directory like this:
Now we add the code for connecting to the database.
Let’s create a query to select all the employees’ data and return the ID list.
Running the same test with Postman.
We now can add two methods for creating and deleting employees in the database using POST.
Testing both endpoints in Postman:
The implementation of the methods is straightforward. Thus anything can be passed as a parameter, even null values. We can create the query dynamically and setting the values as they get set and, for specific fields, validate its value type .e.g:
Checking delete ID parameter:
Now you have up and running a simple rest API. Flask is very practical, as you could see, and you can improve your API gradually depending on your requirements. Although you can do everything as a developer, Flask is a micro-framework and building a heavy load web application would not be recommended in this case.
Get the complete code here: https://github.com/amanajas/flask