Let's create a CRUD Rest API in Python, using the following:
- Flask (Python web framework)
- SQLAlchemy (ORM)
- Postgres (database)
- Docker (containerization)
- Docker Compose (to run the application and the database in containers)
If you prefer a video version:
All the code is available in the GitHub repository (link in the video description): https://youtube.com/live/fHQWTsWqBdE
🏁 Intro
Here is a schema of the architecture of the application we are going to create:
We will create 5 endpoints for basic CRUD operations:
- Create
- Read all
- Read one
- Update
- Delete
Here are the steps we are going through:
- Create a Flask application using SQLALchemy as an ORM.
- Dockerize the Flask application writing a Dockerfile and a docker-compose.yml file to run the application and the database
- Run the Postgres database in a container using Docker Compose, and test it with TablePlus
- Run the Flask application in a container using Docker Compose, and test it with Postman
We will go with a step-by-step guide, so you can follow along.
🏁 Create a Flask application using SQLALchemy as an ORM
Create a new folder:
mkdir flask-crud-api
step into the folder:
cd flask-crud-api
Open the folder with your favorite IDE. I am using VSCode, so I will use the command:
code .
We need just 4 files for the Flask application, including containerization.
You can create these files in different ways. One of them is to create them manually, the other one is to create them with the command line:
touch requirements.txt app.py Dockerfile docker-compose.yml
Your folder structure should look like this:
🗒️requirements.txt file
The requirements.txt file contains all the dependencies of the project. In our case we will need just 3.
Let's add them to the requirements.txt file:
flask
psycopg2-binary
Flask-SQLAlchemy
Short explanation of the dependencies:
flask is the Python web framework we are gonna use.
psycopg2-binary is the driver to make the connection with the Postgres database.
Flask-SQLAlchemy is the ORM to make the queries to the database.
🐍 app.py file
The app.py file is the main file of the application: it contains all the endpoints and the logic of the application.
Populate the app.py file as follows:
from flask import Flask, request, jsonify, make_response
from flask_sqlalchemy import SQLAlchemy
from os import environ
app = Flask(__name__)
app.config['SQLALCHEMY_DATABASE_URI'] = environ.get('DB_URL')
db = SQLAlchemy(app)
class User(db.Model):
__tablename__ = 'users'
id = db.Column(db.Integer, primary_key=True)
username = db.Column(db.String(80), unique=True, nullable=False)
email = db.Column(db.String(120), unique=True, nullable=False)
def json(self):
return {'id': self.id,'username': self.username, 'email': self.email}
db.create_all()
#create a test route
@app.route('/test', methods=['GET'])
def test():
return make_response(jsonify({'message': 'test route'}), 200)
# create a user
@app.route('/users', methods=['POST'])
def create_user():
try:
data = request.get_json()
new_user = User(username=data['username'], email=data['email'])
db.session.add(new_user)
db.session.commit()
return make_response(jsonify({'message': 'user created'}), 201)
except e:
return make_response(jsonify({'message': 'error creating user'}), 500

