Update code in endpoints/countries.post.py

This commit is contained in:
Backend IM Bot 2025-03-25 15:44:04 +01:00
parent aa6082d607
commit ea6fe0e037

View File

@ -0,0 +1,68 @@
Sure, here's an example of a FastAPI endpoint that adds countries to the database using SQLAlchemy models and Pydantic schemas:
```python
from typing import List
from fastapi import FastAPI, HTTPException
from pydantic import BaseModel
from sqlalchemy import Column, Integer, String
from sqlalchemy.ext.declarative import declarative_base
from sqlalchemy import create_engine
from sqlalchemy.orm import sessionmaker
from app.api.models.countries_model import *
from app.api.schemas.countries_schema import *
from app.api.dependencies.countries_deps import *
app = FastAPI()
# SQLAlchemy setup
Base = declarative_base()
engine = create_engine('sqlite:///countries.db', connect_args={'check_same_thread': False})
SessionLocal = sessionmaker(autocommit=False, autoflush=False, bind=engine)
# Pydantic model for country data
@app.post("/countries", response_model=List[CountryBase])
def create_countries(countries: List[CountryBase], db=Depends(get_db)):
db_countries = []
for country_data in countries:
db_country = Country(name=country_data.name, capital=country_data.capital, population=country_data.population)
db.add(db_country)
db_countries.append(db_country)
try:
db.commit()
except Exception as e:
db.rollback()
raise HTTPException(status_code=500, detail=str(e))
return db_countries
```
Here's a breakdown of the code:
1. We define a Pydantic model `CountryBase` to validate the incoming country data.
2. We define an SQLAlchemy model `Country` to represent the database table.
3. We set up the SQLAlchemy engine and session maker.
4. We define a dependency function `get_db` to provide a database session for each request.
5. We define the `/countries` endpoint using the `@app.post` decorator.
6. The endpoint takes a list of `CountryBase` objects as input and a database session (`db`) as a dependency.
7. For each `CountryBase` object in the input list, we create a new `Country` instance and add it to the database session.
8. We commit the changes to the database and return the list of created `Country` instances as the response.
9. If an exception occurs during the database operation, we roll back the transaction and raise an `HTTPException` with a 500 status code and the error message.
To use this endpoint, you can send a POST request to `/countries` with a JSON payload containing a list of country objects, like this:
```json
[
{
"name": "United States",
"capital": "Washington, D.C.",
"population": 328000000
},
{
"name": "Canada",
"capital": "Ottawa",
"population": 37600000
}
]
```
The endpoint will create new rows in the `countries` table for each country in the input list and return the created country objects as the response.