51 lines
2.0 KiB
Python
51 lines
2.0 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 as BookModel
|
|
from schemas import Book
|
|
|
|
router = APIRouter()
|
|
|
|
@router.get("/books", response_model=List[Book])
|
|
|
|
In this example, we have the following components:
|
|
|
|
1. **Models**: We'll assume you have a SQLAlchemy model for the `Book` entity defined in `models.py`:
|
|
|
|
```python
|
|
from sqlalchemy import Column, Integer, String
|
|
from database import Base
|
|
|
|
class Config:
|
|
orm_mode = True
|
|
```
|
|
|
|
3. **Database Dependency**: We'll assume you have a `get_db` dependency function that provides a database session, defined in `database.py`.
|
|
|
|
4. **Router and Endpoint**: The `get_books` function is the endpoint that retrieves all books from the database and returns them as a list of `Book` objects.
|
|
|
|
Here's how it works:
|
|
|
|
- The `get_books` function is decorated with `@router.get("/books", response_model=List[Book])`, which defines it as a GET endpoint at the `/books` path and specifies that the response model is a list of `Book` objects.
|
|
- The function takes a `db` parameter, which is a database session obtained from the `get_db` dependency.
|
|
- Inside the function, we use `db.query(BookModel).all()` to retrieve all book records from the database.
|
|
- The retrieved book records are returned as the response.
|
|
|
|
To include this endpoint in your FastAPI application, you would need to import the router and include it in your main application, like this:
|
|
|
|
```python
|
|
from fastapi import FastAPI
|
|
from routers import books_router
|
|
|
|
from app.api.models.man_model import *
|
|
from app.api.schemas.man_schema import *
|
|
from app.api.dependencies.man_deps import *
|
|
app = FastAPI()
|
|
app.include_router(books_router.router)
|
|
```
|
|
|
|
With this setup, when you send a GET request to `/books`, you'll receive a JSON response containing a list of all books in the database. |