Uncategorized
Getting Started with FastAPI and SQLAlchemy
Jane Doe
Getting Started with FastAPI and SQLAlchemy
FastAPI is a modern, fast (high-performance), web framework for building APIs with Python 3.8+ based on standard Python type hints.
Why FastAPI?
- Very high performance: On par with NodeJS and Go (thanks to Starlette and Uvicorn).
- Fast to code: Increase the speed to develop features by about 200% to 300%.
- Fewer bugs: Reduce about 40% of human (developer) induced errors.
- Intuitive: Great editor support. Completion everywhere. Less time debugging.
Code Example: Define a Route
Here is how simple it is to write an asynchronous FastAPI endpoint:
python
from fastapi import FastAPI
app = FastAPI()
@app.get("/")
async def read_root():
return {"hello": "world"}Adding SQLAlchemy for Database Access
SQLAlchemy 2.0 supports async/await natively. We can easily map our relational tables to Python objects:
python
from sqlalchemy.orm import Mapped, mapped_column
from app.db.base import Base
class Blog(Base):
__tablename__ = "blogs"
id: Mapped[int] = mapped_column(primary_key=True)
title: Mapped[str] = mapped_column(nullable=False)Click here to read the official FastAPI docs for more details!