DEV Community

Cover image for Integrating Databases with FastAPI
Joel-Steve NIKENOUEBA
Joel-Steve NIKENOUEBA

Posted on

Integrating Databases with FastAPI

Exploring Database Integration in FastAPI Applications

In today’s digital landscape, building robust and efficient web applications often involves the integration of various types of databases. FastAPI, a modern web framework for building APIs with Python, offers seamless integration with different database systems, including SQL and NoSQL databases. In this article, we’ll delve into the process of integrating databases with FastAPI, utilizing popular libraries such as SQLAlchemy and Tortoise ORM.

Introduction to Database Integration in FastAPI:

FastAPI provides excellent support for integrating databases into your applications, allowing you to store and retrieve data efficiently. By leveraging the asynchronous capabilities of Python and integrating with powerful database libraries, FastAPI enables developers to build high-performance applications with ease.

Types of Databases Supported:
FastAPI supports integration with a wide range of database systems, including:

1 - SQL Databases: Such as PostgreSQL, MySQL, SQLite, etc.
2 - NoSQL Databases: Such as MongoDB, Redis, Cassandra, etc.

Integration with SQLAlchemy for SQL Databases:

SQLAlchemy is a popular SQL toolkit and Object-Relational Mapping (ORM) library for Python. It provides a powerful and flexible way to work with SQL databases while abstracting away the complexities of raw SQL queries. FastAPI seamlessly integrates with SQLAlchemy, allowing you to define database models and interact with the database using Pythonic syntax.

Example: Integration with SQLAlchemy:

from fastapi import FastAPI
from sqlalchemy import create_engine, Column, Integer, String
from sqlalchemy.ext.declarative import declarative_base
from sqlalchemy.orm import sessionmaker

# Create FastAPI instance
app = FastAPI()

# SQLAlchemy configuration
SQLALCHEMY_DATABASE_URL = "sqlite:///./test.db"
engine = create_engine(SQLALCHEMY_DATABASE_URL)
SessionLocal = sessionmaker(autocommit=False, autoflush=False, bind=engine)
Base = declarative_base()

# Define database model
class User(Base):
    __tablename__ = "users"
    id = Column(Integer, primary_key=True, index=True)
    name = Column(String, index=True)
    email = Column(String, unique=True, index=True)

# Create tables
Base.metadata.create_all(bind=engine)
Enter fullscreen mode Exit fullscreen mode

In this example, we define a User model using SQLAlchemy's declarative syntax. We then create the database tables by calling Base.metadata.create_all().

Integration with Tortoise ORM for Async SQL Databases:

Tortoise ORM is an easy-to-use asynchronous ORM inspired by Django ORM. It provides native support for asynchronous operations, making it an excellent choice for building high-performance asynchronous applications with FastAPI. Tortoise ORM seamlessly integrates with FastAPI, allowing you to define models and interact with the database asynchronously.

Example: Integration with Tortoise ORM:

from fastapi import FastAPI
from tortoise import Tortoise, fields
from tortoise.models import Model

# Create FastAPI instance
app = FastAPI()

# Tortoise ORM configuration
TORTOISE_ORM = {
    "connections": {"default": "sqlite://./test.db"},
    "apps": {
        "models": {
            "models": ["__main__"],
            "default_connection": "default",
        }
    },
}

# Define database model
class User(Model):
    id = fields.IntField(pk=True)
    name = fields.CharField(max_length=50)
    email = fields.CharField(max_length=100, unique=True)

# Initialize Tortoise ORM
Tortoise.init_models(["__main__"], "models")
Tortoise.init_models(["models"], "models")

# Create database tables
async def init():
    await Tortoise.generate_schemas()

# Run initialization function
app.add_event_handler("startup", init)

Enter fullscreen mode Exit fullscreen mode

In this example, we define a User model using Tortoise ORM's syntax. We then initialize Tortoise ORM and generate the database schemas using Tortoise.generate_schemas().

Conclusion:

Integrating databases with FastAPI is straightforward and efficient, thanks to its robust support for various database systems and seamless integration with popular ORM libraries like SQLAlchemy and Tortoise ORM. By leveraging these tools, developers can build scalable and performant web applications with ease, while ensuring data integrity and reliability.

In conclusion, integrating databases with FastAPI empowers developers to create powerful and feature-rich applications that meet the demands of modern web development. Whether you’re working with SQL or NoSQL databases, FastAPI provides the tools and flexibility you need to build efficient and scalable applications.

Top comments (1)

Collapse
 
techbelle profile image
rachelle palmer

If you're in a rush you can use either the PostgreSQL app generator (github.com/tiangolo/full-stack-fas...) or the MongoDB FastAPI app generator (github.com/mongodb-labs/full-stack...) and eliminate much of the boilerplate