2025-03-25 15:18:23 +01:00

80 lines
2.3 KiB
Python

Sure, here's an example of a FastAPI endpoint that returns a list of girls from the database using SQLAlchemy and Pydantic:
```python
from fastapi import APIRouter, Depends
from sqlalchemy.orm import Session
from typing import List
from database import get_db
from models import Girl
from schemas import GirlSchema
router = APIRouter()
@router.get("/girl", response_model=List[GirlSchema])
def get_girls(db: Session = Depends(get_db)):
girls = db.query(Girl).all()
return girls
```
**Explanation:**
1. We import the necessary modules and classes from FastAPI, SQLAlchemy, and Pydantic.
2. We create an instance of `APIRouter` to define our endpoint routes.
3. We define the `get_girls` function, which is a GET endpoint at `/girl`.
4. The `response_model` parameter specifies that the response will be a list of `GirlSchema` objects.
5. We use the `Depends` function to inject the database session (`db`) as a dependency.
6. Inside the function, we query the `Girl` model from the database using `db.query(Girl).all()`.
7. We return the list of `Girl` objects, which will be automatically converted to `GirlSchema` objects by Pydantic.
**Models and Schemas:**
Here's an example of the `Girl` model and `GirlSchema` schema:
```python
# models.py
from sqlalchemy import Column, Integer, String
from database import Base
class Girl(Base):
__tablename__ = "girls"
id = Column(Integer, primary_key=True, index=True)
name = Column(String)
age = Column(Integer)
```
```python
# schemas.py
from pydantic import BaseModel
class GirlSchema(BaseModel):
id: int
name: str
age: int
class Config:
orm_mode = True
```
In this example, the `Girl` model is a SQLAlchemy model that defines the `girls` table with columns for `id`, `name`, and `age`. The `GirlSchema` is a Pydantic model that defines the shape of the data that will be returned by the API endpoint.
When you make a GET request to `/girl`, the API will return a JSON response containing a list of girls, like this:
```json
[
{
"id": 1,
"name": "Alice",
"age": 25
},
{
"id": 2,
"name": "Bob",
"age": 30
},
...
]
```
Note that you'll need to set up the database connection and create the necessary tables before running this code. Additionally, you may want to add error handling, authentication, and other features to make the API more robust and secure.