Learning FastAPI for Beginners – Part 13: FastAPI Relational Database One to Many

Posted by

Welcome to Part 13 of our FastAPI tutorial series for beginners! In this tutorial, we will be looking at how to work with relational databases using FastAPI, specifically focusing on the one-to-many relationship.

To get started, you will need some knowledge of FastAPI, Python, and relational databases. If you haven’t already, be sure to check out our previous tutorials in this series for a better understanding of FastAPI.

One-to-many relationships are a common scenario in database modeling where one entity is associated with multiple entities of another entity. For example, a blog post entity can have multiple comments associated with it.

For this tutorial, we will be using SQLite as our relational database. First, let’s create a new FastAPI project and set up our database connection.

<!DOCTYPE html>
<html>
<head>
    <title>FastAPI One-to-Many Tutorial</title>
</head>
<body>
    <h1>FastAPI One-to-Many Tutorial</h1>
    <p>Let's get started with setting up our database connection</p>
</body>
</html>

Now, let’s create our database connection and define our models. We will create two models – Post and Comment, where each post can have multiple comments associated with it.

from sqlalchemy import create_engine, Column, Integer, String, ForeignKey
from sqlalchemy.ext.declarative import declarative_base
from sqlalchemy.orm import relationship, sessionmaker

DATABASE_URL = "sqlite:///./test.db"
Base = declarative_base()

class Post(Base):
    __tablename__ = 'posts'

    id = Column(Integer, primary_key=True, index=True)
    title = Column(String)
    content = Column(String)

class Comment(Base):
    __tablename__ = 'comments'

    id = Column(Integer, primary_key=True, index=True)
    text = Column(String)
    post_id = Column(Integer, ForeignKey('posts.id'))

    post = relationship("Post", back_populates="comments")

Next, let’s create our database tables and session.

engine = create_engine(DATABASE_URL)
Base.metadata.create_all(bind=engine)

SessionLocal = sessionmaker(autocommit=False, autoflush=False, bind=engine)

def get_db():
    db = SessionLocal()
    try:
        yield db
    finally:
        db.close()

Now that we have our database connection set up, let’s create our API endpoints to handle creating and retrieving posts and comments. We will also include a route to retrieve all comments for a specific post.

from fastapi import FastAPI, Depends, HTTPException
from sqlalchemy.orm import Session

app = FastAPI()

@app.post("/posts/")
def create_post(title: str, content: str, db: Session = Depends(get_db)):
    post = Post(title=title, content=content)
    db.add(post)
    db.commit()
    db.refresh(post)
    return post

@app.get("/posts/{post_id}")
def get_post(post_id: int, db: Session = Depends(get_db)):
    post = db.query(Post).filter(Post.id == post_id).first()
    if post is None:
        raise HTTPException(status_code=404, detail="Post not found")
    return post

@app.post("/posts/{post_id}/comments/")
def create_comment(post_id: int, text: str, db: Session = Depends(get_db)):
    post = db.query(Post).filter(Post.id == post_id).first()
    if post is None:
        raise HTTPException(status_code=404, detail="Post not found")

    comment = Comment(text=text, post_id=post_id)
    db.add(comment)
    db.commit()
    db.refresh(comment)
    return comment

@app.get("/posts/{post_id}/comments/")
def get_comments(post_id: int, db: Session = Depends(get_db)):
    post = db.query(Post).filter(Post.id == post_id).first()
    if post is None:
        raise HTTPException(status_code=404, detail="Post not found")

    comments = db.query(Comment).filter(Comment.post_id == post_id).all()
    return comments

And that’s it! We have successfully set up our FastAPI application to work with a one-to-many relational database. You can now try creating posts, adding comments to posts, and fetching comments for a specific post.

In this tutorial, we have covered how to work with a one-to-many relationship in a relational database using FastAPI. We hope you found this tutorial helpful and are now more confident in working with databases in your FastAPI projects.

Stay tuned for more tutorials in our FastAPI series, where we will cover more advanced topics and features. Happy coding!