2025-03-25 15:17:19 +01:00

57 lines
2.1 KiB
Python

Sure, here's an example of a FastAPI endpoint that returns a list of books from a database using SQLAlchemy and Pydantic:
```python
from typing import List
from fastapi import APIRouter, Depends
from sqlalchemy.orm import Session
from database import SessionLocal
import models
import schemas
router = APIRouter()
# Dependency
def get_db():
db = SessionLocal()
try:
yield db
finally:
db.close()
# SQLAlchemy model
class Book(models.Base):
__tablename__ = "books"
id = models.Column(models.Integer, primary_key=True, index=True)
title = models.Column(models.String, index=True)
author = models.Column(models.String, index=True)
description = models.Column(models.String, index=True)
# Pydantic schema
class BookSchema(schemas.BaseModel):
id: int
title: str
author: str
description: str
class Config:
orm_mode = True
@router.get("/books", response_model=List[BookSchema])
def get_books(db: Session = Depends(get_db)):
books = db.query(Book).all()
return books
```
Here's a breakdown of the code:
1. We import the necessary modules and classes from FastAPI, SQLAlchemy, and Pydantic.
2. We define a SQLAlchemy model `Book` with columns for `id`, `title`, `author`, and `description`.
3. We define a Pydantic schema `BookSchema` that maps to the `Book` model.
4. We create a dependency function `get_db` that establishes a database session and yields it to the endpoint function.
5. We define the `GET` endpoint `/books` that retrieves all books from the database using `db.query(Book).all()`.
6. The `response_model` parameter is set to `List[BookSchema]`, which tells FastAPI to use the `BookSchema` to serialize the response data.
To use this endpoint, you would need to have a running database with a table named `books` and the corresponding columns. When you send a `GET` request to `/books`, the endpoint will retrieve all books from the database and return them as a list of JSON objects.
Note that this is a basic example, and you may want to add error handling, pagination, filtering, and other features depending on your requirements.