Update code in endpoints/books.post.py
This commit is contained in:
parent
3b949da5c3
commit
ff47e895f7
51
endpoints/books.post.py
Normal file
51
endpoints/books.post.py
Normal file
@ -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.
|
Loading…
x
Reference in New Issue
Block a user