5 reasons you should use FastAPI to get stuff done quickly

5 reasons you should use FastAPI to get stuff done quickly

About a month ago, I read about FastAPI when I was skimming through some blogs. It didn't take long until my team at work had to build an API for the app we develop. Because the API isn't too complex, we decided to try out something new, and instead of Flask, we went forth with FastAPI.

The longer I worked with the framework, the more I liked it. Given the good first impression, I would like to tell you about the main reasons why I find FastAPI a great tool. Maybe they will convince you to try it out too!

Get a lot done with a few lines of code

What immediately caught my attention is that it doesn't take much time to have a working API with some simple endpoints. I wanted to write a simple CRUD to use as an example for this article. Below is the code of the API layer for user management. It took me less than 10 minutes to do so.

from typing import Optional
from users import Users

from fastapi import FastAPI

app = FastAPI()


@app.get("/users")
def get_users():
    return Users.all()


@app.get("/users/{id}")
def get_user(id: int):
    return Users.get(id)


@app.post("/users")
def create_user(first_name: str, last_name: str, email: str):
    return Users.create(first_name=first_name, last_name=last_name, email=email)


@app.put("/users/{id}")
def update_user(first_name: Optional[str], last_name: Optional[str], email: Optional[str]):
    return Users.update(id, first_name, last_name, email)


@app.delete("/users/{id}")
def delete_user():
    return Users.delete(id)

When you write the code for the API endpoints, you are encouraged to type the parameters you use. FastAPI has a cool feature leveraging type annotations. If a parameter is invalid, the framework will render a nice JSON explaining what went wrong. So, if you ever forget to fill in a required field in a request body, you'll get a response like this:

{
    "detail": [
        {
            "loc": [
                "query",
                "first_name"
            ],
            "msg": "field required",
            "type": "value_error.missing"
        }
    ]
}

And if the type of a parameter does not match the expected one, you'll also get informed about it:

{
    "detail": [
        {
            "loc": [
                "path",
                "id"
            ],
            "msg": "value is not a valid integer",
            "type": "type_error.integer"
        }
    ]
}

However, this is not the only thing that you get for free when writing the code.

No need to write documentation

I remember projects where I had to write documentation of the API manually. It was a nightmare at the very least. FastAPI makes it all a breeze because it generates the documentation for you as you go.

If you want to see the docs, just set up the server and go to http://localhost:8000/docs to see a pretty OpenAPI UI. Zrzut ekranu 2021-08-16 o 23.39.29.png

And if you don't like OpenAPI, there's an alternative. Go to http://localhost:8000/redoc to see the documentation rendered by ReDoc. Zrzut ekranu 2021-08-16 o 23.39.47.png

Both documentation views allow you to run sample requests.

All of these features make sharing the documentation with others an easy and enjoyable task.

FastAPI itself has robust yet easy-to-grasp documentation, too. It's a crucial piece in making the framework so easy to pick up.

Enjoyable to learn

What I love about the documentation of FastAPI is how actionable it is. Instead of throwing you into the meanders of theory, the documentation breaks down the framework feature by feature and then proceeds to explain each bit with an example.

Zrzut ekranu 2021-08-20 o 17.03.45.png

What's great about the examples is that they highlight the crucial parts of the code that make the functionality work.

Out of all the Python libraries I have worked with so far, this one has the best documentation. You can quickly skim it through it to find what you need. And when there's more time, you can have a proper and comprehensive read of the docs.

So far, I've only focused on the speed and convenience of development. However, FastAPI isn't only about that. When it says it IS fast, it doesn't lie. Let's compare its performance against other Python frameworks.

Convenient, yet quick

When you go to the GitHub page of FastAPI, the very first thing it boasts of is the performance. TechEmpower is a portal that benchmarks available web frameworks and compares their performance in different use cases. By the time I'm writing this article, FastAPI is the 4th fastest Python framework. It beats Flask quite a lot, even though Flask is a quite established framework.

The final thing is not about the framework itself but a related library that makes it easy to embed within the AWS ecosystem.

Seamless integration with AWS

Mangum is a library adapting incoming requests from ALB and API Gateway into a convenient-to-use format for a web app.

Our application leverages Lambdas for hosting, and ALB takes care of traffic routing. Of course, it's possible to write a custom parser for the incoming requests, but instead, you can embed your app with Mangum. It's just two lines of code.

from fastapi import FastAPI
from mangum import Mangum

app = FastAPI()

# here goes the API

handler = Mangum(app)

After I deployed the application to AWS, it immediately started to understand the incoming requests. I was surprised by how quick the process would be.


Coming from a Ruby on Rails background, I appreciate tools helping developers to get stuff done efficiently. I like that the code built with FastAPI is descriptive and easy to understand.

I know that there is so much more to learn about the framework, given that I have only used it for two weeks. However, I have to admit that not many tools made that great first impression on me, and keep it up with many pleasant surprises. One of my friends asked me if it's going to convert me from being a pious Ruby on Rails follower 😄 Let's say that's a little less certain than before 😉

So, to sum it all up, if you want to get stuff done quickly, you should try out FastAPI!

Resources:

Did you find this article valuable?

Support Damian Kampik by becoming a sponsor. Any amount is appreciated!