Lesson 5
Using Parameters with Endpoints
Using Parameters with Endpoints

In previous lessons, we built a simple FastAPI application, defined endpoints, and interacted with a mock database. Today, we'll dive into the concept of parameters and how they can enhance our API functionality.

Parameters enable APIs to accept input that can alter their behavior and outputs. Essentially, they allow us to customize the data retrieval or operations performed by the API based on specific criteria.

For instance, if you needed to fetch details about a specific crew member by their id within our mock database, parameters would be the mechanism to achieve this. Let's explore this concept further.

Path and Query Parameter Types

Parameters in APIs primarily come in two basic flavors: Path Parameters and Query Parameters. While parameters can also be passed through headers and the request body, for now, we will focus on path and query parameters.

  • Path Parameters: Sometimes called URL parameters, these are variables embedded right into the URL path, following a certain syntax.

    • Example: /crew_path/{crew_id}, where {crew_id} is a path parameter.
  • Query Parameters: These are added to the end of a URL following a ?, allowing multiple parameters separated by &.

    • Example: /crew_query/member?crew_id=x, where crew_id=x is a query parameter.

Typically, path parameters are part of the API's base URL, while query parameters allow users to customize their data requests. Now, let's see how we can utilize these parameters with FastAPI.

Creating an Endpoint with Path Parameters

FastAPI provides a straightforward way to incorporate path parameters into endpoint definitions.

Let's see an example:

Python
1@app.get("/crew_path/{crew_id}") 2def read_crew_member_by_path(crew_id: int): 3 for member in crew: 4 if member["id"] == crew_id: 5 return member 6 return {"message": "Crew member not found"}

In this example, /crew_path/{crew_id} is our path with {crew_id} as the path parameter. crew_id: int tells FastAPI that we want the crew_id in the path to be converted to an integer. After receiving a crew_id, the function iterates through the crew list and checks if the crew_id matches any member's id. If found, it returns that member's data; if not, it returns a "not found" message.

Accessing the Path Parameter Endpoint

To retrieve data using the path parameter endpoint, you need to include the crew_id within the URL path. For instance, to request information about the crew member with an ID of 1, you would use the following URL:

Plain text
1localhost:8000/crew_path/1

This structure places the crew_id directly in the URL path, triggering the read_crew_member_by_path function to process the request.

Creating an Endpoint with Query Parameters

Creating an endpoint with query parameters is just as easy in FastAPI. Directly define the parameter in the function using the standard function definition syntax, specifying the type of the parameter (e.g., int):

Python
1@app.get("/crew_query/member") 2def read_crew_member_by_query(crew_id: int): 3 for member in crew: 4 if member["id"] == crew_id: 5 return member 6 return {"message": "Crew member not found"}

In this case, FastAPI will expect a crew_id query parameter in the URL. Again, it iterates through the crew list and checks if a crew_id matches any member's id and returns that member's data or a "not found" message if crew_id is not found.

The use of /member in the path clarifies that we are retrieving data for a specific crew member, although it is optional and provided for added clarity. Query parameters are appended to the URL with a ?, allowing us to pass the crew_id value.

Accessing the Query Parameter Endpoint

For the query parameter endpoint, you will include the crew_id as part of the URL query string. If you want to fetch details for the crew member with an ID of 1, your URL will look like this:

Plain text
1localhost:8000/crew_query/member?crew_id=1

Here, the crew_id is passed as a query parameter, prompting the read_crew_member_by_query function to handle the request.

Path Parameters: Advantages and Disadvantages

Advantages:

  • Clarity and Clean URLs: Path parameters can make URLs more readable and intuitive by embedding variables directly into the URL.
  • RESTful Convention: Often used in RESTful APIs to represent hierarchical resources by embedding the resource identifiers directly into the URL path. For example, in the URL /crew_path/1, 1 is a RESTful parameter that directly refers to a specific crew member's ID within the crew resource.

Disadvantages:

  • Fixed Structure: Path parameters require a predefined structure in the URL, which can be less flexible for optional parameters.
  • Limited Customization: Since path parameters are integrated into the URL, they are less suited for dynamically changing parameters.
Query Parameters: Advantages and Disadvantages

Advantages:

  • Flexibility: Query parameters can be added, removed, or combined without changing the URL structure, allowing for more dynamic queries.
  • Optional Parameters: Ideal for optional parameters, as they do not disrupt the URL structure when omitted.

Disadvantages:

  • Cluttered URLs: Can make URLs longer and harder to read, especially with multiple parameters.
  • Less Intuitive: May be less intuitive for representing hierarchical resources compared to path parameters.
Full Implementation

To help you compare and contrast how path and query parameters work within a complete FastAPI application, here's a full implementation:

Python
1from 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] 12 13# Endpoint to get a crew member by path parameter 14@app.get("/crew_path/{crew_id}") # /crew_path/1 15def read_crew_member_by_path(crew_id: int): 16 for member in crew: 17 if member["id"] == crew_id: 18 return member 19 return {"message": "Crew member not found"} 20 21# Endpoint to get a crew member by query parameter 22@app.get("/crew_query/member") # /crew_query/member?crew_id=1 23def read_crew_member_by_query(crew_id: int): 24 for member in crew: 25 if member["id"] == crew_id: 26 return member 27 return {"message": "Crew member not found"}

Now you can see how both types of parameters—path and query—are integrated within a real FastAPI application.

Summary and Practice Section

Awesome job! You've learned how to use path and query parameters to retrieve specific data in FastAPI applications. We've learned the differences between path and query parameters, and how each can be applied to create flexible and functional API endpoints.

Remember, practicing is fundamental to learning, and in the exercises that follow, you'll put what you've learned into practice! Let's delve into the exercises with enthusiasm. You've got this!

Enjoy this lesson? Now it's time to practice with Cosmo!
Practice is how you turn knowledge into actual skills.