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
|
||||
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 sqlalchemy import Column, Integer, String
|
||||
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.schemas.books_schema import *
|
||||
from app.api.dependencies.books_deps import *
|
||||
app = FastAPI()
|
||||
|
||||
# SQLAlchemy setup
|
||||
Base = declarative_base()
|
||||
engine = create_engine('sqlite:///books.db', echo=True)
|
||||
Session = sessionmaker(bind=engine)
|
||||
engine = create_engine('sqlite:///books.db', connect_args={'check_same_thread': False})
|
||||
SessionLocal = sessionmaker(autocommit=False, autoflush=False, bind=engine)
|
||||
|
||||
# SQLAlchemy model
|
||||
# Pydantic model for book data
|
||||
|
||||
@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()
|
||||
@app.post('/books', response_model=BookCreate)
|
||||
def create_book(book: BookCreate, db=get_db()):
|
||||
# Create a new book instance from the Pydantic model
|
||||
db_book = Book(title=book.title, author=book.author, description=book.description)
|
||||
|
||||
# Add the book to the database session
|
||||
db.add(db_book)
|
||||
db.commit()
|
||||
db.refresh(db_book)
|
||||
|
||||
# Return the created book data
|
||||
return db_book
|
||||
```
|
||||
|
||||
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.
|
||||
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.
|
||||
1. We define a Pydantic model `BookCreate` to represent the data required for creating a new book.
|
||||
2. We define an SQLAlchemy model `Book` that maps to the `books` table in the database.
|
||||
3. We set up an SQLite database engine and create a `SessionLocal` factory to manage database sessions.
|
||||
4. We define a dependency function `get_db` that provides a database session for each request.
|
||||
5. We define a `POST` endpoint `/books` that accepts a `BookCreate` model as input.
|
||||
6. Inside the endpoint function, we create a new `Book` instance from the `BookCreate` data.
|
||||
7. We add the new `Book` instance to the database session and commit the changes.
|
||||
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