2025-03-25 14:44:21 +01:00

45 lines
1.8 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 get_db
from models import Book
from schemas import BookSchema
router = APIRouter()
# SQLAlchemy model
class Config:
orm_mode = True
@router.get("/books", response_model=List[BookSchema])
Here's a breakdown of the code:
1. We import the necessary modules and classes from FastAPI, SQLAlchemy, and Pydantic.
2. We define the `Book` SQLAlchemy model with columns for `id`, `title`, `author`, `description`, and `rating`.
3. We define the `BookSchema` Pydantic model, which will be used for data validation and serialization/deserialization.
4. We create a `router` instance from `APIRouter`.
5. We define the `/books` endpoint using the `@router.get` decorator, and specify the `response_model` as a list of `BookSchema` objects.
6. Inside the `get_books` function, we use the `db` dependency (provided by `get_db`) to query the database and retrieve all books using `db.query(Book).all()`.
7. The retrieved books are returned as the response.
To use this endpoint, you would need to include the `router` in your FastAPI application, like this:
```python
from fastapi import FastAPI
from routers import books
from app.api.models.books_model import *
from app.api.schemas.books_schema import *
from app.api.dependencies.books_deps import *
app = FastAPI()
app.include_router(books.router)
```
Then, you can access the `/books` endpoint using a GET request, and it will return a JSON response containing a list of books from the database.
Note that you'll also need to set up a database connection and define the `get_db` dependency function, which is not shown in this example code.