Supporting Multiple HTTP Methods

Supporting Multiple HTTP Methods

Congratulations on making it to the final lesson of this course! So far, we've learned how to create individual endpoints using the HTTP methods: GET, POST, PUT, and DELETE in FastAPI. Now, it's time to integrate everything and create a FastAPI application that supports multiple HTTP methods.

Remember, each HTTP method serves a distinct purpose:

  • GET is used to retrieve data.
  • POST is used to add new data.
  • PUT is used to update existing data.
  • DELETE is used to remove data.

Let's put this knowledge into action and build our final application.

Setting up the FastAPI Application

First, let's set up our FastAPI application and establish the mock database we'll be utilizing:

from fastapi import FastAPI, Request

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"}
]

This code block imports necessary modules, sets up the FastAPI application as app, and initializes a list crew serving as our mock database, which we'll be using throughout this lesson.

Async Endpoints

Recalling from our first unit, we understood how to create asynchronous endpoints. Let's recreate our GET method endpoint to read a specific crew member's details:

@app.get("/crew/{crew_id}")
async def read_crew_member(crew_id: int):
    # Check if the crew member exists
    for member in crew:
        if member["id"] == crew_id:
            return {"crew_id": crew_id, "crew_member": member}
    # Return a message if not found
    return {"message": "Crew member not found"}

This code block defines an endpoint that responds to the GET HTTP method, accepting an integer crew_id as a path parameter. It then loops through the crew list to find and return the matched crew member. If no match is found, a message is returned indicating the crew member was not found.

POST Endpoint

Following that, we learned about the POST method for adding data. Just like we did before, we'll implement an endpoint to add a new crew member:

@app.post("/crew/")
async def add_crew_member(request: Request):
    # Parse the incoming request body
    data = await request.json()
    name = data["name"]
    role = data["role"]
    # Create a new ID and add crew member
    crew_id = max(member["id"] for member in crew) + 1 if crew else 1
    new_member = {"id": crew_id, "name": name, "role": role}
    crew.append(new_member)
    # Return new crew member details
    return {"crew_id": crew_id, "crew_member": new_member}

This endpoint handles the POST method and adds a new crew member to our list. The incoming request body is parsed for name and role data. A new ID is created, and then a new crew member is added with this ID. The details of the new crew member are then returned.

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