Python APIs with FastAPI, Key Features and CRUD example

Lucas Oliveira
White Prompt Blog
Published in
7 min readApr 5, 2023

--

Nowadays, Python is one of the most popular coding languages in the world. This is due to the ease and different applications that the language can be used for. It is very common to see Python being applied in scripts, machine learning models and web applications.

In this article, we will introduce FastAPI, its main features and performance, and an application example of how Python compares to other popular frameworks out there.

At White Prompt, we believe that creating a robust application that lasts requires thinking and planning before building. Our architects work with you to create the blueprint of your product with rock-solid foundations.

We take the time to understand the complexities of the product and design the underlying architecture, while also ensuring scalability, performance, observability security, reliability, and quality.

If you are looking for a software development team to help you build and scale a solid product, contact us today for a consultation.

What is FastAPI?

FastAPI was released in 2018 by Sebastián Ramírez. He had the idea of creating FastAPI from some difficulties encountered when using the frameworks that existed at the time to carry out the task of developing APIs.

FastAPI boasts to be one of the fastest Python frameworks available, increasing development speeds by up to 300% with high performance. This framework uses features that were added in the latest versions of Python to create a modern tool for building APIs. In addition, FastAPI uses tools such as scarlett, Pydantic and OpenAPI to seek high performance, a low learning curve and ease of application coding.

Key Features

Performance

Undoubtedly, what draws the most attention to FastAPI is its performance test results. When compared to other more traditional frameworks like Django and Flask, FastAPI performs much stronger. This is due to the fact that the framework was built using Starlette, a lightweight ASGI framework/toolkit that is ideal for building async web services in Python.

In the image below, we can see the performance comparison between the various frameworks. FastAPI performs better than Django and Flask in this test, just behind Uvicorn and Starlette. , due to FastAPI when looking at their performance. This is due to Uvicorn and Starlette being a better fit as they are more specific frameworks for this specific case, however FastAPI and the other frameworks have more features in comparison.

By Techempower

Concurrency and Async / Await

The native Async support that FastAPI implements also supports the performance of your applications. This is an advantage over other Python 2 based frameworks that do not implement asynchronous programming.

Fast to Code

Thanks to the use of Type Hints and Pydantic, a simple and declarative syntax, FastAPI is considered a very lean framework and, like Flask, it uses the concept of modularity to add new features.

Automatic Documentation

With just a few lines of code, FastAPI manages to generate documentation of its endpoints using OpenAPI. We will see this function in the following example below.

Installation

Requirements

  • Python 3.7+

Let’s begin by installing FastAPI with the command here.

pip install fastapi

You will also need an ASGI server, for production purposes such as Uvicorn or Hypercorn.

pip install "uvicorn[standard]"

For this example we will also use SQLAlchemy ORM.

pip install SQLAlchemy

Movies CRUD API

Now, let’s reference this Github project: https://github.com/Lucas-loliveira/OTT-FastAPI

Next, we will create a simple application which consists of an API that CRUDs a table called Movies.

After installing FastAPI, Uvicorn and SQLAlquemy, we will create the following file structure.

Database

Let’s begin by creating the module that will manage our database. In this module we will use the SQLAlchemy ORM to manage our SQLite database, create our movie model and access the data.

The src/db/database.pyfile will be responsible for creating the database connection and managing sessions.

In the src/db/models.py file we will create our Movies table that will contain attributes id, title, director, duration_in_minutes and rating.

Finally, we will create the src/db/repositories.py file that will serve as an interface so that our API layer can access the database resources.

Schemas

The src/schemas.py file will contain classes to represent the data that will be received and returned in the body of an HTTP request or response. To create these classes we will use Pydantic, a library that comes with the installation of FastAPI. Pydantic aims to provide a simpler, more straightforward way to perform data validation through the use of Pythons' Type Hints functionality.

In the MovieBase class we have the basic attributes present in both the requests and the API responses. This class was created to reduce code duplication. Notice that in addition to using the Type Hints, the duration_in_minutes and rating attributes use a Pydantic validation.

Also, we create within the MovieResponse class a different class called Config that serves to pass additional configurations to our Pydantic model. The configuration we made set the orm_mode option to True, which enables a static method within the class called from_orm. This class allows the creation of an instance of the Pydantic model from a model class of our ORM.

FastAPIs CRUD

Now, we are ready to create the src/main.py file where we will instantiate our FastApi app. In addition to the FastAPI file, we are importing the elements of SQLAlchemy into this file to make the connection with the database, the schema classes we created earlier, and the classes that serve for data typing.

Our first function is the create function, which is responsible for registering movies in our database. The function uses the @app.post decorator so that the route is interpreted as a POST. In this decorator we inform the route of our endpoint, response_model, that informs what type of data will be contained in the response body, and finally the status_code that defines the expected HTTP status after a successful request.

In the create method, we define a parameter called request which is of type MovieRequest. This parameter receives the data that was passed in the body of the request. We also have a second parameter called db of type Session which has the Depends(get_db) instruction as its default value. At this moment we are performing dependency injection, and FastAPI will execute the get_db function. This will return an instance of the LocalSession class which is the database session; it will then pass this session to our create function.

The other endpoints for listing all movies, searching for a movie by id, updating a movie, and deleting a movie follow the same pattern as the create endpoint. All endpoints have a route and an HTTP verb, in addition to having responses with a status of failure in case a movie id is not found, for example.

Run the Application

With all of the code ready to go, we can now run our application.

uvicorn main:app --reload

Automatic Documentation

As we previously saw, one of the main features of FastAPI is the easy creation of automated documentation with OpenAPI. After performing the local deployment of our application, we access http://localhost:8000/docs route and we can find an interactive documentation with all our endpoints, models and validations. To think that all of this was created using only Pydantic and Type Hints!

FastAPI vs. Flask vs. Django

When we talk about web application development with Python, the most popular frameworks are Django and Flask.

Django was released in 2005 and until today it is the most used framework with a large amount of study materials, libraries and an active community. Django follows a monolithic structure, and has its own ORM as well as popular frameworks like DRF. Because of it’s structure, Django is considered to be a complete framework and recommended for complex applications.

Flask, on the other hand, is considered to be the opposite of Django. It is classified as a microframework that uses a modular structure in which we can use different libraries and frameworks to build the application. Flask is recommended for small applications due to its simplicity and rapid development.

Ultimately, FastAPI tries to strike a balance between simplicity and a larger amount of native features while focusing on performance. The framework gained popularity for using newer features that other frameworks did not due to being outdated. It is recommended to use FastAPI in tools that need high performance, low latency and higher development speeds. However, one should consider that because it is a relatively new framework, it does not have such a large number of libraries in addition to having a smaller community.

By quintagroup

Conclusion

In conclusion, FastAPI has several advantages which include easy coding of applications, simple to use, quick to learn, has a user-friendly interface, and is compatible with most Python libraries and tools. However, like any technology, it also has its limitations, such as a relatively small community and a limited number of tutorials and resources compared to more established frameworks like Flask and Django. Ultimately, the decision to use FastAPI will depend on the specific needs of the project and the experience of the development team. However, with its speed and ease of use, FastAPI is certainly worth considering for any future API development projects.

We think and we do!

Working with us at White Prompt can lead to great outcomes for your project or application. Do you have a business that requires an efficient and powerful data architecture to succeed? Looking for a software development agency to make it happen? Get in touch with us at White Prompt today!

--

--