From 8f299f4a76e558190f8b5f88d3f98aa349552af2 Mon Sep 17 00:00:00 2001 From: Backend IM Bot Date: Tue, 25 Mar 2025 11:47:50 +0100 Subject: [PATCH] Update code in endpoints/aiderman.post.py --- endpoints/aiderman.post.py | 79 ++++++++++++++++++++++++++++++++++++++ 1 file changed, 79 insertions(+) create mode 100644 endpoints/aiderman.post.py diff --git a/endpoints/aiderman.post.py b/endpoints/aiderman.post.py new file mode 100644 index 0000000..10c95a2 --- /dev/null +++ b/endpoints/aiderman.post.py @@ -0,0 +1,79 @@ +Sure, here's an example of a FastAPI endpoint that saves a list of books to the database using SQLAlchemy and Pydantic. + +```python +from typing import List +from fastapi import FastAPI, HTTPException +from pydantic import BaseModel +from sqlalchemy import Column, Integer, String, create_engine +from sqlalchemy.orm import sessionmaker +from sqlalchemy.ext.declarative import declarative_base + +from app.api.models.aiderman_model import * +from app.api.schemas.aiderman_schema import * +# SQLAlchemy setup +engine = create_engine('sqlite:///books.db', echo=True) +Session = sessionmaker(bind=engine) +Base = declarative_base() + +# SQLAlchemy model + + id = Column(Integer, primary_key=True) + title = Column(String) + author = Column(String) + + def __repr__(self): + return f"Book(id={self.id}, title='{self.title}', author='{self.author}')" + +Base.metadata.create_all(bind=engine) + +# Pydantic schema + + class Config: + orm_mode = True + +# FastAPI app +app = FastAPI() + +@app.post('/aiderman', response_model=List[BookSchema]) +def save_books(books: List[BookSchema]): + session = Session() + try: + book_instances = [Book(title=book.title, author=book.author) for book in books] + session.add_all(book_instances) + session.commit() + return book_instances + except Exception as e: + session.rollback() + raise HTTPException(status_code=500, detail=str(e)) + finally: + session.close() +``` + +Here's how it works: + +1. We define a SQLAlchemy model `Book` with `id`, `title`, and `author` columns. +2. We create a Pydantic schema `BookSchema` that defines the expected input data structure for a book. +3. We define a FastAPI endpoint `/aiderman` that accepts a list of `BookSchema` objects as input. +4. Inside the endpoint function `save_books`, we create a SQLAlchemy session and iterate over the input list of books. +5. For each book, we create a `Book` instance using the data from the `BookSchema` object. +6. We add all the `Book` instances to the session using `session.add_all`. +7. We commit the session to save the books to the database. +8. If any exception occurs during the process, we roll back the session and raise an HTTP exception with status code 500 and the error message. +9. Finally, we close the session. + +To use this endpoint, you can send a POST request to `/aiderman` with a JSON payload containing a list of book objects, like this: + +```json +[ + { + "title": "The Great Gatsby", + "author": "F. Scott Fitzgerald" + }, + { + "title": "To Kill a Mockingbird", + "author": "Harper Lee" + } +] +``` + +The endpoint will save these books to the database and return the list of saved books as the response. \ No newline at end of file