➕ Creating a Book with a POST Request
In this phase, we will walk through the process of using a POST request to create a new book resource in our FastAPI application.
This implementation allows the API to accept data from the request body and append a new book to an in-memory collection.
🔧 Implementation Process
👉 Begin by importing the required dependencies.
Import Body to properly handle incoming request payloads.
from fastapi import FastAPI, Body 👉 Define a POST endpoint
# 👉 Endpoint that creates a new book.
@app.post("/create-book")
async def create_book(book_request=Body()):
BOOKS.append(book_request) # 👉 adds a book to the BOOKS collection.🌐 Adding a New Book via the Browser
After defining the endpoint, you can test it using your browser or the Swagger UI interface.
🌐browser
🔁 Important Reminder:
Each time the application reloads, all newly added books will be removed.
This occurs because the application does not yet use a database.
The
BOOKSlist stores data temporarily in memory, and memory-based storage resets whenever the server restarts.
🌐 No validation for Book
At this stage, using Body() alone does not provide built-in data validation.
Try adding a book correctly then a book with :
The book ID may be improperly formatted.
Required fields missing entirely.
The API will accept any structure of data sent in the request body.
🔍 Why Validation Is Critical
Validation ensures:
✔️ Data integrity
✔️ Consistency
✔️ Prevention of malformed data
✔️ Reliable API behavior
In the next phase of the project, we will introduce structured validation to enforce rules and guarantee that then incoming data meets defined requirements.
🗂️ books2.py
from fastapi import FastAPI, Body
app = FastAPI()
class Book:
id: int
title: str
author: str
description: str
rating: int
def __init__(self, id, title, author, description, rating):
self.id = id
self.title = title
self.author = author
self.description = description
self.rating = rating
BOOKS = [
Book(1, 'Computer Science Pro', 'codingwithrobby', 'A very nice book', 3),
Book(2, 'Be Fast with FastAPI', 'codingwithrobby', 'A great book', 5),
Book(3, 'Master Endpoints', 'codingwithrobby', 'An awesome book', 5),
Book(4, 'HP1', 'Author 1', 'Book Description', 2),
Book(5, 'HP2', 'Author 2', 'Book Description', 3),
Book(6, 'HP3', 'Author 3', 'Book Description', 1)
]
@app.get("/books")
async def read_all_books():
return BOOKS
@app.post("/create-book")
async def create_book(book_request=Body()):
BOOKS.append(book_request)