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