Update code in endpoints/aiderman.post.py
This commit is contained in:
parent
cc2c11a0d3
commit
4ac39717c6
@ -1,27 +1,80 @@
|
|||||||
|
Sure, here's an example of a FastAPI endpoint that saves a list of books to the database using SQLAlchemy and Pydantic schemas:
|
||||||
|
|
||||||
```python
|
```python
|
||||||
from fastapi import APIRouter, HTTPException
|
|
||||||
from typing import List
|
from typing import List
|
||||||
from models.book import Book
|
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
|
||||||
|
|
||||||
router = APIRouter()
|
from app.api.models.aiderman_model import *
|
||||||
books = [] # In-memory storage
|
from app.api.schemas.aiderman_schema import *
|
||||||
|
app = FastAPI()
|
||||||
|
|
||||||
@router.post("/aiderman", status_code=201)
|
# SQLAlchemy setup
|
||||||
async def save_books(book_list: List[Book]):
|
engine = create_engine('sqlite:///books.db', echo=True)
|
||||||
"""Save a list of books to the database"""
|
Session = sessionmaker(bind=engine)
|
||||||
if request.method != "POST":
|
Base = declarative_base()
|
||||||
raise HTTPException(status_code=405, detail="Method Not Allowed")
|
|
||||||
|
|
||||||
books.extend(book_list)
|
# SQLAlchemy model
|
||||||
|
|
||||||
return {
|
id = Column(Integer, primary_key=True)
|
||||||
"method": "POST",
|
title = Column(String)
|
||||||
"_verb": "post",
|
author = Column(String)
|
||||||
"message": "Books saved successfully",
|
|
||||||
"books_saved": len(book_list)
|
def __repr__(self):
|
||||||
}
|
return f"Book(id={self.id}, title='{self.title}', author='{self.author}')"
|
||||||
|
|
||||||
|
Base.metadata.create_all(engine)
|
||||||
|
|
||||||
|
# Pydantic schema
|
||||||
|
|
||||||
|
class Config:
|
||||||
|
orm_mode = True
|
||||||
|
|
||||||
|
# Endpoint to save a list of books
|
||||||
|
@app.post("/aiderman")
|
||||||
|
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 {"message": "Books saved successfully"}
|
||||||
|
except Exception as e:
|
||||||
|
session.rollback()
|
||||||
|
raise HTTPException(status_code=500, detail=str(e))
|
||||||
|
finally:
|
||||||
|
session.close()
|
||||||
```
|
```
|
||||||
|
|
||||||
This endpoint accepts a list of `Book` objects in the request body and saves them to an in-memory list called `books`. It returns a JSON response with the number of books saved and the required method metadata.
|
Here's how it works:
|
||||||
|
|
||||||
Ensure that the `Book` model is defined in `models/book.py` with the necessary fields, and imported correctly in this file.
|
1. We define a SQLAlchemy model `Book` with `id`, `title`, and `author` columns.
|
||||||
|
2. We create a Pydantic schema `BookSchema` that defines the structure of a book object.
|
||||||
|
3. The `save_books` endpoint accepts a list of `BookSchema` objects as input.
|
||||||
|
4. Inside the endpoint, we create a SQLAlchemy session and iterate over the 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 changes to the database using `session.commit()`.
|
||||||
|
8. If any exception occurs during the process, we rollback the transaction using `session.rollback()`.
|
||||||
|
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"
|
||||||
|
}
|
||||||
|
]
|
||||||
|
```
|
||||||
|
|
||||||
|
This will save the list of books to the `books` table in the `books.db` SQLite database.
|
Loading…
x
Reference in New Issue
Block a user