Why you should switch to FastAPI

After exploring Django, Flask for couple of years, I came across FastAPI and decided to give it a shot for one of our new project. In this article will discuss some of the core features of the FastAPI and how can we leverage them in order to faster the API development.

Access headers, cookies directly by name

You can directly access headers and cookies without traversing the request object which will be really helpful during the token validation. You need to pass the header and cookie with the same name as of the variable and then FastAPI will internally map those to the defined parameters. you can also use the alias field to specify the custom name and then it’s value will be directly mapped to the defined variable.

Dependency Injection

One of the core feature of FastAPI is “Dependency Injection”. Instead of initializing common piece of code (e.g. database connection)on every request we can use DI here and the framework will take care of the initialization. In our case we used it to verify the user token on each request (as shown below).

Database Session initialization using DI

Basic User Authentication & Authorization

Handling exception globally

This is one of my favourite, as we all know exception handling is one of the major component of any application. Now you don’t need try/catch on each endpoint or function unless you want perform some other specific action on exception then FastAPI got you covered, you just have to override the default exception handler.

from fastapi import FastAPI, Request
from fastapi.responses import JSONResponse
app = FastAPI()@app.get("/test_enpoint")
def read_root():
1/0
@app.exception_handler(Exception)
def global_exception_handler(request: Request, exc: Exception):
#log your exception here
# you can also request details by using request object
return JSONResponse(content={"message":"Something went wrong"},
status_code=500)

Request/Response Model

Finally the last but not the least, in each api request and response model plays crucial role of sending/receiving data from client. FastAPI uses Pydantic to take care of the request/response models. I highly recommend you to explore the Pydantic documentation before starting with the FastAPI. In this section we will only cover specific feature from response model which are really helpful during the development . Let’s say you want to return the user details from an endpoint, then you need to models one which will return the response to the client and the other model will represent the database table if you are using orm framework like SQLAlchemy instead of plain sql queries. In this case you can’t return the database model directly to user as it might contain some unwanted fields which will be specific to database and not relevant for client, now the biggest task is transform database model to response model manually by creating object of the response model and assigning the value of database model to each property, if the response models consist of many properties then you need use some other mapper extensions to achieve this, however with the FastAPI you don’t need any of this as the response_model parameter will take care of this.

Next Steps for Your Learning

I haven’t explored following important features which might be useful for you so I will just list them. One of the best thing about the FastAPI is their documentation

  1. Middleware
  2. Swagger/OpenAPI

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store