Skip to content

Paths

A URL's path identifies the page or data requested from a server. A blog might use different paths for the post list, an individual post, and an about page. Let's see how paths identify resources in our blog API.

Hierarchies and Paths

A blog has a collection of posts, with individual entries such as post 1 and post 2. This collection-and-item relationship forms a hierarchy.

To retrieve post 1, a client must tell the server which data it wants. A web API expresses that target in the URL path.

This is similar to locating a file. photos/trip.jpg identifies trip.jpg inside the photos folder. Our API can use / to express relationships too: /posts identifies the collection, and /posts/1 identifies post 1 within it.

/posts     All posts
├── 1      Post 1
└── 2      Post 2

In /posts/1, posts identifies the collection and 1 identifies the item. GET /posts retrieves the list; GET /posts/1 retrieves one post. Both use GET, but their paths select different resources.

Retrieving an Individual Post

Add the following below get_posts_handler in main.py:

main.py
@app.get("/posts/1", summary="Get the first post")  # ①
def get_first_post_handler():
    return posts[0]  # ②

① connects GET /posts/1 to get_first_post_handler. When called, ② returns posts[0], the first item in the list.

The list also contains post 2. With this approach, retrieving it requires another function registered at /posts/2.

main.py
@app.get("/posts/2", summary="Get the second post")
def get_second_post_handler():
    return posts[1]

Would we need a new API for every post? At this rate, post 3 needs another function, and 100 posts need 100 paths and functions. Every new post would require a code change.

Yet both functions do the same thing: find and return one post. Only the requested post ID changes. If we accept that ID from the path, one function can handle many posts.

Path Parameters

The two functions differ only in their post IDs. Let's combine them and read the ID from the request path.

Replace the functions registered at /posts/1 and /posts/2 with:

main.py
@app.get("/posts/{post_id}", summary="Get a post")  # ①
def get_post_handler(post_id):  # ②
    return {"post_id": post_id}

In ①, {post_id} marks the part of /posts/{post_id} that varies between requests. FastAPI extracts that value and passes it to the parameter with the same name in ②. The function can then use post_id to identify the requested post.

For example, GET /posts/2 passes the path value 2 to post_id.

What Is a Parameter?

A parameter is a name in a function definition that receives an input value. In def greet(name):, name is a parameter. A path parameter receives a value from the URL: {post_id} in the decorator marks its position, and post_id in the function receives it.

Save the file and open http://127.0.0.1:8000/posts/2 with the server running. The function returns the received value under the "post_id" key:

{"post_id": "2"}

Opening http://127.0.0.1:8000/posts/1 displays {"post_id": "1"}.

Both responses contain strings, shown by the quotes around "1" and "2". Without a type annotation, the path value arrives as a string even if it looks like a number.

This also means /posts/python calls the same function. Open http://127.0.0.1:8000/posts/python; post_id receives "python":

{"post_id": "python"}

A fixed path, such as /posts, has no variable segments. It usually identifies a resource or operation that does not vary by request.

A dynamic path, such as /posts/{post_id}, includes a variable segment. It lets one function perform the same operation on different resources. Both /posts/1 and /posts/2 reach the same handler, which uses post_id to choose a post.

Validating Path Values

To require an integer ID, add : int to the function parameter. FastAPI uses this type hint to attempt to convert the path value to the declared type before passing it to the function.

main.py
@app.get("/posts/{post_id}", summary="Get a post")
def get_post_handler(post_id: int):
    return {"post_id": post_id}

A type annotation such as : int is called a type hint. We will explore these in more detail shortly.

Save and open /posts/1 again. Instead of {"post_id": "1"}, you now see {"post_id": 1}. The quotes disappear because FastAPI converted the path value to an integer.

Now open /posts/python again. Since python cannot be converted to an integer, FastAPI sends an error before calling the function:

{
  "detail": [
    {
      "type": "int_parsing",  // ①
      "loc": ["path", "post_id"],  // ②
      "msg": "Input should be a valid integer, unable to parse string as an integer",  // ③
      "input": "python"  // ④
    }
  ]
}

This is a 422 response. FastAPI returns it when input does not match the declared types or constraints, or a required value is missing.

The response's detail helps the client identify what needs to change.

  • ① type identifies the error category. int_parsing means conversion to an integer failed.
  • ② loc identifies the location: here, the post_id path parameter.
  • ③ msg explains that an integer was expected but the supplied string could not be converted.
  • ④ input contains the actual value, "python".

Returning the Requested Post

Let's use post_id to find and return a post. Update get_post_handler in main.py:

main.py
@app.get("/posts/{post_id}", summary="Get a post")
def get_post_handler(post_id: int):
    for post in posts:  # ①
        if post["id"] == post_id:  # ②
            return post  # ③
  • ① for post in posts visits each post in the list.
  • ② if post["id"] == post_id compares its ID with the requested ID. Both are integers.
  • ③ When they match, return post returns the post and ends the function.

Save and open /posts/1. The response contains that post's id, title, and content.

What if you request a nonexistent post? Open /posts/10. No item has ID 10, so the loop finishes without reaching return post. The function returns None, which FastAPI sends as JSON null.

Try /posts/-1 as well. Since -1 is an integer, it passes validation. No post has that ID, so the response is again null.

Restricting the Value Range

Numeric identifiers often start at 1. Our two posts have IDs 1 and 2. FastAPI's Path lets us check this range before the function runs.

Add Path to the import at the top of main.py:

main.py
from fastapi import FastAPI, Path

Then add it to the get_post_handler parameter:

main.py
@app.get("/posts/{post_id}", summary="Get a post")
def get_post_handler(post_id: int = Path(ge=1, le=2)):
    for post in posts:
        if post["id"] == post_id:
            return post

ge=1 means greater than or equal to 1, and le=2 means less than or equal to 2. Only 1 and 2 satisfy both.

Save and request /posts/-1 and /posts/10 again. Both values are integers, but outside the allowed range, so FastAPI returns 422.

Depending on the type, Path can validate numeric ranges, digit counts, and string lengths. Common options include:

Example Applies To Constraint
ge=1 Numbers At least 1
gt=0 Numbers Greater than 0
le=2 Numbers At most 2
lt=3 Numbers Less than 3
max_digits=5 Decimal At most 5 digits in total
min_length=2 Strings At least 2 characters
max_length=20 Strings At most 20 characters

Check Your Understanding

Decide whether each statement is true or false.

  1. A collection path can be extended with an identifier to address an individual item.
  2. A dynamic path still requires a separate handler for every item.
  3. Without a type annotation, a numeric-looking path parameter is passed as a string.
  4. A handler with an integer path parameter runs even when the value cannot be converted to an integer.
  5. Greater-than-or-equal and less-than-or-equal constraints include their boundary values.
Answers and Explanations
  1. True — Hierarchical paths can narrow a request from a collection to an individual resource.
  2. False — FastAPI passes the variable path value to one handler that can serve many items.
  3. True — A path value is a string unless a declared type triggers conversion.
  4. False — FastAPI returns a validation error before calling the handler.
  5. True — Both constraints include their stated limits.