templates-u1sz65/endpoints/countries.post.py
2025-03-25 15:45:27 +01:00

60 lines
2.3 KiB
Python

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, 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.countries_model import *
from app.api.schemas.countries_schema import *
from app.api.dependencies.countries_deps import *
# SQLAlchemy setup
Base = declarative_base()
engine = create_engine('sqlite:///countries.db')
SessionLocal = sessionmaker(autocommit=False, autoflush=False, bind=engine)
# Database model
app = FastAPI()
@app.post('/countries', response_model=List[CountryCreate])
def create_countries(countries: List[CountryCreate], db: Session = Depends(get_db)):
db_countries = []
for country_data in countries:
country = Country(name=country_data.name, capital=country_data.capital)
db.add(country)
db_countries.append(country_data)
db.commit()
return db_countries
```
Here's a breakdown of the code:
1. We define a SQLAlchemy database model `Country` with fields `id`, `name`, and `capital`.
2. We create a Pydantic schema `CountryCreate` to validate the incoming data for creating new countries.
3. We define a dependency function `get_db` to provide a database session for each request.
4. We create a FastAPI app instance.
5. We define the `/countries` endpoint with the `POST` method and `response_model` set to a list of `CountryCreate` objects.
6. In the endpoint function `create_countries`, we iterate over the list of `CountryCreate` objects received in the request body.
7. For each `CountryCreate` object, 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 `CountryCreate` objects.
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."
},
{
"name": "Canada",
"capital": "Ottawa"
}
]
```
This will create new entries in the `countries` table of the database with the provided names and capitals.