FastAPI Extensions


What are FastAPI extensions?

FastAPI extensions are third-party libraries or tools that enhance the capabilities of FastAPI applications. These extensions help you integrate various functionalities like databases, authentication, background tasks, real-time communications, and more into your FastAPI projects. FastAPI has a growing ecosystem of extensions that make it easier to add common features without reinventing the wheel.


What is fastapi-sqlalchemy?

fastapi-sqlalchemy is a popular extension that provides seamless integration between SQLAlchemy and FastAPI. It manages SQLAlchemy sessions, allowing you to perform database operations without worrying about session handling and lifecycle management in your FastAPI application.

Example of using fastapi-sqlalchemy:

from fastapi import FastAPI
from fastapi_sqlalchemy import DBSessionMiddleware, db
from sqlalchemy import Column, Integer, String
from sqlalchemy.ext.declarative import declarative_base

app = FastAPI()
app.add_middleware(DBSessionMiddleware, db_url="sqlite:///test.db")

Base = declarative_base()

class User(Base):
    __tablename__ = "users"
    id = Column(Integer, primary_key=True)
    name = Column(String)

@app.get("/users/")
async def get_users():
    users = db.session.query(User).all()
    return users

In this example, fastapi-sqlalchemy is used to manage SQLAlchemy sessions in a FastAPI application, simplifying database interaction by automatically handling the session lifecycle.


What is fastapi-users?

fastapi-users is an extension that simplifies user authentication, registration, and management in FastAPI applications. It provides pre-built utilities for handling user login, registration, password reset, and verification using JWT, OAuth2, and other common authentication methods.

Example of using fastapi-users for user authentication:

from fastapi import FastAPI
from fastapi_users import FastAPIUsers
from fastapi_users.db import SQLAlchemyUserDatabase
from fastapi_users.models import BaseUser
from sqlalchemy.ext.declarative import DeclarativeMeta, declarative_base

app = FastAPI()

Base: DeclarativeMeta = declarative_base()

class User(Base, BaseUser):
    pass

@app.get("/protected-route")
async def protected_route(user=Depends(fastapi_users.current_user)):
    return {"message": f"Hello {user.email}"}

In this example, fastapi-users provides a quick way to handle user authentication and access control in the FastAPI application.


What is fastapi-mail?

fastapi-mail is an extension that simplifies sending emails in FastAPI applications. It provides support for asynchronous email sending and allows you to configure SMTP email providers and customize email templates.

Example of using fastapi-mail:

from fastapi import FastAPI, BackgroundTasks
from fastapi_mail import FastMail, MessageSchema, ConnectionConfig

app = FastAPI()

conf = ConnectionConfig(
    MAIL_USERNAME="[email protected]",
    MAIL_PASSWORD="your-password",
    MAIL_FROM="[email protected]",
    MAIL_PORT=587,
    MAIL_SERVER="smtp.mailtrap.io",
    MAIL_TLS=True,
    MAIL_SSL=False,
    USE_CREDENTIALS=True,
)

@app.post("/send-email/")
async def send_email(background_tasks: BackgroundTasks):
    message = MessageSchema(
        subject="FastAPI Email",
        recipients=["[email protected]"],
        body="This is a test email from FastAPI.",
        subtype="html"
    )
    fm = FastMail(conf)
    background_tasks.add_task(fm.send_message, message)
    return {"message": "Email sent in the background"}

In this example, fastapi-mail is used to send an email asynchronously in the background when a user hits the email route.


What is fastapi-jwt-auth?

fastapi-jwt-auth is an extension that simplifies handling JWT (JSON Web Tokens) authentication in FastAPI applications. It provides utilities for generating, verifying, and managing JWT tokens, as well as handling token-based authentication in your routes.

Example of using fastapi-jwt-auth for JWT authentication:

from fastapi import FastAPI, Depends, HTTPException
from fastapi_jwt_auth import AuthJWT
from pydantic import BaseModel

app = FastAPI()

class Settings(BaseModel):
    authjwt_secret_key: str = "secret"

@AuthJWT.load_config
def get_config():
    return Settings()

class User(BaseModel):
    username: str
    password: str

@app.post("/login/")
def login(user: User, Authorize: AuthJWT = Depends()):
    if user.username != "test" or user.password != "password":
        raise HTTPException(status_code=401, detail="Bad username or password")
    access_token = Authorize.create_access_token(subject=user.username)
    return {"access_token": access_token}

@app.get("/protected/")
def protected_route(Authorize: AuthJWT = Depends()):
    Authorize.jwt_required()
    current_user = Authorize.get_jwt_subject()
    return {"message": f"Hello {current_user}"}

In this example, fastapi-jwt-auth is used to create and verify JWT tokens for securing routes, ensuring only authenticated users can access the protected routes.


What is fastapi-cache?

fastapi-cache is an extension that adds caching capabilities to FastAPI applications. It helps improve performance by caching responses, database queries, or any computationally expensive operations to reduce repeated work.

Example of using fastapi-cache:

from fastapi import FastAPI
from fastapi_cache import caches, close_caches
from fastapi_cache.backends.redis import RedisCacheBackend

app = FastAPI()

@app.on_event("startup")
async def on_startup():
    caches.set("default", RedisCacheBackend("redis://localhost"))

@app.get("/data/")
async def get_data():
    return {"message": "This is cached data"}

@app.on_event("shutdown")
async def on_shutdown():
    await close_caches()

In this example, fastapi-cache is used to cache the response of the /data/ route using a Redis backend. This can improve performance by reducing the number of repeated computations or database queries.


What is fastapi-pagination?

fastapi-pagination is an extension that provides pagination support in FastAPI applications. It allows you to paginate large datasets, returning only a subset of the data for each request, and provides page numbers, page sizes, and total items.

Example of using fastapi-pagination:

from fastapi import FastAPI
from fastapi_pagination import Page, add_pagination, paginate

app = FastAPI()

data = [{"name": f"Item {i}"} for i in range(1000)]

@app.get("/items/", response_model=Page[dict])
async def get_items():
    return paginate(data)

add_pagination(app)

In this example, fastapi-pagination is used to paginate a list of items, ensuring that only a limited number of items are returned for each request, and supporting query parameters for page size and number.


What is fastapi-socketio?

fastapi-socketio is an extension that adds Socket.IO support to FastAPI applications, enabling real-time communication between clients and servers. It is useful for applications that require bi-directional communication, such as chat applications or live updates.

Example of using fastapi-socketio:

from fastapi import FastAPI
from fastapi_socketio import SocketManager

app = FastAPI()
sio = SocketManager(app=app)

@app.sio.on("message")
async def handle_message(sid, data):
    await sio.emit("response", data)

@app.get("/")
async def index():
    return {"message": "Welcome to FastAPI with Socket.IO"}

In this example, fastapi-socketio adds support for WebSockets and real-time communication, allowing the server to handle incoming messages and send real-time updates to connected clients.


What is fastapi-background?

fastapi-background is an extension that simplifies handling background tasks in FastAPI. It allows you to execute long-running tasks asynchronously without blocking the main request-response cycle, improving the responsiveness of your API.

Example of using fastapi-background:

from fastapi import FastAPI, BackgroundTasks

app = FastAPI()

def background_task(name: str):
    print(f"Task executed for {name}")

@app.post("/start-task/")
async def start_task(name: str, background_tasks: BackgroundTasks):
    background_tasks.add_task(background_task, name)
    return {"message": "Task started"}

In this example, a background task is added using fastapi-background, allowing the server to process the task asynchronously without delaying the response to the client.

Ads