mahala-ygzkrg/endpoints/states.post.py
2025-03-25 14:01:37 +01:00

59 lines
2.8 KiB
Python

Sure, here's an example of a FastAPI endpoint that saves states in France to the 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 State
from schemas import StateCreate, StateResponse
router = APIRouter()
@router.post("/states", response_model=List[StateResponse])
def create_states(states: List[StateCreate], db: Session = Depends(get_db)):
db_states = [State(name=state.name, country="France") for state in states]
db.add_all(db_states)
db.commit()
return db_states
# models.py
from sqlalchemy import Column, Integer, String
from database import Base
from app.api.models.states_model import *
from app.api.schemas.states_schema import *
class StateCreate(StateBase):
pass
class StateResponse(StateBase):
id: int
country: str
class Config:
orm_mode = True
```
Here's a breakdown of the code:
1. We import the necessary modules, including `typing`, `fastapi`, `sqlalchemy.orm`, our database module, models, and Pydantic schemas.
2. We create a new instance of `APIRouter` to define our endpoint routes.
3. We define the `/states` endpoint with the `POST` method using the `@router.post` decorator. The `response_model` parameter specifies that the response should be a list of `StateResponse` objects.
4. The `create_states` function accepts a list of `StateCreate` objects as input and a database session (`db`) obtained from the `get_db` dependency.
5. Inside the function, we create a list of `State` model instances from the input `StateCreate` objects, setting the `country` attribute to "France" for each state.
6. We add all the `State` instances to the database session using `db.add_all`, and then commit the changes using `db.commit()`.
7. Finally, we return the list of created `State` instances as `StateResponse` objects.
8. The `State` model is defined in `models.py`, with columns for `id`, `name`, and `country`.
9. The Pydantic schemas `StateBase`, `StateCreate`, and `StateResponse` are defined in `schemas.py`. `StateCreate` inherits from `StateBase` and is used for input validation. `StateResponse` inherits from `StateBase` and includes the `id` and `country` fields, with the `orm_mode` set to `True` to allow Pydantic to automatically convert SQLAlchemy model instances to Pydantic objects.
To use this endpoint, you would send a `POST` request to `/states` with a JSON payload containing a list of state names:
```json
[
{"name": "Île-de-France"},
{"name": "Normandie"},
{"name": "Bretagne"}
]
```
The endpoint will create new `State` instances in the database with the provided names and the country set to "France". The response will be a list of `StateResponse` objects representing the created states, including their `id` values.