From c5e3b0075d873d8bf47e4579a3c73bb709c497e7 Mon Sep 17 00:00:00 2001 From: Backend IM Bot Date: Tue, 25 Mar 2025 12:20:44 +0100 Subject: [PATCH] Update code in endpoints/cities.post.py --- endpoints/cities.post.py | 63 ++++++++++++++++++++++++++++++++++++++++ 1 file changed, 63 insertions(+) create mode 100644 endpoints/cities.post.py diff --git a/endpoints/cities.post.py b/endpoints/cities.post.py new file mode 100644 index 0000000..8a1b302 --- /dev/null +++ b/endpoints/cities.post.py @@ -0,0 +1,63 @@ +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. \ No newline at end of file