63 lines
2.5 KiB
Python
63 lines
2.5 KiB
Python
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 fastapi import FastAPI, HTTPException
|
|
from pydantic import BaseModel
|
|
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', connect_args={'check_same_thread': False})
|
|
SessionLocal = sessionmaker(autocommit=False, autoflush=False, bind=engine)
|
|
|
|
# Pydantic model for book data
|
|
|
|
@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 a breakdown of the code:
|
|
|
|
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 use this endpoint, you can send a `POST` request to `/books` with a JSON payload containing the book data, like this:
|
|
|
|
```
|
|
POST /books
|
|
Content-Type: application/json
|
|
|
|
{
|
|
"title": "The Great Gatsby",
|
|
"author": "F. Scott Fitzgerald",
|
|
"description": "A classic American novel about decadence and idealism."
|
|
}
|
|
```
|
|
|
|
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. |