Creating a Custom GET Endpoint

Creating a Custom GET Endpoint

Welcome to this lesson on creating custom GET endpoints in FastAPI! Today, you'll learn how to extend a basic FastAPI application by adding a new endpoint. This will enable us to build more versatile and feature-rich APIs, like our example spaceship management system, where we might need endpoints for various resources such as crew members, spaceship parts, and more.

The key learning goal for today is to successfully create a custom GET endpoint that retrieves a list of crew members from a mock database, following the steps provided below.

Setting Up the Application

Before diving into the new endpoint, let's ensure our application setup is correct. We'll start by initializing a FastAPI app instance and setting up a mock database of crew members that we will use for our endpoint.

Here's the setup:

from fastapi import FastAPI

# Initialize a FastAPI app instance
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"}
]

Adding a Custom GET Endpoint

Next, we'll add a new custom GET endpoint to our FastAPI application. This endpoint will be used to retrieve a list of crew members from the mock database. In FastAPI, we define new endpoints using decorators like @app.get("/path").

Let's add a new endpoint for retrieving crew members:

# Define a new endpoint for retrieving crew members
@app.get("/crew")
def read_crew():
    # Return the list of all crew members
    return {"crew": crew}

Adding a custom GET endpoint for retrieving crew members from our mock database is straightforward. Using the @app.get("/crew") decorator and a function to return the JSON response, we can easily extend the application with new endpoints.

Accessing the Custom Endpoint

Once the new endpoint is defined, you can access it by navigating to /crew on your server. For example, if your server is running locally at port 8000, you would go to http://127.0.0.1:8000/crew.

This path should return the JSON response representing the list of crew members from our mock database. The response will be in the following format:

{
    "crew": [
        {"id": 1, "name": "Cosmo", "role": "Captain"},
        {"id": 2, "name": "Alice", "role": "Engineer"},
        {"id": 3, "name": "Bob", "role": "Scientist"}
    ]
}
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