FastAPI Database Sqlalchemy
Getting Started with FastAPI, Database, and SQLAlchemy
In this tutorial, we will explore how to create a FastAPI application that interacts with a database using SQLAlchemy. FastAPI is a modern, fast (high-performance), web framework for building APIs with Python 3.7+ based on standard Python type hints. SQLAlchemy is a SQL toolkit and Object-Relational Mapping (ORM) system for Python. This tutorial will guide you through setting up a FastAPI project, creating a database, and using SQLAlchemy to interact with the database.
Setting Up a FastAPI Project
To start, you need to install FastAPI and uvicorn, which is an ASGI web server. You can install them using pip:
pip install fastapi uvicorn
Next, create a new Python file, e.g., `main.py`, and add the following code to create a basic FastAPI application:
from fastapi import FastAPI
app = FastAPI()
@app.get("/")
def read_root():
return {"Hello": "World"}
This code creates a FastAPI application with a single route, `/`, that returns a JSON response.
Creating a Database
For this tutorial, we will use SQLite as our database. You can create a new SQLite database using the `sqlite3` command in your terminal:
sqlite3 database.db
This will create a new file called `database.db` in your current directory. You can exit the SQLite shell by typing `.quit`.
Installing SQLAlchemy
To use SQLAlchemy with FastAPI, you need to install it using pip:
pip install sqlalchemy
Once installed, you can import SQLAlchemy in your FastAPI application and create a database engine:
from sqlalchemy import create_engine
engine = create_engine('sqlite:///database.db')
This code creates a database engine that connects to the `database.db` file.
Defining Models with SQLAlchemy
To interact with the database, you need to define models using SQLAlchemy. For example, let’s create a `User` model:
from sqlalchemy import Column, Integer, String
from sqlalchemy.ext.declarative import declarative_base
Base = declarative_base()
class User(Base):
__tablename__ = 'users'
id = Column(Integer, primary_key=True)
name = Column(String)
email = Column(String)
This code defines a `User` model with `id`, `name`, and `email` columns.
Creating Tables and Interacting with the Database
To create the tables in the database, you can use the `Base.metadata.create_all()` method:
Base.metadata.create_all(engine)
Once the tables are created, you can interact with the database using SQLAlchemy’s ORM. For example, you can create a new user:
from sqlalchemy.orm import sessionmaker
Session = sessionmaker(bind=engine)
session = Session()
new_user = User(name='John Doe', email='john@example.com')
session.add(new_user)
session.commit()
This code creates a new `User` object, adds it to the session, and commits the changes to the database.
Using SQLAlchemy with FastAPI
To use SQLAlchemy with FastAPI, you can create a dependency that provides a database session:
from fastapi import Depends
def get_session():
session = Session()
try:
yield session
finally:
session.close()
@app.get("/users/")
def read_users(session: Session = Depends(get_session)):
users = session.query(User).all()
return [{"id": user.id, "name": user.name, "email": user.email} for user in users]
This code creates a dependency that provides a database session and uses it to query the `users` table.
Conclusion
In this tutorial, we have explored how to create a FastAPI application that interacts with a database using SQLAlchemy. We have covered setting up a FastAPI project, creating a database, installing SQLAlchemy, defining models, creating tables, and interacting with the database. We have also seen how to use SQLAlchemy with FastAPI to create a RESTful API. With this knowledge, you can build robust and scalable APIs that interact with databases using FastAPI and SQLAlchemy.