CRUD REST APIs in 5 Minutes Using Flask

alpha2phi
5 min readApr 3, 2021

Use Flask AppBuilder to develop CRUD REST APIs.

Overview

For Python, when it comes to API development, we have an abundance of choices. Popular ones are Django, Flask, and FastAPI, to name a few.

In this article, let’s use Flask to build RESTful APIs to create, read, update and delete (CRUD) records in a database table. Specifically, I will use Flask + Flask AppBuilder to build the APIs in 5 minutes.

Setup

Libraries

Let’s install the flask-appbuilder library. I also installpython-dotenv in order to use a .env file as my configuration file.

$ pip install flask-appbuilder python-dotenv

Using a virtualenv will be preferred. I assume you are already familiar with Python and will not go through the steps here. For me, I prefer to use Minconda to manage all my packages.

PostgreSQL

For this example, I am going to use PostgreSQL. The docker-compose file is shown below.

As part of the database setup, a database table called accounts is created.

CREATE TABLE accounts (
userid SERIAL PRIMARY KEY,
username VARCHAR (50) UNIQUE NOT NULL,
password VARCHAR (50) NOT NULL,
email VARCHAR (255) UNIQUE NOT NULL,
createdon TIMESTAMP NOT NULL DEFAULT CURRENT_TIMESTAMP,
lastlogin TIMESTAMP
);

The database credentials are in the .env file

POSTGRES_USER=user1
POSTGRES_PASSWORD=userpwd
POSTGRES_DB=testdb
POSTGRES_HOST=localhost
POSTGRES_PORT=5432
SECRET_KEY=9e9b7b01-ae3e-433d-b2ea-c93a69d77802

Application Setup

Create the App

Let’s create the application now using Flask AppBuilder.

$ flask fab create-app
Your new app name: flask-api
Your engine type, SQLAlchemy or MongoEngine (SQLAlchemy, MongoEngine) [SQLAlchemy]:
Downloaded the skeleton app, good coding!

Change Config to Use PostgreSQL

--

--

alpha2phi

Software engineer, Data Science and ML practitioner.