Update code in endpoints/books.post.py
This commit is contained in:
parent
ff47e895f7
commit
ed5420f53a
@ -1,51 +1,63 @@
|
|||||||
Sure, here's an example of a FastAPI endpoint that creates books and adds them to the database using SQLAlchemy and Pydantic:
|
Sure, here's an example of a FastAPI endpoint that creates a book and saves it to the database using SQLAlchemy and Pydantic:
|
||||||
|
|
||||||
```python
|
```python
|
||||||
from typing import List
|
|
||||||
from fastapi import FastAPI, HTTPException
|
from fastapi import FastAPI, HTTPException
|
||||||
from pydantic import BaseModel
|
from pydantic import BaseModel
|
||||||
from sqlalchemy import Column, Integer, String, create_engine
|
from sqlalchemy import Column, Integer, String
|
||||||
from sqlalchemy.orm import declarative_base, sessionmaker
|
from sqlalchemy.ext.declarative import declarative_base
|
||||||
|
from sqlalchemy import create_engine
|
||||||
|
from sqlalchemy.orm import sessionmaker
|
||||||
|
|
||||||
from app.api.models.books_model import *
|
from app.api.models.books_model import *
|
||||||
from app.api.schemas.books_schema import *
|
from app.api.schemas.books_schema import *
|
||||||
|
from app.api.dependencies.books_deps import *
|
||||||
|
app = FastAPI()
|
||||||
|
|
||||||
# SQLAlchemy setup
|
# SQLAlchemy setup
|
||||||
Base = declarative_base()
|
Base = declarative_base()
|
||||||
engine = create_engine('sqlite:///books.db', echo=True)
|
engine = create_engine('sqlite:///books.db', connect_args={'check_same_thread': False})
|
||||||
Session = sessionmaker(bind=engine)
|
SessionLocal = sessionmaker(autocommit=False, autoflush=False, bind=engine)
|
||||||
|
|
||||||
# SQLAlchemy model
|
# Pydantic model for book data
|
||||||
|
|
||||||
@app.post('/books', response_model=BookSchema)
|
@app.post('/books', response_model=BookCreate)
|
||||||
def create_book(book: BookSchema):
|
def create_book(book: BookCreate, db=get_db()):
|
||||||
session = Session()
|
# Create a new book instance from the Pydantic model
|
||||||
try:
|
db_book = Book(title=book.title, author=book.author, description=book.description)
|
||||||
new_book = Book(title=book.title, author=book.author)
|
|
||||||
session.add(new_book)
|
# Add the book to the database session
|
||||||
session.commit()
|
db.add(db_book)
|
||||||
return new_book
|
db.commit()
|
||||||
except Exception as e:
|
db.refresh(db_book)
|
||||||
session.rollback()
|
|
||||||
raise HTTPException(status_code=500, detail=str(e))
|
# Return the created book data
|
||||||
finally:
|
return db_book
|
||||||
session.close()
|
|
||||||
```
|
```
|
||||||
|
|
||||||
Here's what's happening:
|
Here's a breakdown of the code:
|
||||||
|
|
||||||
1. We define a SQLAlchemy model `Book` with `id`, `title`, and `author` columns.
|
1. We define a Pydantic model `BookCreate` to represent the data required for creating a new book.
|
||||||
2. We create a Pydantic schema `BookSchema` that defines the expected input data for creating a new book.
|
2. We define an SQLAlchemy model `Book` that maps to the `books` table in the database.
|
||||||
3. We create a FastAPI app instance.
|
3. We set up an SQLite database engine and create a `SessionLocal` factory to manage database sessions.
|
||||||
4. We define an endpoint `/books` that accepts `POST` requests with a `BookSchema` body.
|
4. We define a dependency function `get_db` that provides a database session for each request.
|
||||||
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.
|
5. We define a `POST` endpoint `/books` that accepts a `BookCreate` model as input.
|
||||||
6. If the operation is successful, we commit the changes to the database and return the newly created book.
|
6. Inside the endpoint function, we create a new `Book` instance from the `BookCreate` data.
|
||||||
7. If an exception occurs, we roll back the transaction and raise an HTTP exception with a 500 status code and the error message.
|
7. We add the new `Book` instance to the database session and commit the changes.
|
||||||
8. Finally, we close the database session.
|
8. We return the created book data as the response.
|
||||||
|
|
||||||
To test this endpoint, you can use a tool like Postman or cURL. For example, with cURL:
|
To use this endpoint, you can send a `POST` request to `/books` with a JSON payload containing the book data, like this:
|
||||||
|
|
||||||
```
|
```
|
||||||
curl -X POST -H "Content-Type: application/json" -d '{"title": "The Great Gatsby", "author": "F. Scott Fitzgerald"}' http://localhost:8000/books
|
POST /books
|
||||||
|
Content-Type: application/json
|
||||||
|
|
||||||
|
{
|
||||||
|
"title": "The Great Gatsby",
|
||||||
|
"author": "F. Scott Fitzgerald",
|
||||||
|
"description": "A classic American novel about decadence and idealism."
|
||||||
|
}
|
||||||
```
|
```
|
||||||
|
|
||||||
This will create a new book in the `books.db` SQLite database file with the provided title and author.
|
The endpoint will create a new book in the `books` table and return the created book data as the response.
|
||||||
|
|
||||||
|
Note that this example uses an SQLite database for simplicity, but you can easily adapt it to use other database engines by modifying the `create_engine` call and updating the database URL accordingly.
|
Loading…
x
Reference in New Issue
Block a user