Trailing slash behavior controls how FastAPI handles URLs that end with or without a slash. It helps avoid confusion and broken links.
0
0
Trailing slash behavior in FastAPI
Introduction
When you want to decide if '/items' and '/items/' should be treated the same or differently.
When building APIs that need consistent URL patterns for clients.
When you want to avoid 404 errors caused by missing or extra slashes in URLs.
Syntax
FastAPI
from fastapi import FastAPI app = FastAPI() @app.get("/path/") async def with_slash(): return {"message": "URL ends with slash"} @app.get("/path") async def without_slash(): return {"message": "URL without slash"}
FastAPI treats routes with and without trailing slashes as different by default.
You can define both versions if you want to support both URLs.
Examples
This route matches only URLs ending with a slash, like '/hello/'.
FastAPI
from fastapi import FastAPI app = FastAPI() @app.get("/hello/") async def hello_slash(): return {"msg": "Hello with slash"}
This route matches only URLs without a trailing slash, like '/hello'.
FastAPI
from fastapi import FastAPI app = FastAPI() @app.get("/hello") async def hello_no_slash(): return {"msg": "Hello without slash"}
Defining both routes lets you handle both '/hello' and '/hello/' separately.
FastAPI
from fastapi import FastAPI app = FastAPI() @app.get("/hello") async def hello_no_slash(): return {"msg": "Hello without slash"} @app.get("/hello/") async def hello_slash(): return {"msg": "Hello with slash"}
Sample Program
This example shows two routes: one with and one without a trailing slash. It tests both URLs and prints their JSON responses.
FastAPI
from fastapi import FastAPI from fastapi.testclient import TestClient app = FastAPI() @app.get("/greet") async def greet_no_slash(): return {"message": "Hello without slash"} @app.get("/greet/") async def greet_with_slash(): return {"message": "Hello with slash"} client = TestClient(app) response1 = client.get("/greet") response2 = client.get("/greet/") print(response1.json()) print(response2.json())
OutputSuccess
Important Notes
FastAPI does not automatically redirect between slash and no-slash URLs.
Be consistent with your URL style to avoid confusion for API users.
You can use middleware or custom logic if you want to enforce one style.
Summary
Trailing slash matters in FastAPI URLs and affects route matching.
Define routes carefully to support or avoid both slash and no-slash URLs.
Test your API URLs to ensure they behave as expected.