mahala-ygzkrg/endpoints/cities.post.py
2025-03-25 12:20:44 +01:00

63 lines
2.1 KiB
Python

Sure, here's an example of a FastAPI endpoint that saves cities in France to the database using SQLAlchemy and Pydantic:
```python
from typing import List
from fastapi import FastAPI, Depends
from sqlalchemy import Column, Integer, String
from sqlalchemy.orm import Session
from sqlalchemy.ext.declarative import declarative_base
from pydantic import BaseModel
from app.api.models.cities_model import *
from app.api.schemas.cities_schema import *
from app.api.dependencies.cities_deps import *
# SQLAlchemy setup
Base = declarative_base()
engine = create_engine('sqlite:///cities.db')
SessionLocal = sessionmaker(autocommit=False, autoflush=False, bind=engine)
# SQLAlchemy model
# FastAPI app
app = FastAPI()
# Endpoint for saving cities in France
@app.post('/cities', response_model=List[CityCreate])
def create_cities(cities: List[CityCreate], db: Session = Depends(get_db)):
db_cities = [City(name=city.name, department=city.department) for city in cities]
db.add_all(db_cities)
db.commit()
return cities
```
Here's a breakdown of the code:
1. We define SQLAlchemy models and Pydantic schemas for representing cities.
2. We set up a SQLite database using SQLAlchemy's `create_engine` function.
3. We create a dependency function `get_db` that provides a database session for each request.
4. We define a FastAPI app instance.
5. We create a POST endpoint `/cities` that accepts a list of `CityCreate` objects in the request body.
6. Inside the endpoint function, we create SQLAlchemy `City` objects from the `CityCreate` objects.
7. We add the `City` objects to the database session and commit the changes.
8. Finally, we return the list of `CityCreate` objects as the response.
To use this endpoint, you can send a POST request to `/cities` with a JSON payload containing a list of cities, like this:
```json
[
{
"name": "Paris",
"department": "Paris"
},
{
"name": "Marseille",
"department": "Bouches-du-Rhône"
},
{
"name": "Lyon",
"department": "Rhône"
}
]
```
This will create new rows in the `cities` table of the SQLite database for each city in the request payload.