Trailing slash behavior controls how FastAPI handles URLs that end with or without a slash. It helps avoid confusion and broken links.
Trailing slash behavior in 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.
from fastapi import FastAPI app = FastAPI() @app.get("/hello/") async def hello_slash(): return {"msg": "Hello with slash"}
from fastapi import FastAPI app = FastAPI() @app.get("/hello") async def hello_no_slash(): return {"msg": "Hello without slash"}
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"}
This example shows two routes: one with and one without a trailing slash. It tests both URLs and prints their JSON responses.
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())
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.
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.
Practice
@app.get('/items/') and a client requests /items without the slash?Solution
Step 1: Understand FastAPI's default trailing slash behavior
FastAPI automatically redirects requests without a trailing slash to the route with a trailing slash if defined that way.Step 2: Apply this to the given route
Since the route is defined with a trailing slash, a request to/itemswill redirect to/items/.Final Answer:
FastAPI will redirect the client to/items/automatically. -> Option AQuick Check:
Trailing slash route causes redirect = C [OK]
- Thinking FastAPI treats slash and no-slash URLs identically without redirect
- Assuming 404 error on missing slash
- Believing server error occurs
/users without a trailing slash?Solution
Step 1: Recall route syntax for exact path matching
To match a path without trailing slash exactly, define the route without the slash.Step 2: Check each option
@app.get('/users') uses@app.get('/users')which matches/usersexactly without trailing slash.Final Answer:
@app.get('/users') -> Option BQuick Check:
Exact no-slash route = D [OK]
- Adding trailing slash when none is wanted
- Using wildcard or query syntax incorrectly
- Confusing optional trailing slash with exact match
@app.get('/products')
async def get_products():
return {'message': 'No slash'}
@app.get('/products/')
async def get_products_slash():
return {'message': 'With slash'}
What will be the JSON response when a client requests /products/?Solution
Step 1: Identify route matching for
The route/products/@app.get('/products/')matches the URL/products/exactly.Step 2: Determine which function runs
The functionget_products_slashhandles/products/and returns{'message': 'With slash'}.Final Answer:
{'message': 'With slash'} -> Option AQuick Check:
Trailing slash URL matches trailing slash route = A [OK]
- Assuming no slash route handles slash URL
- Expecting redirect instead of direct match
- Confusing 404 error with route mismatch
@app.get('/orders')
But when you request /orders/ with a trailing slash, you get a 404 error. How can you fix this to accept both /orders and /orders/ without errors?Solution
Step 1: Understand FastAPI's strict matching
FastAPI treats/ordersand/orders/as different routes and does not match one to the other automatically unless redirect applies.Step 2: Add explicit route for trailing slash
Defining@app.get('/orders/')alongside@app.get('/orders')allows both URLs to be handled without 404.Final Answer:
Define a second route with trailing slash:@app.get('/orders/')-> Option DQuick Check:
Explicit routes for both slash and no-slash = A [OK]
- Assuming one route handles both URLs automatically
- Using wildcard incorrectly
- Expecting middleware to fix trailing slash issues by default
/profile and /profile/ URLs without redirect or 404 errors, and return the same response. Which approach is best?Solution
Step 1: Understand FastAPI's redirect behavior
FastAPI redirects missing trailing slash URLs to the defined route with trailing slash, but this causes a redirect, not direct handling.Step 2: Avoid redirects by defining both routes
Defining both@app.get('/profile')and@app.get('/profile/')with the same function handles both URLs directly without redirect or 404.Final Answer:
Define two routes:@app.get('/profile')and@app.get('/profile/')with the same function. -> Option CQuick Check:
Two explicit routes avoid redirect and 404 = B [OK]
- Relying on redirect when direct handling is needed
- Using middleware unnecessarily
- Defining only one route expecting both URLs to work
Ready to prove it?
Pass the test and this pattern moves unknown
