Open In App

FastAPI – Request Body

In this discussion we will learn about the FastAPI – Request Body, FastAPI is a cutting-edge, high-performance web framework designed for building APIs in Python 3.7 and above, leveraging standard Python-type hints. Over recent years, it has gained significant popularity due to its modern approach and efficiency. One of its standout features is its robust handling of request bodies, which forms the focal point of this article.

What is FastAPI – Request Body?

In web development, the request body is essentially the data that a client intends to send to the server. It constitutes a crucial part of the HTTP request, encapsulating information that the client (end-user) desires to transmit to the server. FastAPI excels in managing request bodies, ensuring an efficient and streamlined process for handling data exchange between clients and servers.



Types of FastAPI – Request Body

FastAPI supports various types of request bodies, each tailored to different data formats and use cases:

  1. JSON Request Body:
    • Sending data in JSON format is a prevalent practice in modern APIs, and FastAPI simplifies this process. The framework automatically validates and parses JSON request bodies, making use of the powerful Pydantic library.
    • Pydantic is employed to define data models, enabling automatic validation of the data structure. This ensures that the received data adheres to the expected format, enhancing the reliability and integrity of the API.
  2. Form Data Request Body:
    • Traditional HTML forms rely on form data for user input. FastAPI seamlessly handles form data, facilitating easy integration with web forms. This capability is particularly useful when dealing with scenarios where input is collected through web-based forms.
    • The framework streamlines the process of managing form data, offering developers a convenient way to work with inputs from users interacting with HTML forms.

FastAPI – Request Body Examples

We will now illustrate two examples related to FastAPI – Request Body, as outlined below.



Handling JSON Request Body in FastAPI

In this example, This FastAPI code sets up a simple blog post API. It uses Pydantic for data validation, defines an imaginary in-memory database class, and has two endpoints: `create_blog_post` for adding posts with input validation, and `get_blog_posts` for retrieving a list of posts from the imaginary database. The code highlights FastAPI’s ease of use, automatic validation, and asynchronous functionality for handling HTTP requests.




from fastapi import FastAPI, HTTPException, Body
from typing import List, Optional
 
from pydantic import BaseModel
 
app = FastAPI()
 
# Imaginary database class
class Database:
    def __init__(self):
        self.db = []
 
    def add_blog_post(self, blog_post: dict):
        self.db.append(blog_post)
 
    def get_blog_posts(self):
        return self.db
 
db = Database()
 
class BlogPost(BaseModel):
    title: str
    # Making content optional
    content: Optional[str] = None 
 
@app.post("/create_blog_post")
async def create_blog_post(blog_post: BlogPost):
    # Input validation
    if not blog_post.title:
        raise HTTPException(status_code=400, detail="Title is required")
 
    # Database operation
    db.add_blog_post(blog_post.dict())
 
    # Returning a confirmation message
    return {"message": "Blog post created successfully"}
 
@app.get("/get_blog_posts", response_model=List[BlogPost])
async def get_blog_posts():
    # Returning the list of blog posts from the imaginary database
    return db.get_blog_posts()

Run the server :

uvicorn main:app --reload 

Output

Form Data Request Body in FastAPI

In this example below code uses FastAPI to create a web app with a “/login/” endpoint handling POST requests containing “username” and “password” form data. The asynchronous function responds with a message indicating a login attempt and the received username. The development server runs on localhost:8000 using uvicorn. In summary, it establishes a simple FastAPI server for handling user login attempts.




from fastapi import FastAPI, Form
 
# Create a FastAPI app instance
app = FastAPI()
 
# Endpoint to handle POST requests with form data
@app.post("/login/")
async def login(username: str = Form(...), password: str = Form(...)):
    """
    Handle user login using form data.
 
    Parameters:
    - username (str): The username received from the form.
    - password (str): The password received from the form.
 
    Returns:
    - dict: A dictionary containing the message and username.
    """
    response_message = {"message": "The user attempted to log in", "username": username}
    return response_message
 
# Run the FastAPI development server
if __name__ == "__main__":
    import uvicorn
 
    # Start the server on 127.0.0.1:8000
    uvicorn.run(app, host="127.0.0.1", port=8000)

Run the server :

uvicorn main:app --reload 

Output:

Conclusion

In conclusion, FastAPI’s robust support for request bodies enhances the development of web applications and APIs. With automatic data validation, serialization, and the use of Pydantic models, it ensures efficient data exchange and clear code structure. FastAPI’s intuitive syntax, asynchronous capabilities, and automatic documentation make it a powerful choice for building modern and maintainable services that rely on request bodies for data communication.


Article Tags :