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.

Most of the standard headers are separated by a “hyphen” character, also known as the “minus symbol” (-).But a variable like user-agent is invalid in Python. So, by default, Header will convert the parameter names characters from underscore (_) to hyphen (-) to extract and document the headers.

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

If you want your dependency to return some value then you have to use it as a function parameter at the endpoint level like we did it for database session. Please ignore response_model as of now we will discuss this later in detail.

Basic User Authentication & Authorization

In first example we have seen dependencies declared as functions get_db. But that’s not the only way to declare dependencies. The key factor is that a dependency should be a “callable”. A “callable” in Python is anything that Python can “call” like a function.

In above snippet we have used Classes as Dependencies AuthUser Python class is also a callable. Then, in FastAPI, you could use a Python class as a dependency.

Applying dependency to an endpoint/route/app.

you can apply dependencies in following ways.

1. Directly to endpoint like we did it for (admin_endpoint).

2. On a route which will be registered to an FastAPI application (user_router).

3. Globally to an application like below.

app = FastAPI(dependencies=[Depends(user_auth_scheme)]

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():
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"},

The above function will be invoked for all the exceptions raised by the code as we have specified the Exception class. You can also override the other exception handlers such as RequestValidationError from fastapi.exceptions to handle the request validation errors, in order to achieve this just replace the Exception parameter with the class for which you want to handle the exception or you can also specify multiple handler function with their respective exception classes.

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.

In model_example.py we have declared two models MUser is database model and UserRead is pydantic response model which will be returned to the client. now wothout any assignment or object creation the FastAPI and pydantic together will take care of transformation, here the response_model will tell fast api what to return to client when the respective api is called. In response model we have specified a config class in which the orm_mode=True property will tell pydantic this is database model. please note that in response model field name should be same as database model and you can use alias field to change the field name in the json response (in our case response will be [{“userId”: ”1”, “userFullName”:”user_one”}]) if you don’t want to return the same fields as that of the database model.

there are many other parameter’s which will be helpful during the response manipulation which I will leave up to you to explore.

response_model_include, response_model_exclude, response_model_exclude_unset, response_model_exclude_defaults, response_model_exclude_none

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. Async
  2. Middleware
  3. 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