FastAPI - Beginner to Pro / Project 1 - FastAPI Request Method Logic

Project: POST Request

πŸ“€ POST Request Method in FastAPI

The POST HTTP request is used to create new resources on the server

  • Allows clients to send structured data to the server

  • Ideal for creating new entries or modifying server state

  • Unlike GET, POST supports a request body, making it suitable for large or complex data

In this example, we will use POST to create a new book

Prior to sending a POST request, we must know the required structure of a complete book object.


πŸ“¦ Book Data Structure

A book must include these fields, represented in JSON format (Python dictionary):

{
    "title": "",
    "author": "",
    "category": ""
}

πŸ‘‰ Three pieces of data are required to create a book


🧾 Using the Request Body in POST Requests

POST requests include a request body, which allows the client to send structured data to the server.

  • Import Body from FastAPI to access the request body

  • Provide all required fields in JSON/dictionary format

from fastapi import FastAPI, Body 
# Import **Body** from FastAPI to access the request body

app = FastAPI()

BOOKS = [
    {"title": "Title One", "author": "Author One", "category": "science"},
    {"title": "Title Two", "author": "Author Two", "category": "science"},
    {"title": "Title Three", "author": "Author Three", "category": "history"},
    {"title": "Title Four", "author": "Author Four", "category": "math"},
    {"title": "Title Five", "author": "Author Five", "category": "math"},
    {"title": "Title Six", "author": "Author Two", "category": "math"}
]

@app.post("/books/create_book")
async def create_book(new_book = Body()):
    BOOKS.append(new_book) 
    # πŸ‘‰ Append the submitted book to the BOOKS list

πŸ”Ž How It Works

  • πŸ“₯ Body is imported to read data sent in the request body (JSON payload)

  • 🌐 API endpoint: POST /books/create_book

    πŸ‘‰ Used to create/add a new book

  • πŸ“¦ new_book = Body()

    πŸ‘‰ Receives the JSON data sent by the


🌐 Testing in Swagger UI

After running the app, navigate to Swagger docs:

  • πŸ“Œ You’ll see:

    • Four GET endpoints

    • One POST endpoint

Inside the POST Endpoint

  • πŸ”Ή No URL parameters

  • πŸ”Ή Request body field for submitting book data

⚠️ Important: Use double quotes " " in JSON; single quotes ' ' are invalid

As shown by the /get_books endpoint, we currently have a total of 6 books. After validation, we add a new book using the POST request at /books/create_book.


πŸ“š Verifying Book Creation

  • Use a GET request to fetch all books

  • The newly added book (e.g., Title Seven) should appear in the list

  • Confirms the POST request worked correctly πŸ‘


🚫 Attempting to Use Body with GET Request

@app.get('/books/{book_title}')
async def read_all_books(book_title: str, new_book=Body()):
    for book in BOOKS:
        if book.get('title').casefold() == book_title.casefold():
            return book

❌ Result in Swagger UI

Request with GET/HEAD method cannot have a body


πŸ” Key Takeaways

  • GET requests cannot include a request body

  • GET is strictly for data retrieval

  • POST is required when sending data to the server

  • FastAPI enforces HTTP standards strictly


from fastapi import FastAPI, Body

app = FastAPI()

BOOKS = [
    {"title": "Title One", "author": "Author One", "category": "science"},
    {"title": "Title Two", "author": "Author Two", "category": "science"},
    {"title": "Title Three", "author": "Author Three", "category": "history"},
    {"title": "Title Four", "author": "Author Four", "category": "math"},
    {"title": "Title Five", "author": "Author Five", "category": "math"},
    {"title": "Title Six", "author": "Author Two", "category": "math"}
]

@app.get("/books")
async def read_all_books():
    return BOOKS

@app.get('/books/{book_title}')
async def read_book(book_title: str):
    for book in BOOKS:
        if book.get('title').casefold() == book_title.casefold():
            return book

@app.get("/books/")
async def read_category_by_query(category: str):
    books_to_return = []
    for book in BOOKS:
        if book.get('category').casefold() == category.casefold():
            books_to_return.append(book)
    return books_to_return

@app.get("/books/{book_author}/")
async def read_author_and_category(book_author: str, category: str):
    books_to_return = []
    for book in BOOKS:
        print('book', book)
        if book.get('author').casefold() == book_author.casefold() and \\
                book.get('category').casefold() == category.casefold():
            books_to_return.append(book)
    return books_to_return

@app.post("/books/create_book")
async def create_book(new_book=Body()):
    BOOKS.append(new_book)  
    # πŸ‘‰ Append the submitted book to the BOOKS list