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.

PUT Endpoint

Can you remember the third unit? We discussed the PUT method for updating existing data. Let's recreate our endpoint for updating crew member details:

@app.put("/crew/{crew_id}")
async def update_crew_member(crew_id: int, request: Request):
    # Parse the incoming request body
    data = await request.json()
    name = data["name"]
    role = data["role"]
    # Update the crew member's details in the mock database
    for member in crew:
        if member["id"] == crew_id:
            member["name"] = name
            member["role"] = role
            return {"crew_id": crew_id, "crew_member": member}
    # Return a message if not found
    return {"message": "Crew member not found"}

In this code block, we define a PUT endpoint. By parsing the incoming request body for updated name and role data, we can successfully update the existing member's details in our crew list. If the crew member doesn't exist, a message is returned.

DELETE Endpoint

Lastly, we learned about the DELETE method for removing data. Here's how we developed the endpoint to delete a crew member:

@app.delete("/crew/{crew_id}")
async def delete_crew_member(crew_id: int):
    # Remove the crew member from the mock database
    for member in crew:
        if member["id"] == crew_id:
            crew.remove(member)
            return {"message": "Crew member removed"}
    # Return a message if not found
    return {"message": "Crew member not found"}

This endpoint responds to the DELETE method. It removes the crew member with the supplied crew_id from our list. In case the crew member is not found, an appropriate message is returned.

Summary and Practices

In this lesson, our focus was to integrate our knowledge of various HTTP methods. We began by setting up a FastAPI application, then we reviewed each HTTP method, and created respective endpoints supporting each method in our application.

Learning is all about practice. It helps cement new knowledge and techniques and builds confidence. So, we have a set of exercises following this lesson. Give them a go!

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