Performance: Trailing slash behavior
This affects the routing and request handling speed, impacting how quickly the server responds and the browser renders the page.
from fastapi import FastAPI app = FastAPI() @app.get("/items/") async def read_items(): return {"message": "With trailing slash"}
from fastapi import FastAPI app = FastAPI() @app.get("/items") async def read_items(): return {"message": "No trailing slash"}
| Pattern | DOM Operations | Reflows | Paint Cost | Verdict |
|---|---|---|---|---|
| Route without trailing slash, request with slash | N/A | N/A | N/A | [X] Bad - causes redirect delay |
| Route with trailing slash, request with slash | N/A | N/A | N/A | [OK] Good - direct response, no redirect |
@app.get('/items/') and a client requests /items without the slash?/items will redirect to /items/./items/ automatically. -> Option A/users without a trailing slash?@app.get('/users') which matches /users exactly without trailing slash.@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/?/products/@app.get('/products/') matches the URL /products/ exactly.get_products_slash handles /products/ and returns {'message': 'With slash'}.@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?/orders and /orders/ as different routes and does not match one to the other automatically unless redirect applies.@app.get('/orders/') alongside @app.get('/orders') allows both URLs to be handled without 404.@app.get('/orders/') -> Option D/profile and /profile/ URLs without redirect or 404 errors, and return the same response. Which approach is best?@app.get('/profile') and @app.get('/profile/') with the same function handles both URLs directly without redirect or 404.@app.get('/profile') and @app.get('/profile/') with the same function. -> Option CPass the test and this pattern moves unknown