In this tutorial, you will learn how to build a simple CRUD API using Flask, SQLAlchemy, and PostgreSQL.
~ sudo service postgresql start
➜ * Starting PostgreSQL 14 database server
# 14 is the PostgreSQL Server Version
~ sudo -u postgres psql
➜ postgres=#
<!-- create database DBNAME; -->
postgres=# create database testdb;
➜ CREATE DATABASE
<!-- create user USERNAME with encrypted password 'PASSWORD'; -->
postgres=# create user testuser with encrypted password 'testpass';
➜ CREATE ROLE
<!-- grant all privileges on database DBNAME to USERNAME; -->
postgres=# grant all privileges on database testdb to testuser;
➜ GRANT
postgres=# \q
~ psql -U testuser -h 127.0.0.1 -d testdb
Password for user testuser: testpass
➜ testdb=>
testdb=> \conninfo
➜ You are connected to database "testdb" as user "testuser" on host "127.0.0.1" at port "5432".
<!-- We need this information later for the env file -->
$ python3 -m venv env
$ source env/bin/activate
pip install -U flask Flask-SQLAlchemy psycopg2-binary Flask-JWT-Extended python-dotenv Flask-Migrate
pip freeze > requirements.txt
└── src
├── app.py
├── config.py
├── controllers.py
├── __init__.py
├── models.py
└── urls.py
flask run -h 127.0.0.2 -p 5001
flask db init
flask db migrate
flask db upgrade
- Request Method: POST
- Request Link: http://127.0.0.2:5001/api/user
- Body Data in form-data:
{
"username":"akkaoui",
"password":"OLEm#-!",
"email":"email@gmail.com"
}
- Request Method: GET
- Request Link: http://127.0.0.2:5001/api/user
- Request Method: GET
- Request Link: http://127.0.0.2:5001/api/user/1
- Request Method: PUT
- Request Link: http://127.0.0.2:5001/api/user/1
- Body Data in form-data:
{
"email": "akkaoui@gmail.com",
"role": "Senior Sofware Engineer"
}
- Request Method: DELETE
- Request Link: http://127.0.0.2:5001/api/user/1