Fast API is a new framework for building RESTful APIs, released in 2018, and so this post is on setting up a new fast api with database models and schemas, routes, and controllers. As a Fast API newbie i found myself struggling with basic authentication, saving media files, and most importantly databases and how to manage migrations (before i discover Alembic). If you're used to working with django or laravel frameworks, learning Fast API can be difficulty because you'll have to manually do some of the things that laravel and django does for you.
What is Fast API
It is a python web framework for building RESTful APIs, it is based on Pydantic and type hints to serialize, deserialize data and to generate the OpenAPI docs (which is also a fantastic feature for APIs). Fast API supports asynchronous programming and can be run using Uvicorn and Gunicorn.
This is a library used for data parsing and validation using python type annotations. Pydantic enforces type hints at runtime, and provides user friendly errors when data has errors.
It is a specification for machine-readable interface files for describing, producing, consuming, and visualizing RESTful web services. OpenAPI defines a standard, language-agnostic interface to RESTful APIs which allows both humans and computers to discover and understand the capabilities of the service without access to source code, documentation,
It is a lightning-fast ASGI server implementation, using uvloop and httptools. Very handy for deploying Fast API apps. And you can also use it with gunicorn, another python WSGI HTTP Server for UNIX. Uvicorn includes a Gunicorn worker class allowing you to run ASGI applications, with all of Uvicorn's performance benefits, while also giving you Gunicorn's fully-featured process management.
Why you may be interested in Fast API
- Fast to code
- Standards-based (Open API)
Now let's get into the technical parts, starting with requirements installation,
pip install fastapi pip install sqlalchemy pip install alembic pip install pydantic pip install psycopg2-binary pip install "uvicorn[standard]"
sqlalchemy is a database SQL toolkit and ORM (Object-relational mapper) for python. This library is responsible for translating your python models into SQL statements that can effect changes to your database.
Alembic is a database migration tool, used alongside sqlalchemy for database tables migrations.
This is a PostgreSQL driver. This make it possible for your app to connect to a postgresql database.
Creating the database
Log into an interactive Postgres session by typing:
sudo -u postgres psql
CREATE DATABASE fstapidb; CREATE USER fstapiusr WITH PASSWORD '123467hbff'; GRANT ALL PRIVILEGES ON DATABASE fstapidb TO fstapiusr; \q
So we have created a database fstapidb with the username fstapiusr and password 123467hbff. Then, we can gave the user access to administer the database.