Reader small image

You're reading from  Building Data Science Applications with FastAPI

Product typeBook
Published inOct 2021
Reading LevelBeginner
PublisherPackt
ISBN-139781801079211
Edition1st Edition
Languages
Concepts
Right arrow
Author (1)
François Voron
François Voron
author image
François Voron

François Voron graduated from the University of Saint-Étienne (France) and the University of Alicante (Spain) with a master's degree in machine learning and data mining. A full stack web developer and a data scientist, François has a proven track record working in the SaaS industry, with a special focus on Python backends and REST APIs. He is also the creator and maintainer of FastAPI Users, the #1 authentication library for FastAPI, and is one of the top experts in the FastAPI community.
Read more about François Voron

Right arrow

Chapter 6: Databases and Asynchronous ORMs

The main goal of a REST API is, of course, to read and write data. So far, we've solely worked with the tools given by Python and FastAPI, allowing us to build reliable endpoints to process and answer requests. However, we haven't been able to effectively retrieve and persist that information: we missed a database.

The goal of this chapter is to show you how you can interact with different types of databases and related libraries inside FastAPI. It's worth noting that FastAPI is completely agnostic regarding databases: you can use any system you want and it's your responsibility to integrate it. This is why we'll review three different approaches to integrate a database, that is, using basic SQL queries, using Object-Relational Mapping (ORM), and, finally, using a NoSQL database.

In this chapter, we're going to cover the following main topics:

  • An overview of relational and NoSQL databases
  • Communicating...

Technical requirements

For this chapter, you'll require a Python virtual environment, just as we set up in Chapter 1, Python Development Environment Setup.

For the Communicating with a MongoDB database using Motor section, you'll need a running MongoDB server on your local computer. The easiest way to do this is to run it as a Docker container. If you've never used Docker before, we recommend that you refer to the Getting started tutorial in the official documentation at https://docs.docker.com/get-started/. Once you have done this, you'll be able to run a MongoDB server using this simple command:

$ docker run -d --name fastapi-mongo -p 27017:27017 mongo:4.4

The MongoDB server instance will then be available on your local computer at port 27017.

You can find all the code examples for this chapter in the dedicated GitHub repository at https://github.com/PacktPublishing/Building-Data-Science-Applications-with-FastAPI/tree/main/chapter6.

An overview of relational and NoSQL databases

The role of a database is to store data in a structured way, preserve the integrity of the data, and offer a query language that enables you to retrieve this data when an application needs it.

Nowadays, when it comes to choosing a database for your web project, you have two main choices: relational databases, with their associated SQL query language, and NoSQL databases, named in opposition to the first category.

Selecting the right technology for your project is left up to you, as it greatly depends on your needs and requirements. In this section, we'll outline the main characteristics and features of those two database families and try to give you some insights into choosing the right one for your project.

Relational databases

Relational databases have existed since the 1970s, and they have proved to be very performant and reliable over time. They are almost inseparable from the SQL query language, which has become the...

Communicating with a SQL database with SQLAlchemy

To begin, we'll discuss how to work with a relational database using the SQLAlchemy library. SQLAlchemy has been around for years and is the most popular library in Python when you wish to work with SQL databases.

In this chapter, it's worth noting that we'll only consider the core part of the library, which only provides the tools to abstract communication with a SQL database. We won't consider the ORM part, as, in the next section, we'll focus on another ORM: Tortoise. As such, in this section, we'll pay very close attention to the SQL language.

Recently, async support has been added in version 1.4 but is not yet considered stable. That's why, for now, we'll combine it with the databases library by Encode, the same team behind Starlette, which provides an asynchronous connection layer for SQLAlchemy. In Figure 6.3, we have presented a schema for you to better visualize the interaction...

Communicating with a SQL database with Tortoise ORM

When dealing with relational databases, you might wish to abstract away the SQL concepts and only deal with proper objects from the programming language. That's the main motivation behind ORM tools. In this section, we'll examine how to work with Tortoise ORM, which is a modern and asynchronous ORM that fits nicely within a FastAPI project. It's greatly inspired by the Django ORM; so, if you've ever worked with it, you'll probably be on familiar ground.

As usual, the first step is to install the library using the following command:

$ pip install tortoise-orm

If you need drivers for database engines such as PostgreSQL or MySQL, you can install them, as explained in the documentation at https://tortoise-orm.readthedocs.io/en/latest/getting_started.html#installation. We're now ready to work!

Creating database models

The first step is to create the Tortoise model for your entity. This is a...

Communicating with a MongoDB database using Motor

As we mentioned at the beginning of this chapter, working with a document-oriented database, such as MongoDB, is quite different from a relational database. First and foremost, you don't need to configure a schema upfront: it follows the structure of the data that you insert into it. In the case of FastAPI, it makes our life slightly easier since we'll only have to work with Pydantic models. However, there are some subtleties around the document identifiers that we need to take into account. We'll review this next.

To begin, we'll install Motor, which is a library that is used to communicate asynchronously with MongoDB and is officially supported by the MongoDB organization. You can run the following command:

$ pip install motor

Once this is done, we can start working!

Creating models compatible with MongoDB ID

As we mentioned in the introduction to this section, there are some difficulties with the...

Summary

Congratulations! You've reached another big milestone in your mastering of building a REST API with FastAPI. As you know, databases are an essential part of every system; they allow you to save data in a structured way and retrieve it precisely and reliably thanks to powerful query languages. You are now able to leverage their power in FastAPI, whether they are relational databases or document-oriented databases. Additionally, you've seen the differences between working with and without an ORM to manage relational databases, and you have also learned about the importance of a good migration system when working with such databases.

Serious things can now happen: users can send and retrieve data to and from your system. However, this poses a new challenge to tackle. This data needs to be protected so that it can remain private and secure. This is exactly what we'll discuss in our next chapter: how to authenticate users and set up FastAPI for maximum security...

lock icon
The rest of the chapter is locked
You have been reading a chapter from
Building Data Science Applications with FastAPI
Published in: Oct 2021Publisher: PacktISBN-13: 9781801079211
Register for a free Packt account to unlock a world of extra content!
A free Packt account unlocks extra newsletters, articles, discounted offers, and much more. Start advancing your knowledge today.
undefined
Unlock this book and the full library FREE for 7 days
Get unlimited access to 7000+ expert-authored eBooks and videos courses covering every tech area you can think of
Renews at $15.99/month. Cancel anytime

Author (1)

author image
François Voron

François Voron graduated from the University of Saint-Étienne (France) and the University of Alicante (Spain) with a master's degree in machine learning and data mining. A full stack web developer and a data scientist, François has a proven track record working in the SaaS industry, with a special focus on Python backends and REST APIs. He is also the creator and maintainer of FastAPI Users, the #1 authentication library for FastAPI, and is one of the top experts in the FastAPI community.
Read more about François Voron