What is the best tool or ORM to manage database in Fast API?
See original GitHub issueFirst 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:
- Created 2 years ago
- Comments:8 (1 by maintainers)
Top 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 >Top Related Medium Post
No results found
Top Related StackOverflow Question
No results found
Troubleshoot Live Code
Lightrun enables developers to add logs, metrics and snapshots to live code - no restarts or redeploys required.
Start FreeTop Related Reddit Thread
No results found
Top Related Hackernoon Post
No results found
Top Related Tweet
No results found
Top Related Dev.to Post
No results found
Top Related Hashnode Post
No results found
Top GitHub Comments
I use SqlModel and SqlAlchemy Core. I think it better to use the official ORM tool for FastAPI 😃
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.