Basic Rest API in Flask and SqlAlchemy

  1. Step 1: pipenv install --python 3.8
  2. Step 2: pipenv shell
  3. Step 3: pipenv install flask flask-sqlalchemy flask-marshmallow marshmallow-sqlalchemy flask-migrate psycopg2

flask-sqlalchemy is the sql-alchemy with flask bindings. flask-marshmallow is like the Serializer in Django Rest Framework, marshmallow-sqlalchemy is common binding between marshmallow and sqlalchemy (for things like ModelSerializer in Django Rest Framework).flask-migrate is migration tool for Flask based on ALEMBIC.psycopg2-binary is for connecting to postgres db.

Note: If psycopg2 install gives errors use psycopg2-binary. But this is a development only binary. It is not meant for production. For production, you need to compile psycopg2 from source.
See here for installing psycopg2 if you face issues: https://tekshinobi.com/install-psycopg2-on-ubuntu-18-04/

Now create the application file.. traditionally called app.py (or main.py…whatever your taste).
touch app.py

Now do these steps on the console (don’t do the third step yet as app.py is still empty):

  1. export FLASK_APP=app.py
  2. export FLASK_ENV=development
  3. flask run

The no. 2 in above list is important. It will hot reload the server upon code changes

Here is the app.py file. This is a toy CRUD app. So, all code is in one file.

Before running this app, lets create the database and populate it.

Goto Python console and say:

Thats it. SQLAlchemy has done all the magic for you and created your database.

Now run the app by:
flask run




No Comments


You can leave the first : )



Leave a Reply

Your email address will not be published. Required fields are marked *