Reader small image

You're reading from  Building Data Science Applications with FastAPI - Second Edition

Product typeBook
Published inJul 2023
Reading LevelIntermediate
PublisherPackt
ISBN-139781837632749
Edition2nd Edition
Languages
Tools
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

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 don’t have 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 two different approaches to integrating a database: using an object-relational mapping (ORM) system for SQL databases and 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:6.0

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 this book’s dedicated GitHub repository at https://github.com/PacktPublishing/Building-Data-Science-Applications-with-FastAPI-Second-Edition...

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 SQL, which has become the de facto standard...

Communicating with a SQL database with SQLAlchemy ORM

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. Since version 1.4, it also natively supports async.

The key thing to understand about this library is that it’s composed of two parts:

  • SQLAlchemy Core, which provides all the fundamental features to read and write data to SQL databases
  • SQLAlchemy ORM, which provides a powerful abstraction over SQL concepts

While you can choose to only use SQLAlchemy Core, it’s generally more convenient to use ORM. The goal of ORM is to abstract away the SQL concepts of tables and columns so that you only have to deal with Python objects. The role of ORM is to map those objects to the tables and columns they belong to and generate the corresponding SQL queries automatically.

The first step is...

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 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. Run the following command:

(venv) $ pip install motor

Once you’ve done this, we can start working!

Creating models that are compatible with MongoDB ID

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

Summary

Congratulations! You’ve reached another big milestone in mastering how to build 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.

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 the 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 - Second Edition
Published in: Jul 2023Publisher: PacktISBN-13: 9781837632749
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