Create a rest API with Flask in less than 10 minutes

Let’s start

Installing Flask and a little bit more

Assuming that you have python installed in your machine. If not, follow this tutorial before continuing:

Continuing

Create a folder for your project, and inside of the folder, execute the following code.

Creating environment and installing flask lib

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

Class and methods with route defined

Run your rest API

Send a request using Postman.

Postman first test

That is it

Now, with only this code, you already created your rest API.
Tutorial finished.

Adding 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/

Create your database or get one already done and populated

https://www.sqlitetutorial.net/sqlite-sample-database/

Folder database and db file
Connecting with database file
Listing IDs from employees
Create employee method
Delete employee method
Successful message creating employee
Successful message deleting employee

Next steps

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:

Number validation

Conclusion

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.

GitHub

Get the complete code here: https://github.com/amanajas/flask

Software nerd and data engineer enthusiast