Creating high performance APIs with FastAPI

Posted By : Siddhant Sinha | 31-Jul-2020

api

Loading...

FastAPI

FastAPI is a high-performance web framework, based on Python 3.6+, similar to Flask. It is lightweight and fast to code. It follows the OpenAPI(Swagger) standard and JSON Schema, therefore makes building API documentation pretty easy. Its fast performance comes from using an asynchronous code called coroutines which is similar to the event loop in NodeJS. It is based on concurrent programming design which was introduced from Python 3.5 onwards and was improved in further versions of Python. If you want to know more about Asynchronous Programming, you can refer to this article. It uses uvicorn as a server which is based on ASGI.

FastAPI uses type hints extensively which were introduced in version 3.6 of Python. Type-hints basically allow us to declare a type of a variable, take this example -

def add(a: int, b: int):

return a+b

Here I have declared a type hint for parameters a and b to be of integer type. We can also declare generic types like List, Dictionary, Tuple, etc.

from typing import List

def printList( items:List):

for item in items:

print(item)

Now, let’s move on to creating some APIs in FastAPI. Setup a project in the directory and create a virtual environment. Then, install these modules -

pip3 install fastapi uvicorn pymysql

Create a main.py in your folder, and add a simple get request -

from fastapi import FastAPI

app = FastAPI()

@app.get(“/”)

async def root():

return { “message”: “Hello There!” }

We initialize ‘app’ as an instance of class FastAPI. Then we create a basic GET request which returns a JSON message. Note the use of async function here. Now on the terminal run -

uvicorn main:app –reload

main refers to our main.py file and app refers to the instance app. Go to localhost:8000 or http://127.0.0.1:8000/ on your browser. You’ll see the message. Now go to http://127.0.0.1:8000/docs, an OpenAPI based documentation will be automatically generated for your GET request.

FastAPI uses SQLAlchemy for its ORM just like Flask does. Let’s create a model for an Employee -

from sqlalchemy.ext.declarative import declarative_base

from sqlalchemy import Column, Integer, String

Base = declarative_base()

class Employee(Base):

__tablename__ = “employee”

id = Column(Integer, primary_key=True, index=True)

name = Column(String(256))

age = Column(Integer)

Now define a schema for the employee in a schema.py file

from typing import List

from pydantic import BaseModel

class EmployeeBase(BaseModel):

employeename: str

class EmployeeCreate(EmployeeBase):

name: str

age: int

class Employee( EmployeeBase):

id:int

class Config:

orm_mode = True

Create a folder for routers and add a __init__.py file there. Also, create an employee.py file, where we will create the routes -

from fastapi import APIRouter

from fastapi_sqlalchemy import db

from model import Employee

from schema import EmployeeCreate as SchemaEmployee

router = APIRouter()

@router.post(“/register”, response_model=Employee)

async def create_user(employee: SchemaEmployee):

create_emp = Employee(name=employee.name, age= employee.age, id= employee.id)

db.session.add(create_emp)

db.session.commit()

db.session.refresh(create_emp)

return create_emp

In your main.py, import this router -

from fastapi import FastAPI

from routers import employee

from fastapi_sqlalchemy import DBSessionMiddleware

app = FastAPI()

app.add_middleware(DBSessionMiddleware,db_url=os.environ["SQLALCHEMY_DATABASE_URI"])

@app.get(“/”)

async def root():

return { “message”: “Hello There!” }

app.include_router(employee.router)

Now run the server again and go to http://127.0.0.1:8000/docs. A POST method with a URL /register has been created. Here you can create a new employee using the POST method with the schema of the employee.

Hence, we saw how using FastAPI helps us create API methods easily with included API docs.

We are an API development company that aims to build seamlessly functioning software suites for businesses. Our developers hold expertise in developing ERP systems as well as task-specific business applications for enterprises to automate and optimize their operations/processes. We develop mobile and web applications as well as SaaS applications for WFM, HRM, CRM, WMS, Finance, Accounting, eCommerce, and more. Contact us to avail our custom development services.!