0
0
FastAPIframework~5 mins

Route ordering and priority in FastAPI

Choose your learning style9 modes available
Introduction

Route ordering helps FastAPI decide which path to use when multiple routes look similar. It makes sure the right code runs for the right URL.

You have multiple routes with similar paths and want to control which one matches first.
You want to avoid conflicts between static and dynamic routes.
You want to make sure a specific route handles a special case before a general route.
You are adding new routes and want to keep your API predictable.
You want to prevent unexpected route matches that cause bugs.
Syntax
FastAPI
from fastapi import FastAPI

app = FastAPI()

@app.get("/items/special")
async def read_special_item():
    return {"message": "This is a special item"}

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

FastAPI checks routes in the order they are added to the app.

More specific routes should be added before more general ones to get matched first.

Examples
The route /users/me is more specific and placed before the dynamic /users/{user_id}. This way, /users/me matches exactly and does not get treated as a user ID.
FastAPI
from fastapi import FastAPI

app = FastAPI()

@app.get("/users/me")
async def read_current_user():
    return {"user": "current"}

@app.get("/users/{user_id}")
async def read_user(user_id: int):
    return {"user_id": user_id}
If /files/static is added after the catch-all /files/{file_path:path}, it will never be matched. So, put the static route first.
FastAPI
from fastapi import FastAPI

app = FastAPI()

@app.get("/files/static")
async def read_static_file():
    return {"message": "Static file"}

@app.get("/files/{file_path:path}")
async def read_file(file_path: str):
    return {"file_path": file_path}
Sample Program

This example shows two routes: one for a special product and one for any product by ID. Because the special route is added first, requests to /products/special return the special message. Requests like /products/123 return the product ID.

FastAPI
from fastapi import FastAPI

app = FastAPI()

@app.get("/products/special")
async def special_product():
    return {"product": "special"}

@app.get("/products/{product_id}")
async def product(product_id: int):
    return {"product_id": product_id}
OutputSuccess
Important Notes

Always add specific routes before general ones to avoid unexpected matches.

Dynamic routes with path parameters can catch many URLs, so place them last.

Use clear route names to keep your API easy to understand and maintain.

Summary

FastAPI matches routes in the order they are added.

Put specific routes before general dynamic routes to control priority.

Proper route ordering prevents bugs and makes your API predictable.