Sling Academy
Home/FastAPI/How to Use Dynamic Routes in FastAPI

How to Use Dynamic Routes in FastAPI

Last updated: November 03, 2022

Routing refers to how an API’s endpoints (URIs) respond to incoming requests. In FastAPI, a route path, in combination with a request method, define the endpoint at which requests can be made. You can define a dynamic route path that can contain one or multiple path parameters (variables). Each parameter will be wrapped in a pair of curly braces { }.

Let’s examine the most minimal example below for more clarity:

from fastapi import FastAPI

app = FastAPI()


@app.get('/users/{user_id}/{user_name}')
async def get_users(user_id: int, user_name: str):
    return {"user_data": {
        "id": user_id,
        "message": "Hello, " + user_name,
    }}

The value of the path params user_id and user_name will be passed to the handler function as the arguments user_id and user_name.

If you run the code above and go to http://localhost:8000/users/123/ABCDEF with your web browser, you will see this:

{"user_data":{"id":123,"message":"Hello, ABCDEF"}}

Screenshot:

If you look closer at the code, you would notice that the types of the parameters were declared in the function, where user_id is int and user_name is str. This helps validate the values passed to the URL. If you enter this URL http://localhost:8000/users/foo/bar into the address bar, you will get an error:

{"detail":
  [{
      "loc":["path","user_id"],
       "msg":"value is not a valid integer",
       "type":"type_error.integer"
  }]
}

The detailed information about the API was also automatically generated at http://localhost:8000/docs:

This will make it easier for developers using your API (for web frontend or mobile apps) to get the necessary insights.

Next Article: How to Extract Query Parameters in FastAPI

Previous Article: Write Your First Backend API with FastAPI (Hello World)

Series: FastAPI Tutorials for Beginners

FastAPI

You May Also Like

  • Popular useful built-in Jinja filters you should know
  • How to remove consecutive whitespace in rendered Jinja pages
  • How to format large numbers with thousand separators in Jinja template
  • How to format date time in Jinja templates
  • FastAPI + Jinja: How to create custom filters
  • How to pass variables from Python (FastAPI) to Jinja
  • How to decode Jinja response to string
  • How to create and use macros in Jinja
  • How to use namespace in Jinja
  • How to use if/ else in Jinja
  • How to use loops in Jinja
  • FastAPI + SQLAlchemy: Using cursor-based pagination
  • FastAPI: How to use macros in Jinja templates
  • Fixing Common Swagger UI Errors in FastAPI
  • FastAPI Error: 307 Temporary Redirect – Causes and Solutions
  • FastAPI Error: Expected UploadFile, received ‘str’
  • Resolving FastAPI ImportError: No Known Parent Package
  • FastAPI Error: No module named ‘pydantic_core._pydantic_core’
  • Resolving FastAPI 422 Error: Value is not a valid dict