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.
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:
Python1from fastapi import FastAPI 2 3# Initialize a FastAPI app instance 4app = FastAPI() 5 6# Mock database of crew members 7crew = [ 8 {"id": 1, "name": "Cosmo", "role": "Captain"}, 9 {"id": 2, "name": "Alice", "role": "Engineer"}, 10 {"id": 3, "name": "Bob", "role": "Scientist"} 11]
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:
Python1# Define a new endpoint for retrieving crew members 2@app.get("/crew") 3def read_crew(): 4 # Return the list of all crew members 5 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.
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:
JSON1{ 2 "crew": [ 3 {"id": 1, "name": "Cosmo", "role": "Captain"}, 4 {"id": 2, "name": "Alice", "role": "Engineer"}, 5 {"id": 3, "name": "Bob", "role": "Scientist"} 6 ] 7}
In this lesson, you learned how to create a custom GET
endpoint in FastAPI. We covered how to define the new endpoint using decorators, implement the endpoint function, and return JSON responses from a mock database. Understanding these basics is crucial for building more complex and functional APIs.
Practice by extending your API with more endpoints and features to solidify your learning. Each new endpoint you create will help you build a more robust and versatile API, preparing you for real-world backend engineering tasks.
Great job, and keep coding!