FastAPI is a modern, fast (high-performance), web framework for building APIs with Python 3.7+ based on standard Python type hints. In recent years, FastAPI has gained a lot of popularity due to its simplicity and ease of use. It’s quickly becoming a go-to choice for developers looking to build APIs with Python. In this article, we’ll explore the reasons for FastAPI’s growing popularity and take a closer look at some of its key features.

The Context

FastAPI, Flask, and Django are all popular web frameworks for building APIs and web applications with Python. Each has its own strengths and trade-offs, and the best choice for a particular project will depend on the specific requirements and goals of that project. Here is a comparison of the three frameworks:

  • FastAPI: FastAPI is a modern, high-performance web framework that is built on top of Python’s asyncio library. It is designed to be easy to use and to provide automatic validation and documentation of API endpoints. FastAPI is a good choice for building APIs that need to be very fast and support high levels of concurrency.

  • Flask: Flask is a microweb framework that is simple and easy to get started with. It is a good choice for building small, simple web applications and APIs. Flask is not designed to be as high-performance as FastAPI, but it is very lightweight and easy to extend.

  • Django: Django is a full-featured web framework that is designed for building complex, database-driven web applications. It includes a large set of pre-built components and libraries, and it is highly customizable. Django is not as lightweight as Flask or FastAPI, but it is a good choice for projects that require a lot of built-in functionality and the ability to handle complex workflows.

Key Features

Some of the best features of FastAPI include:

  • Fast and efficient: FastAPI is built on top of Python’s asyncio library, which makes it one of the fastest web frameworks available for Python. It is also highly efficient, using a minimal amount of memory and CPU resources.
  • Automatic documentation: FastAPI automatically generates documentation for your API using the same code that powers the API. This makes it easy to keep your documentation accurate and up-to-date, and it also makes it easier for developers to understand how to use your API.
  • Built-in validation: FastAPI integrates with the Pydantic library for data validation, which allows you to define complex, self-validating data models. These models are used to automatically validate request payloads and convert them into Python objects.
  • Easy to use: FastAPI is designed to be easy to use and to get started with. It has a clean and simple API, and it is well-documented.
  • Open source: FastAPI is an open-source project, which means that you can use it for free and contribute to its development if you wish.

Performance

FastAPI is memory efficient and performant compared to other Python web frameworks because it is built on top of the asyncio library, which is a high-performance, asynchronous I/O library included with Python. Asyncio allows FastAPI to handle a large number of concurrent connections using a minimal amount of memory and CPU resources.

In terms of performance, FastAPI is one of the fastest web frameworks available for Python. In benchmarks, it has consistently outperformed other popular frameworks such as Flask and Django. For example, in one benchmark, FastAPI was found to be up to 6x faster than Flask and up to 35x faster than Django.

It’s worth noting that the performance of a web framework can depend on a variety of factors, such as the specific hardware and software it is running on, the complexity of the application, and the workload it is handling. In general, FastAPI is a very fast and efficient web framework, but the actual performance improvements you see in your own applications may vary.

Built-in Validation

FastAPI integrates with a library called Pydantic for data validation. Pydantic is a library that is built on top of Python’s built-in data types (such as int, str, and bool) and allows you to define complex, self-validating data models. These models can be used to automatically validate request payloads (e.g. JSON data) and convert them into Python objects.

One of the key benefits of using Pydantic for data validation is that it increases the security of your application. By using Pydantic to validate input data, you can ensure that your application only receives data that is in the correct format and meets certain requirements (e.g. a string must be a certain length or a number must be within a certain range). This can help to prevent security vulnerabilities such as injection attacks and other types of malicious input.

In addition to improving the security of your application, using Pydantic for data validation also has the benefit of automatically generating documentation for your API. FastAPI uses the same data models that you define with Pydantic to generate documentation for your API endpoints. This means that you don’t have to write separate documentation for your API – it is all generated automatically based on the code that powers your API. This makes it easy to keep your documentation accurate and up-to-date, and it also makes it easier for developers to understand how to use your API.

Here is an example of a Pydantic model that defines a user with a name, email, and age:

from pydantic import BaseModel

class User(BaseModel):
    name: str
    email: str
    age: int

This model defines a User class with three fields: name, email, and age. The data types for each field are specified using Python type hints. In this case, name and email are both strings and age is an integer.

Pydantic models also allow you to specify validation rules for each field. For example, you could require that the name field is at least 3 characters long and the email field is in a valid email format:

from pydantic import BaseModel

class User(BaseModel):
    name: str
    email: str
    age: int

    class Config:
        min_length = 3
        max_length = 100

In this example, the name field is required to be at least 3 characters long and no longer than 100 characters. Pydantic will automatically enforce these validation rules when you use the User model to validate data.

Writing Routes

Here is an example route for retrieving a User model using Flask:

from flask import Flask, jsonify
from models import User

app = Flask(__name__)

@app.route("/users/<int:user_id>", methods=["GET"])
def get_user(user_id):
    user = User.query.get(user_id)
    return jsonify(user.to_dict())

This route defines a function called get_user that is responsible for retrieving a user with a given ID. The user is retrieved using the User model’s query attribute, which is a SQLAlchemy query object. The get method is used to retrieve the user with the given ID. The user is then converted to a dictionary using the to_dict method and returned as a JSON response.

Here is the equivalent route using Django:

from django.shortcuts import get_object_or_404, render
from django.http import JsonResponse
from .models import User

def get_user(request, user_id):
    user = get_object_or_404(User, pk=user_id)
    return JsonResponse(user.to_dict())

This route defines a function called get_user that is responsible for retrieving a user with a given ID. The get_object_or_404 function is used to retrieve the user with the given ID. If the user does not exist, a 404 error will be returned. The user is then converted to a dictionary using the to_dict method and returned as a JSON response.

Here is the equivalent route using FastAPI:

from fastapi import FastAPI, HTTPException
from pydantic import BaseModel

app = FastAPI()

class User(BaseModel):
    id: int
    name: str
    email: str
    age: int

@app.get("/users/{user_id}")
def get_user(user_id: int):
    user = get_user_by_id(user_id)
    if user is None:
        raise HTTPException(status_code=404, detail="User not found")
    return user

This route defines a function called get_user that is responsible for retrieving a user with a given ID. The get_user_by_id function is a hypothetical function that retrieves a user with a given ID from a database. If the user does not exist, an HTTPException is raised with a status code of 404. If the user does exist, it is returned as a response.

Note that in this example, the User model is defined using Pydantic. This model is used to define the expected structure of the user object that is returned by the get_user function.

Who wrote FastAPI?

FastAPI was written by Sebastián Ramírez, also known as “tiangolo” on GitHub. Sebastián is a software engineer and entrepreneur from Uruguay who has been working on web development for over 15 years. He created FastAPI as a way to make it easier to build high-performance, well-documented APIs with Python. FastAPI is open-source software and is actively developed and maintained by Sebastián and a team of contributors.