Update code in endpoints/books.post.py
This commit is contained in:
parent
269b1e09d2
commit
6d5f43843a
62
endpoints/books.post.py
Normal file
62
endpoints/books.post.py
Normal file
@ -0,0 +1,62 @@
|
||||
Sure, here's an example of a FastAPI endpoint that saves a book 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 sessionmaker
|
||||
from sqlalchemy.ext.declarative import declarative_base
|
||||
|
||||
from app.api.models.books_model import *
|
||||
from app.api.schemas.books_schema import *
|
||||
# Create the database engine and session
|
||||
engine = create_engine('sqlite:///books.db', echo=True)
|
||||
Session = sessionmaker(bind=engine)
|
||||
session = Session()
|
||||
|
||||
# Define the base class for SQLAlchemy models
|
||||
Base = declarative_base()
|
||||
|
||||
# Define the Book model
|
||||
|
||||
class Config:
|
||||
orm_mode = True
|
||||
|
||||
# Define the FastAPI app
|
||||
app = FastAPI()
|
||||
|
||||
# Define the POST endpoint to save a book
|
||||
@app.post('/books', response_model=BookSchema)
|
||||
def create_book(book: BookSchema):
|
||||
# Create a new Book instance from the Pydantic schema
|
||||
new_book = Book(title=book.title, author=book.author, description=book.description)
|
||||
|
||||
# Add the new book to the database session
|
||||
session.add(new_book)
|
||||
session.commit()
|
||||
|
||||
return new_book
|
||||
|
||||
# Run the FastAPI app
|
||||
if __name__ == '__main__':
|
||||
import uvicorn
|
||||
uvicorn.run(app, host='0.0.0.0', port=8000)
|
||||
```
|
||||
|
||||
Here's how it works:
|
||||
|
||||
1. We define the `Book` model using SQLAlchemy, which maps to the `books` table in the database.
|
||||
2. We create a Pydantic `BookSchema` that defines the expected input data for a book.
|
||||
3. We define a `POST` endpoint at `/books` using FastAPI, which accepts a `BookSchema` instance as input.
|
||||
4. Inside the endpoint function, we create a new `Book` instance from the Pydantic schema data.
|
||||
5. We add the new `Book` instance to the database session and commit the changes.
|
||||
6. We return the newly created `Book` instance as the response.
|
||||
|
||||
To test the endpoint, you can use a tool like `curl` or a REST client like Postman. Here's an example using `curl`:
|
||||
|
||||
```
|
||||
curl -X POST -H "Content-Type: application/json" -d '{"title": "The Great Gatsby", "author": "F. Scott Fitzgerald", "description": "A classic novel about the Jazz Age."}' http://localhost:8000/books
|
||||
```
|
||||
|
||||
This will create a new book in the `books.db` SQLite database file.
|
Loading…
x
Reference in New Issue
Block a user