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
@app.get("/crew_path/{crew_id}")
def read_crew_member_by_path(crew_id: int):
    for member in crew:
        if member["id"] == crew_id:
            return member
    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.

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