Chapter 6: Connecting to a Database
In the last chapter, we looked at how to structure a FastAPI application. We successfully implemented some routes and models for our application and tested the endpoints. However, the application still uses an in-app database to store the events. In this chapter, we will migrate the application to use a proper database.
A database can be simply referred to as a storehouse for data. In this context, a database enables us to store data permanently, as opposed to an in-app database, which is wiped off upon any app restart or crash. A database is a table housing columns, referred to as fields, and rows, referred to as records.
By the end of this chapter, you will be equipped with the knowledge of how to connect a FastAPI application to a database. This chapter will explain how to connect to a SQL database using SQLModel and a MongoDB database via Beanie. (However, the application will make use of MongoDB as its primary database in later chapters...