FastAPI is the fast way for building APIs?
"If anyone is looking to build a production Python API, I would highly recommend FastAPI. It is beautifully designed, simple to use and highly scalable, it has become a key component in our API first development strategy and is driving many automations and services such as our Virtual TAC Engineer."
Deon Pillsbury - Cisco
Installation:
pip install "fastapi[standard]"
When you install FastAPI with pip install "fastapi[standard]" it comes with the standard group of optional dependencies:
The few rows of code and the Web server is running:
from fastapi import FastAPI
app = FastAPI()
@app.get("/")
async def index():
return {"Hello": "World"}
? fastapi: The framework on which we’ll build our application.
For running web server:
uvicorn main:app --reload
? uvicorn: An Asynchronous Server Gateway Interface module to run our application.
The command uvicorn main:app refers to:
The web framework contains classes, modules and functions:
Let's add a Database to our project:
First of all we need install a packages:
pip install asyncpg alembic sqlalchemy[asyncio,mypy]
asyncpg is a database interface library designed specifically for PostgreSQL and Python/asyncio.
Alembic is a lightweight database migration tool for usage with the SQLAlchemy Database Toolkit for Python.
SQLAlchemy has been around for years and is the most popular library in Python when you wish to work with SQL databases. Since version 1.4, it also natively supports async.The key thing to understand about this library is that it’s composed of two parts:
? SQLAlchemy Core, which provides all the fundamental features to read and write data to SQL databases
? SQLAlchemy ORM, which provides a powerful abstraction over SQL concepts
While you can choose to only use SQLAlchemy Core, it’s generally more convenient to use ORM.The goal of ORM is to abstract away the SQL concepts of tables and columns so that you only haveto deal with Python objects. The role of ORM is to map those objects to the tables and columns they belong to and generate the corresponding SQL queries automatically.
Notice that we added two optional dependencies: asyncio and mypy. The first one ensures thetools for async support are installed.The second one is a special plugin for mypy that provides special support for SQLAlchemy. ORMdoes a lot of magic things under the hood, which are hard for type checkers to understand. With this plugin, mypy learns to recognize those constructs.
We are created file for environment variables in the root of the project named like .env and wich we provide a necessary variables for connection:
Also we created a config file for Dotenv module:
Dotenv is a zero-dependency module that loads environment variables from a .env file into process.env.
Database file with parameters and async session creation:
One more concept for Migrations there is alembic package that we alredy installed let's initialize the alembic by the command:
alembic init migrations
migrations This folder will contain all the configurations for your migrations and your migration scripts themselves.It should be committed along with your code so that you have a record of the versions of those files.
Additionally, note that it created an alembic.ini file, which contains all the configuration options of Alembic.
In alembic.ini we should replace url link:
And in migrations-> env.py file we need provide additional parameters:
So database and migrations are configurated and ready for a CRUD operations:
First, we need to create a model of entity that we would like to save in database:
领英推荐
declarative_base is a factory function that constructs a base class for declarative class definitions (which is assigned to the Base variable in your example). The one you created in userModel.py is associated with the User model, while the other one (in main.py) is a different class and doesn't know anything about your models, that's why the Base.metadata.create_all() call didn't create the table. You need to import Base from userModel.py
Second, we need to create a DTO that imlemented and named in fastapi as a schema:
And Finally we need import from userModel.py a Base class that inhereted from declarative Base class to env.py of migration folder like that:
So, we start with migration of model to database by the command in terminal panel:
alembic revision --autogenerate -m "Migration of user model"
This will create a new script in the versions directory with the commands reflecting your schema changes. This file defines two functions: upgrade and downgrade. You can view upgrade in the following snippet:
Finally, you can apply the migrations to your database using the following command:
alembic upgrade head
This will run all the migrations that have not yet been applied to your database until the latest. It’s interesting to know that, in the process, Alembic creates a table in your database so that it can remember all the migrations it has applied: this is how it detects which scripts to run.
Now, the time for CRUD operations:(Create,Read,Update,Delete). Let's before isolate the logic of users in new folder and new file. We also create a new Router class to provide logic to the main class:
And import the separated router to the main.py
CREATE Operation:
READ Operation:
Here, I separated the logic with get_user_or_404 function:
UPDATE operation:
DELETE operation:
Let's test the CRUD operations by included swagger functionallity:
Also we need represent home page. I added the templates and static folder to the project and created home page by html:
Now, home page availeble on https://localhost:8000/ :
In the next post I will discover the authentication and authorization ways in FasApi Framework.
code available in github: FastApi project