From ff47e895f71204d967b28cae2d3cac64c5aaa817 Mon Sep 17 00:00:00 2001 From: Backend IM Bot Date: Tue, 25 Mar 2025 16:03:40 +0100 Subject: [PATCH] Update code in endpoints/books.post.py --- endpoints/books.post.py | 51 +++++++++++++++++++++++++++++++++++++++++ 1 file changed, 51 insertions(+) create mode 100644 endpoints/books.post.py diff --git a/endpoints/books.post.py b/endpoints/books.post.py new file mode 100644 index 0000000..eccd2a4 --- /dev/null +++ b/endpoints/books.post.py @@ -0,0 +1,51 @@ +Sure, here's an example of a FastAPI endpoint that creates books and adds them 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 declarative_base, sessionmaker + +from app.api.models.books_model import * +from app.api.schemas.books_schema import * +# SQLAlchemy setup +Base = declarative_base() +engine = create_engine('sqlite:///books.db', echo=True) +Session = sessionmaker(bind=engine) + +# SQLAlchemy model + +@app.post('/books', response_model=BookSchema) +def create_book(book: BookSchema): + session = Session() + try: + new_book = Book(title=book.title, author=book.author) + session.add(new_book) + session.commit() + return new_book + except Exception as e: + session.rollback() + raise HTTPException(status_code=500, detail=str(e)) + finally: + session.close() +``` + +Here's what's happening: + +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 for creating a new book. +3. We create a FastAPI app instance. +4. We define an endpoint `/books` that accepts `POST` requests with a `BookSchema` body. +5. Inside the endpoint function `create_book`, we open a database session and try to create a new `Book` instance using the data from the request body. +6. If the operation is successful, we commit the changes to the database and return the newly created book. +7. If an exception occurs, we roll back the transaction and raise an HTTP exception with a 500 status code and the error message. +8. Finally, we close the database session. + +To test this endpoint, you can use a tool like Postman or cURL. For example, with cURL: + +``` +curl -X POST -H "Content-Type: application/json" -d '{"title": "The Great Gatsby", "author": "F. Scott Fitzgerald"}' http://localhost:8000/books +``` + +This will create a new book in the `books.db` SQLite database file with the provided title and author. \ No newline at end of file