Open In App

FastAPI Architecture

FastAPI is a cutting-edge Python web framework that simplifies the process of building robust REST APIs. In this article, we will explore the fundamental aspects of architecture by delving into its core components.

What is FastAPI?

FastAPI is a modern, fast (high-performance), web framework for building APIs with Python 3.6+ based on standard Python type hints. It is designed to be easy to use, efficient, and reliable, making it a popular choice for developing RESTful APIs and web applications. FastAPI has gained popularity due to its simplicity, automatic documentation generation, and excellent performance.



Features of FastAPI

Core Components of FastAPI

First, you’ll need to install FastAPI and an ASGI server, such as uvicorn, if you haven’t already. You can install them using pip:

pip install fastapi uvicorn

Endpoints

Endpoints in FastAPI are Python functions that handle incoming HTTP requests. They are defined using the @app.route decorator. Endpoints can have path parameters, query parameters, request bodies, and more. FastAPI automatically handles data validation, serialization, and deserialization based on Python type hints.
The code for endpoints can be found in various places, reflecting the organization of the project. Specifically, endpoints are defined within the “fastapi/routing/ directory”. However, the actual endpoint definitions and route handling are distributed across multiple files due to the modularity of the library.



Overview of where we can find endpoints in the FastAPI repository.




from fastapi import FastAPI
app = FastAPI()
@app.get("/")
def read_root():
    return {"message": "Hello, World!"}
@app.get("/items/{item_id}")
def read_item(item_id: int, q: str = None):
    return {"item_id": item_id, "q": q}

Request Handling

When a request is received, FastAPI automatically parses and validates query parameters, request bodies (JSON, form data), path parameters, and headers using Python type hints. Data validation and serialization are automatically handled, reducing the boilerplate code required for input validation.
In FastAPI, request handling logic is primarily defined in router modules. Routers handle incoming HTTP requests, and their logic is defined in separate Python files within the routers directory of the FastAPI repository. Each router file contains endpoint definitions, request handling functions, and route configurations. You can find request handling logic in various router files within the FastAPI repository’s routers directory.

Example: Create a file (for example, main.py) with the following code:

We import the FastAPI class and create an instance of it.We define a Pydantic model Item to represent the expected request data. Pydantic models are used for data validation and serialization.We create a route using the @app.post(“/items/”) decorator. The create_item function is the request handler for this route. It takes an Item object as input.Inside the create_item function, we create a dictionary containing the received item data.The function returns this dictionary, which FastAPI automatically serializes into JSON before sending it as the response.




from fastapi import FastAPI
app = FastAPI()
class Item:
    def __init__(self, name, description, price):
        self.name = name
        self.description = description
        self.price = price
@app.post("/items/")
async def create_item(item: Item):
    """
    Create an item with a name, description, and price.
    """
    item_dict = {
        "name": item.name,
        "description": item.description,
        "price": item.price,
    }
    return item_dict

To run the FastAPI application, use the following command:

uvicorn main:app --reload

This command starts the ASGI server (uvicorn) and tells it to run the app instance from the main.py file. The –reload flag enables automatic code reloading during development.

You can test the API by sending a POST request to http://localhost:8000/items/ with JSON data containing “name”, “description”, and “price”. FastAPI will handle the request, validate the input data, and serialize the output data back to JSON before sending the response.
If you send this post request
curl -X POST -H “Content-Type: application/json” -d ‘{“name”: “Example Item”, “description”: “Test Description”, “price”: 19.99}’ http://localhost:8000/items/

Ouput for the above code

We can see that post request is handled successfully and get request is not mentioned it is failed without giving error on the user side.

Data Models (Pydantic Models)

In FastAPI, Pydantic models are used for defining the data structures of your application. These models not only serve as a powerful tool for data validation but also play a central role in automatic documentation generation and serialization/deserialization of data. Pydantic models are typically defined in the schemas directory within the FastAPI application, and they help ensure that the data sent to and received from the API endpoints adhere to the specified structure and constraints.
In the FastAPI repository, you can find Pydantic models defined in the schemas directory within the respective router modules. For example, if you have an items router handling item-related endpoints, you might define a Pydantic model for items in a file like schemas/item.py

Dependency Injection System

FastAPI provides a powerful dependency injection system, allowing you to declare dependencies for your endpoints. Dependencies can be used for authentication, database connections, external services, etc. FastAPI manages the instantiation and lifecycle of these dependencies.
The internal implementation of FastAPI’s dependency injection system involves a combination of Python’s type hinting, function annotations, and a mechanism to inspect these annotations during the request handling process. Overview of how FastAPI handles dependency injection internally:

Response Generation

FastAPI generates responses by utilizing Python’s type hinting system, Pydantic models, and the JSON serialization capabilities of the underlying Starlette framework. The response generation process in FastAPI involves the following steps:

Internally, FastAPI leverages the response generation capabilities provided by the Starlette framework, on which FastAPI is built. Starlette handles the low-level HTTP handling and response generation, while FastAPI enriches this process by providing high-level abstractions, automatic validation, and Pydantic model integration, making it easier for developers to work with responses in a strongly typed and intuitive manner.

Middleware

In FastAPI, middlewares are implemented and managed using the underlying Starlette framework, which provides a flexible and powerful middleware system. FastAPI builds upon Starlette’s middleware capabilities to allow developers to define custom middleware functions and apply them to specific routes or the entire application. Here is the overview of middlewares in FastAPI and Starlette:

While the internal implementation details of middlewares are handled by the Starlette framework, FastAPI offers a clean and intuitive interface for developers to define, manage, and apply middlewares to their applications, enhancing the application’s functionality and customization capabilities.

FastAPI’s core components make it a reliable framework, providing developers with a robust, efficient, and intuitive solution for building APIs with Python. Its architecture promotes clean and readable code while managing complex tasks such as data validation, serialization, and dependency management under the hood.


Article Tags :