Lesson 2
Handling POST Requests
Handling POST Requests in FastAPI

Welcome back! Well done learning the basics of using asynchronous methods. This time, we'll explore other types of HTTP methods — specifically, POST requests, and how to handle them with FastAPI.

POST is one of the HTTP methods that allow you to send data to a server for processing. We can imagine it like dropping off a parcel at a courier office. The parcel is your data, and the office is your server.

Let's dive deeper into how this works.

Understanding POST Requests

POST requests submit data to be processed by a specified resource on the server. Imagine you are signing up for a new online service. When you fill out your details and hit "Sign Up," your information (name, email, password) is sent to the server via a POST request to add you as a new user in the database.

The data sent in a POST request is included in the body of the request and is used to create or update resources. Unlike GET requests, which only retrieve data, POST requests modify the server's state.

Moreover, a POST request usually receives a response from the server. This response could include confirmation of the action taken, details of the newly created resource, or any additional information related to the request. For example, after signing up, you might receive a response with your new user ID and a welcome message.

Creating a POST Request in FastAPI

FastAPI makes it straightforward to handle different HTTP methods. You might recall from our previous lessons that we use decorators like @app.get() to handle GET requests. Similarly, we use @app.post() to define endpoints that handle POST requests.

Setting up the API and Mock Database

Before creating our endpoint, let's set up our application and a mock database of crew members.

Python
1from fastapi import FastAPI 2 3app = FastAPI() 4 5# Mock database of crew members 6crew = [ 7 {"id": 1, "name": "Cosmo", "role": "Captain"}, 8 {"id": 2, "name": "Alice", "role": "Engineer"}, 9 {"id": 3, "name": "Bob", "role": "Scientist"} 10]
Handling the POST Request

Next, we create the endpoint to handle the POST request for adding a new crew member.

Python
1from fastapi import Request 2 3# Endpoint to add a new crew member using POST method 4@app.post("/crew/") 5async def add_crew_member(request: Request): 6 # Parse the incoming JSON request body 7 data = await request.json() 8 name = data["name"] 9 role = data["role"] 10 11 # Create a new ID for the new crew member 12 crew_id = max(member["id"] for member in crew) + 1 if crew else 1 13 14 # Add the new member to the mock database 15 new_member = {"id": crew_id, "name": name, "role": role} 16 crew.append(new_member) 17 18 return {"crew_id": crew_id, "crew_member": new_member}
Code Walkthrough

The POST method in the code is defined using @app.post("/crew/"). This decorator tells FastAPI that whenever it receives a POST request at the /crew/ endpoint, it should call the add_crew_member function.

Here's a step-by-step breakdown of the function:

  1. Importing the Request Object:

    • The Request object is imported from fastapi. This import is crucial as the Request class provides functionalities like processing the request body asynchronously.
  2. Handling the Incoming Request:

    • We use the Request object to handle the incoming request.
    • By calling await request.json(), the function parses the JSON data from the request body into a dictionary. This allows us to easily extract the name and role of the new crew member.
  3. Creating a New ID for the Crew Member:

    • A new ID for the crew member is created by finding the maximum existing ID in the crew list and adding 1. If the list is empty, the ID is set to 1.
  4. Adding the New Member to the Mock Database:

    • The new member's details (ID, name, and role) are added to the crew list, simulating the addition of the new member to the database.
  5. Returning a JSON Response:

    • The function returns a JSON response containing the new crew member's ID and details.
Making a POST Request

To make a POST request to this endpoint, the URL http://localhost:8000/crew/ would be used. Unlike GET requests, where parameters are included in the URL, the data for a POST request is included in the body of the request. This body is where you supply the necessary details for the operation — in this case, the name and role of the new crew member.

What is the Request Body?

The request body is a part of the HTTP request where data is sent to the server. Unlike query or path parameters, which are included in the URL, the request body allows you to send more complex and structured data. This is especially useful for operations like creating or updating resources on the server.

How the Body Looks Like

The body of the request will contain a JSON object with the crew member's details, like the following example:

JSON
1{ 2 "name": "Jack", 3 "role": "Astronaut" 4}

When the server receives this POST request, it extracts the name and role from the request body, adds the new crew member to the database, and returns the newly created resource's information. This ensures that the data is clearly structured and properly transmitted, facilitating efficient resource creation or modification on the server.

Summary and Preparing for Practices

Well done on grasping the POST method in FastAPI! You've just stepped further into the vast universe of FastAPI, successfully understanding and writing your first POST request!

In the teachings to follow, you'll be going hands-on, crafting POST requests, and practicing all you've learned here today. Remember, practice is key to retaining new skills. So, keep coding, and keep exploring!

Enjoy this lesson? Now it's time to practice with Cosmo!
Practice is how you turn knowledge into actual skills.