Easy development with FastAPI

Tech Talk

by Engineers of Acroquest Myanmar Technology

Easy development with FastAPI

Hello, this is Thin Pyai from Acroquest Myanmar Technology. Now, I am working as a technical architect.  

This blog contents are based on FastAPI 0.78.0 version. 

I am going to introduce a quick server development by using FastAPI. From my example, named “Book Store “, you can understand how it is easy to develop a server within a short time by using FastAPI and its useful libraries.  
 
As the contents are much, I will introduce part by part. This blog will introduce you  

  • what FastAPI is and  
  • how to start using it. 

FastAPI is a modern, fast (high-performance), web framework for building APIs with Python 3.6+ based on standard Python type hints.  

Here are its key features. This is the reason for selecting FastAPI in this example. 

1FastVery high performance, on par with NodeJS and Go (thanks to Starlette and Pydantic). One of the fastest Python frameworks available
2Fast to codeIncrease the speed to develop features by about 200% to 300%. *​ 
3Fewer bugsReduce about 40% of human (developer) induced errors. * 
4 Intuitive Great editor support. Completion everywhere. Less time debugging.​
5 Easy Designed to be easy to use and learn. Less time reading docs.​ 
6 Short Minimize code duplication. Multiple features from each parameter declaration. Fewer bugs. 
7 Robust Get production-ready code. With automatic interactive documentation.​ 
8 Standards-based Based on (and fully compatible with) the open standards for APIs: OpenAPI (previously known as Swagger) and JSON Schema.​ 

More information is at https://fastapi.tiangolo.com/

However, beginners may feel difficulties when we want to develop more than tutorial level because  

1. Guideline community is very small. Its documentation and examples are very simple. It will be difficult to get good references when your requirement becomes high to meet with your project design and architecture. 

2. FastAPI uses SQLAlchemy. If you follow their tutorials, your model will be full of dependencies of ORM. It will be difficult to separate your models from storage concerns.

But you can avoid it by understanding ORM.  
In this series of blogs, I would like to show you how we can develop quickly. Additionally, I will introduce one of powerful but still in experimental state features in this content writing time. 

Simply, this is the image of our system. 

1. System acrhitecture

In this series of blogs, I am going to create a server with the following technologies. 

  • FastAPI : As I introduced above, it is a modern, fast (high-performance), web framework for building APIs with Python 3.6+. For details, please read https://fastapi.tiangolo.com/ 
  • GraphQL: A query language for APIs and a runtime for fulfilling those queries with your existing data. For details, please read https://graphql.org/  
  • SQLite: SQLite is a C-language library that implements a small, fast, self-contained, high-reliability, full-featured, SQL database engine. SQLite is the most used database engine in the world. For details, please read https://www.sqlite.org/index.html

FastAPI has effective libraries to work with those technologies. 

2. FastAPI libraries 
NoLibraryExplanation
1 Strawberry It is a new GraphQL library for Python 3.  
https://strawberry.rocks/ 
In future, it can work with Pydantic for efficient implementation techniques like reducing duplicate codes and validation check. It is still in experimental feature. It is still in experimental feature. But I will show some samples in today’s topic. Detail: https://strawberry.rocks/docs/integrations/pydantic 
2 Pydantic It is for data validation and settings management using python type annotations. Detail: https://pydantic-docs.helpmanual.io/  
3 SQLAlchemy Python SQL toolkit and Object Relational Mapper that gives application developers the full power and flexibility of SQL. Detail : https://www.sqlalchemy.org/  

Additionally, as server workers,  

4 uvicorn Uvicorn is an ASGI web server implementation for Python. And Uvicorn has a Gunicorn-compatible worker class.
5gunicorn Gunicorn ‘Green Unicorn’ is a Python WSGI HTTP Server for UNIX.

Using that combination, Gunicorn would act as a process manager, listening on the port and the IP. And it would transmit the communication to the worker processes running the Uvicorn class. 
And then the Gunicorn-compatible Uvicorn worker class would be in charge of converting the data sent by Gunicorn to the ASGI standard for FastAPI to use it. 
Detail : https://fastapi.tiangolo.com/deployment/server-workers/

Let’s try those things step by step. 

Before implementing, I would like to recommend you read and understand the above contents. 

  1.   Setup environment (Python)
    • Before starting the tutorial, you need to have Python version 3.6+.
    • Install the necessary libraries 
      > pip install fastapi 
      > pip install uvicorn[standard] gunicorn 
      > pip install strawberry-graphql[fastapi] 
      > pip install sqlalchemy
  2. Let’s develop.

This tutorial is about book store.  
Book can be registered. Registered books can be got. By using id, each book can be got/ deleted. 
 
I will create the following 5 files. 

1 database.py  Database setting for connecting with database. 
2 models.py  Model definition and table definition. 
3 crud.py  CRUD operation definitions. 
4 main.py  Main function and endpoint definitions. 
5 type.py  Object types definition to input and output to server application. 

1) In main.py, define a simple query which will get a book.
Let’s check with sample data for initial understanding.

get_book() will accept id as input data. It will return a sample book data.
As get_book() is the GraphQL Endpoint, strawberry APIs are used.
In here, you will need to understand GraphQL query and how to use Strawberry library. Please read https://strawberry.rocks/docs/general/queries

import strawberry
  
 @strawberry.type
 class Query:
  
     @strawberry.field
     def get_book(self, id: int):
         return {
             'title': 'The End We Start From',
             'author': 'Megan Hunter',
             'type': 'fiction'
             } 

Strawberry provides support for FastAPI with a custom APIRouter called GraphQLRouter.
Define a route to access our endpoint.
https://strawberry.rocks/docs/integrations/fastapi

 from fastapi import FastAPI
 import strawberry
 from strawberry.fastapi import GraphQLRouter
  
 @strawberry.type
 class Query:
  
     @strawberry.field
     def get_book(self, id: int):
         return {
             'title': 'The End We Start From',
             'author': 'Megan Hunter',
             'type': 'fiction'
             }
  
 schema = strawberry.Schema(query=Query)
 graphql_app = GraphQLRouter(
     schema
 )
  
 app = FastAPI()
 app.include_router(graphql_app, prefix="/graphql") 

Define main method to run the server with host 127.0.0.1 and 8000 port.
I setup None for log setting in current. For log configuration, please read detail at https://www.uvicorn.org/settings/#logging

 from fastapi import FastAPI
 import strawberry
 from strawberry.fastapi import GraphQLRouter
 import uvicorn
  
 @strawberry.type
 class Query:
  
     @strawberry.field
     def get_book(self, id: int):
         return {
             'title': 'The End We Start From',
             'author': 'Megan Hunter',
             'type': 'fiction'
             }
  
 schema = strawberry.Schema(query=Query)
 graphql_app = GraphQLRouter(
     schema
 )
  
 app = FastAPI()
 app.include_router(graphql_app, prefix="/graphql")
  
 if __name__ == '__main__':
     uvicorn.run(app=app, host='127.0.0.1', port='8000', log_config=None) 

2) Run the server
activate the virtual environment.
> .venv\Scripts\activate

run python file.
> python -m main

3) Access to  GraphQL console
by going to http://127.0.0.1:8000/graphql from browser

4) Paste and execute following query which will call get_book().

 {
   getBook{
     title
     author
     type
   }
 } 

Following result must be returned.

 {
   "data": {
     "getBook": {
       "title": "The End We Start From",
       "author": "Megan Hunter",
       "type": "fiction"
     }
   }
 } 

In this blog, I introduced how to develop a server easily in short time with FastAPI.

As I described only how to access a GraphQL Endpoint, I will introduce how to interact with Database for CRUD activities in the future blog. Please look forward.  

Thank you very much for reading until the end. 
Stay safe everyone.

★★★We are hiring the staff who are interested in latest technologies.★★★

If you are interested in our company, please see the available job descriptions in the following links.

Senior Frontend/ Backend Developer : https://www.acromyanmar.com/senior-frontend-backend-developer/


Check our Facebook Page!