Bird
Raised Fist0
FastAPIframework~10 mins

Trailing slash behavior in FastAPI - Step-by-Step Execution

Choose your learning style10 modes available
Concept Flow - Trailing slash behavior
Client sends request URL
↓
Check if URL ends with slash
↓
Match route with slash
↓
Return response
FastAPI checks if the request URL ends with a slash and matches it to the route with or without a trailing slash, possibly redirecting if needed.
Execution Sample
FastAPI
from fastapi import FastAPI
app = FastAPI()

@app.get("/items/")
async def read_items():
    return {"msg": "Trailing slash route"}
Defines a route with a trailing slash and returns a message when accessed.
Execution Table
StepRequest URLTrailing Slash?Route MatchedResponse or Redirect
1"/items/"Yes"/items/" routeReturns {"msg": "Trailing slash route"}
2"/items"NoNo exact matchRedirects to "/items/" (status 307)
3"/items/"YesAfter redirect, matches "/items/"Returns {"msg": "Trailing slash route"}
4"/unknown"NoNo matchReturns 404 Not Found
💡 Execution stops after response or 404 error is returned.
Variable Tracker
VariableStartAfter Step 1After Step 2After Step 3After Step 4
Request URLNone"/items/""/items""/items/" (after redirect)"/unknown"
Trailing Slash?NoneTrueFalseTrueFalse
Route MatchedNone"/items/"None"/items/"None
ResponseNone200 OK with message307 Redirect200 OK with message404 Not Found
Key Moments - 3 Insights
Why does accessing "/items" redirect to "/items/"?
Because the route is defined with a trailing slash, FastAPI redirects requests without the slash to the correct route to keep URLs consistent, as shown in step 2 and 3 of the execution_table.
What happens if the route is defined without a trailing slash and the request has one?
FastAPI will redirect the request with the trailing slash to the route without it, similar to the opposite case, ensuring consistent URL matching.
Why does accessing an unknown URL return 404?
Because no route matches the requested URL, FastAPI returns a 404 Not Found error as shown in step 4 of the execution_table.
Visual Quiz - 3 Questions
Test your understanding
Look at the execution_table, what response does FastAPI give when requesting "/items" initially?
AReturns 200 OK with message
BRedirects to "/items/" with status 307
CReturns 404 Not Found
DReturns 500 Internal Server Error
💡 Hint
Check step 2 in the execution_table where the request URL is "/items" without trailing slash.
At which step does the request URL change due to redirect?
AStep 3
BStep 2
CStep 1
DStep 4
💡 Hint
Look at the Request URL variable in variable_tracker after step 3.
If the route was defined without a trailing slash, what would happen when requesting "/items/"?
AReturn 404 Not Found
BReturn 200 OK immediately
CRedirect to "/items" without slash
DCause server error
💡 Hint
Based on key_moments about opposite redirect behavior for trailing slash.
Concept Snapshot
FastAPI routes can end with or without a trailing slash.
Requests must match the route's slash pattern.
If not matched, FastAPI redirects to the correct URL.
This keeps URLs consistent and avoids duplicate content.
Trailing slash behavior affects route matching and redirects.
Full Transcript
This visual execution shows how FastAPI handles trailing slashes in URLs. When a client requests a URL, FastAPI checks if it ends with a slash and tries to match it to a route defined with or without a trailing slash. If the request URL does not exactly match the route, FastAPI issues a redirect to the correct URL with or without the trailing slash. For example, a route defined as "/items/" will redirect requests to "/items" to "/items/". If no route matches, FastAPI returns a 404 error. This behavior ensures consistent URLs and helps avoid confusion or duplicate content. The execution table traces requests with and without trailing slashes, showing when redirects happen and what responses are returned.

Practice

(1/5)
1. In FastAPI, what happens if you define a route with a trailing slash like @app.get('/items/') and a client requests /items without the slash?
easy
A. FastAPI will redirect the client to /items/ automatically.
B. FastAPI will return a 404 Not Found error.
C. FastAPI will treat both URLs as the same without any redirect.
D. FastAPI will raise a server error.

Solution

  1. 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.
  2. Step 2: Apply this to the given route

    Since the route is defined with a trailing slash, a request to /items will redirect to /items/.
  3. Final Answer:

    FastAPI will redirect the client to /items/ automatically. -> Option A
  4. Quick Check:

    Trailing slash route causes redirect = C [OK]
Hint: Trailing slash routes redirect missing slash URLs [OK]
Common Mistakes:
  • Thinking FastAPI treats slash and no-slash URLs identically without redirect
  • Assuming 404 error on missing slash
  • Believing server error occurs
2. Which of the following is the correct way to define a FastAPI route that matches exactly /users without a trailing slash?
easy
A. @app.get('/users/')
B. @app.get('/users')
C. @app.get('/users/*')
D. @app.get('/users?')

Solution

  1. Step 1: Recall route syntax for exact path matching

    To match a path without trailing slash exactly, define the route without the slash.
  2. Step 2: Check each option

    @app.get('/users') uses @app.get('/users') which matches /users exactly without trailing slash.
  3. Final Answer:

    @app.get('/users') -> Option B
  4. Quick Check:

    Exact no-slash route = D [OK]
Hint: No trailing slash in route means no slash in URL [OK]
Common Mistakes:
  • Adding trailing slash when none is wanted
  • Using wildcard or query syntax incorrectly
  • Confusing optional trailing slash with exact match
3. Given this FastAPI code snippet:
@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/?
medium
A. {'message': 'With slash'}
B. {'message': 'No slash'}
C. 404 Not Found error
D. Redirect to /products without slash

Solution

  1. Step 1: Identify route matching for /products/

    The route @app.get('/products/') matches the URL /products/ exactly.
  2. Step 2: Determine which function runs

    The function get_products_slash handles /products/ and returns {'message': 'With slash'}.
  3. Final Answer:

    {'message': 'With slash'} -> Option A
  4. Quick Check:

    Trailing slash URL matches trailing slash route = A [OK]
Hint: Trailing slash URL matches trailing slash route exactly [OK]
Common Mistakes:
  • Assuming no slash route handles slash URL
  • Expecting redirect instead of direct match
  • Confusing 404 error with route mismatch
4. You have this FastAPI route:
@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?
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

  1. 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.
  2. Step 2: Add explicit route for trailing slash

    Defining @app.get('/orders/') alongside @app.get('/orders') allows both URLs to be handled without 404.
  3. Final Answer:

    Define a second route with trailing slash: @app.get('/orders/') -> Option D
  4. 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

  1. 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.
  2. 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.
  3. Final Answer:

    Define two routes: @app.get('/profile') and @app.get('/profile/') with the same function. -> Option C
  4. 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 unknown strong while earning +1 Grip toward your certificate.

10 questions~5 mineasy hard