question-mark
Stuck on an issue?

Lightrun Answers was designed to reduce the constant googling that comes with debugging 3rd party libraries. It collects links to all the places you might be looking at while hunting down a tough bug.

And, if you’re still stuck at the end, we’re happy to hop on a call to see how we can help out.

What is the best tool or ORM to manage database in Fast API?

See original GitHub issue

First Check

  • I added a very descriptive title to this issue.
  • I used the GitHub search to find a similar issue and didn’t find it.
  • I searched the FastAPI documentation, with the integrated search.
  • I already searched in Google “How to X in FastAPI” and didn’t find any information.
  • I already read and followed all the tutorial in the docs and didn’t find an answer.
  • I already checked if it is not related to FastAPI but to Pydantic.
  • I already checked if it is not related to FastAPI but to Swagger UI.
  • I already checked if it is not related to FastAPI but to ReDoc.

Commit to Help

  • I commit to help with one of those options 👆

Example Code

from typing import List

import databases
import sqlalchemy
from fastapi import FastAPI
from pydantic import BaseModel

# SQLAlchemy specific code, as with any other app
DATABASE_URL = "sqlite:///./test.db"
# DATABASE_URL = "postgresql://user:password@postgresserver/db"

database = databases.Database(DATABASE_URL)

metadata = sqlalchemy.MetaData()

notes = sqlalchemy.Table(
    "notes",
    metadata,
    sqlalchemy.Column("id", sqlalchemy.Integer, primary_key=True),
    sqlalchemy.Column("text", sqlalchemy.String),
    sqlalchemy.Column("completed", sqlalchemy.Boolean),
)


engine = sqlalchemy.create_engine(
    DATABASE_URL, connect_args={"check_same_thread": False}
)
metadata.create_all(engine)


class NoteIn(BaseModel):
    text: str
    completed: bool


class Note(BaseModel):
    id: int
    text: str
    completed: bool


app = FastAPI()


@app.on_event("startup")
async def startup():
    await database.connect()


@app.on_event("shutdown")
async def shutdown():
    await database.disconnect()


@app.get("/notes/", response_model=List[Note])
async def read_notes():
    query = notes.select()
    return await database.fetch_all(query)


@app.post("/notes/", response_model=Note)
async def create_note(note: NoteIn):
    query = notes.insert().values(text=note.text, completed=note.completed)
    last_record_id = await database.execute(query)
    return {**note.dict(), "id": last_record_id}

Description

I read FastAPI documentation, but still not clear which tools should use to manage database in FastAPI projects. encode/databases + SqlAlchemy or tortoise-orm?

Operating System

Linux, Windows

Operating System Details

No response

FastAPI Version

0.75.0

Python Version

3.7 +

Additional Context

No response

Issue Analytics

  • State:open
  • Created 2 years ago
  • Comments:8 (1 by maintainers)

github_iconTop GitHub Comments

3reactions
yinziyan1206commented, Mar 7, 2022

I use SqlModel and SqlAlchemy Core. I think it better to use the official ORM tool for FastAPI 😃

1reaction
Leon0824commented, Jun 1, 2022

Try Prisma.

Define your schema in its Prisma language, and use its generator to generate whole pydantic / db hybrid models. Then import the models module into your project.

Read more comments on GitHub >

github_iconTop Results From Across the Web

SQL (Relational) Databases - FastAPI
FastAPI works with any database and any style of library to talk to the database. A common pattern is to use an "ORM":...
Read more >
Best ORM to use with FastAPI? : r/Python - Reddit
I'm totally willing to experiment with something new. Right now I'm leaning towards Tortoise with SQLAlchemy as a safe vanilla choice for backup ......
Read more >
Profiling ORM in FastAPI. At Indigo Ag, we love Python and we…
This is why for one of our projects, we decided to use FastAPI, an open source Python web framework for building… you guessed...
Read more >
The Ultimate FastAPI Tutorial Part 7 - Database Setup with ...
SQLAlchemy is one of the most widely used and highest quality Python third-party libraries. It gives application developers easy ways to work ...
Read more >
SQLModel: The New ORM for FastAPI and Beyond - YouTube
Two frameworks that have taken the Python world by storm are FastAPI and Pydantic. Once you already have your data exchange modeled in ......
Read more >

github_iconTop Related Medium Post

No results found

github_iconTop Related StackOverflow Question

No results found

github_iconTroubleshoot Live Code

Lightrun enables developers to add logs, metrics and snapshots to live code - no restarts or redeploys required.
Start Free

github_iconTop Related Reddit Thread

No results found

github_iconTop Related Hackernoon Post

No results found

github_iconTop Related Tweet

No results found

github_iconTop Related Dev.to Post

No results found

github_iconTop Related Hashnode Post

No results found