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?
medium
A. Add a middleware to ignore trailing slashes
B. Change the route to @app.get('/orders/') only
C. Use a wildcard route like @app.get('/orders*')
D. Define a second route with trailing slash: @app.get('/orders/')
Solution
Step 1: Understand FastAPI's strict matching
FastAPI treats /orders and /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 D
Quick Check:
Explicit routes for both slash and no-slash = A [OK]
Hint: Add both slash and no-slash routes to avoid 404 [OK]
Common Mistakes:
Assuming one route handles both URLs automatically
Using wildcard incorrectly
Expecting middleware to fix trailing slash issues by default
5. You want a FastAPI route to accept both /profile and /profile/ URLs without redirect or 404 errors, and return the same response. Which approach is best?
hard
A. Define one route with trailing slash and rely on FastAPI redirect.
B. Define one route without trailing slash and rely on FastAPI redirect.
C. Define two routes: @app.get('/profile') and @app.get('/profile/') with the same function.
D. Use a custom middleware to strip trailing slashes before routing.
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 C
Quick Check:
Two explicit routes avoid redirect and 404 = B [OK]
Hint: Define both slash and no-slash routes for no redirect [OK]
Common Mistakes:
Relying on redirect when direct handling is needed
Using middleware unnecessarily
Defining only one route expecting both URLs to work
Recommended
Ready to prove it?
Pass the test and this pattern moves unknownstrongwhile earning +1 Grip toward your certificate.