CodeBlanks Logo Icon CodeBlanks

Path parameter

Learn path parameters with /items/{id}.

Path parameter

A placeholder of the form {name} in the path becomes a path parameter. The function parameter with the same name matches it; FastAPI extracts the value from the URL and passes it.

@app.get("/items/{item_id}")
def read_item(item_id: int):
    return {"item_id": item_id}

With the type int, FastAPI converts automatically. If the value does not match, a 422 response is returned. This is ideal for routes that take a resource id.

Type conversion

You can give path parameters types like int, str, float. FastAPI converts the string from the URL to this type; if it cannot, a 422 response is returned.

@app.get("/items/{item_id}")
def read_item(item_id: int):
    # item_id is an int here
    return {"item_id": item_id, "tipi": type(item_id).__name__}

Without a type, the parameter is treated as str. Giving a type strengthens validation and documentation.

Practice GET route with a path parameter

Start with from fastapi import FastAPI and from fastapi.testclient import TestClient. Define app = FastAPI(). With @app.get("/items/{item_id}") define def read_item(item_id: int): returning {"item_id": item_id}. Create a client with client = TestClient(app). Print the response body with print(client.get("/items/5").text).

Starter code

main.py
# bring in FastAPI from fastapi
# bring in TestClient
# define app
# add a get function at '/items/{item_id}' (with item_id: int)
# create a client with TestClient, query '/items/5' and print the body

Sample solution

main.py
from fastapi import FastAPI
from fastapi.testclient import TestClient

app = FastAPI()

@app.get("/items/{item_id}")
def read_item(item_id: int):
    return {"item_id": item_id}

client = TestClient(app)
print(client.get("/items/5").text)

Expected output

{"item_id":5}

Questions and answers

Review the lesson questions together with their answers. To test yourself, solve the lesson interactively.

1 How is item_id obtained in @app.get("/items/{item_id}")?

  • Through the function parameter Correct answer
  • Through a global variable
  • From the query string
  • By reading from a file

Explanation: item_id is obtained through the function parameter with the same name.

2 Complete the path parameter route

Question
@app.get("/items/____")
def read_item(item_id: int):
Answer
@app.get("/items/{item_id}")
def read_item(item_id: int):

Explanation: {item_id} is the path parameter placeholder.

3 Match the path parameter concepts

Term Meaning
{item_id} Is the placeholder
item_id: int Is a type conversion
422 Is a validation error
/items/{id} Is a path template

All lessons in Advanced