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.

from fastapi import FastAPI

app = FastAPI()

# Mock database of crew members
crew = [
    {"id": 1, "name": "Cosmo", "role": "Captain"},
    {"id": 2, "name": "Alice", "role": "Engineer"},
    {"id": 3, "name": "Bob", "role": "Scientist"}
]

Handling the POST Request

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

from fastapi import Request

# Endpoint to add a new crew member using POST method
@app.post("/crew/")
async def add_crew_member(request: Request):
    # Parse the incoming JSON request body
    data = await request.json()
    name = data["name"]
    role = data["role"]
    
    # Create a new ID for the new crew member
    crew_id = max(member["id"] for member in crew) + 1 if crew else 1

    # Add the new member to the mock database
    new_member = {"id": crew_id, "name": name, "role": role}
    crew.append(new_member)

    return {"crew_id": crew_id, "crew_member": new_member}
Sign up

Join the 1M+ learners on CodeSignal

Be a part of our community of 1M+ users who develop and demonstrate their skills on CodeSignal