After a FastAPI login form POST returns RedirectResponse("/dashboard"), the browser re-sends the POST and gets 405. Why, and how do you fix it?
answer
- check the default status
- 307 keeps the method
- post, redirect, get
- 405 means the path matched, not the method
basics
~20 sFastAPI's RedirectResponse defaults to 307, which tells the browser to repeat the same method and body, so it POSTs to a GET-only /dashboard and gets 405. Pass status_code=status.HTTP_303_SEE_OTHER so the browser follows with a GET.
solid answer
~30 s`RedirectResponse` (Starlette's class, re-exported by FastAPI) uses **307 Temporary Redirect** when no status is given. A 307 requires the client to repeat the original method and body, so after the login form the browser POSTs to `/dashboard`, which only has a GET route, and FastAPI answers 405 Method Not Allowed. The fix is `RedirectResponse("/dashboard", status_code=status.HTTP_303_SEE_OTHER)`: 303 tells the client to fetch the new URL with GET, the post/redirect/get pattern. The same 307 default applies to `response_class=RedirectResponse` when you return a URL. The session cookie goes on the returned `RedirectResponse` with `set_cookie`.
code
python · 19 linesfrom typing import Annotated
from fastapi import FastAPI, Form, status
from fastapi.responses import RedirectResponse
app = FastAPI()
@app.post("/login")
def login(username: Annotated[str, Form()], password: Annotated[str, Form()]):
# credential check omitted
response = RedirectResponse("/dashboard", status_code=status.HTTP_303_SEE_OTHER)
response.set_cookie("session", "opaque-token", httponly=True, secure=True)
return response
@app.get("/dashboard")
def dashboard():
return {"page": "dashboard"}go deeper
Recall that RedirectResponse sends a Location header and defaults to 307, and that 303 is the code for redirecting after a form POST.
Explain how 303 and 307 differ in the follow-up method, and why the GET-only dashboard route answers 405 to a repeated POST.
Diagnose the 405 from the network trace, fix the status, test with redirects not followed, and close the open-redirect risk of a next parameter.
Settle whether server-rendered login flows live in the API service at all, or behind a separate front end with its own redirect handling.
## What the browser saw A login page posts a form to `POST /login`. The path operation checks the credentials and returns `RedirectResponse("/dashboard")`. Instead of landing on the dashboard, the user sees an error; the network panel shows `POST /login -> 307`, then `POST /dashboard -> 405 Method Not Allowed`. ## Reading the trace The diagnosis comes straight from the browser's network panel or a test that does not follow redirects: 1. `POST /login` returns **307** with `Location: /dashboard`. The credentials were accepted; the problem is the code. 2. The browser sends **`POST /dashboard`**, not `GET`, carrying the same form body. 3. The app has only a GET route for `/dashboard`, so it answers **405** with an `Allow: GET` header. The method on the second request is the clue. If it had been a GET, the cause would lie in the dashboard route itself. ## Why: the 307 default `RedirectResponse` is Starlette's class, re-exported from `fastapi.responses`. Its constructor is `RedirectResponse(url, status_code=307, headers=None, background=None)`: it sends an empty body, sets the `Location` header to the URL, and defaults to **307 Temporary Redirect**. The redirect status codes differ in what the client must do with the method: | Status | `fastapi.status` constant | Method on the follow-up request | |---|---|---| | 301 Moved Permanently | `HTTP_301_MOVED_PERMANENTLY` | browsers usually switch a POST to GET | | 302 Found | `HTTP_302_FOUND` | browsers usually switch a POST to GET | | 303 See Other | `HTTP_303_SEE_OTHER` | always GET | | 307 Temporary Redirect | `HTTP_307_TEMPORARY_REDIRECT` | same method and body | | 308 Permanent Redirect | `HTTP_308_PERMANENT_REDIRECT` | same method and body | With 307 the browser repeats `POST` with the form body against `/dashboard`. The app registered only `@app.get("/dashboard")`, so FastAPI's router finds the path but not the method and answers **405**. If `/dashboard` had accepted POST, the bug would be worse: the credentials would be submitted a second time to a handler that never expected them. The 307 default is reasonable for API redirects, where repeating a `PUT` or `POST` as is matters. It is the wrong choice for the **post/redirect/get** pattern a login form needs. ## The fix Pass the status explicitly: ```python response = RedirectResponse("/dashboard", status_code=status.HTTP_303_SEE_OTHER) ``` 303 means "see the result at this other URL with GET". After it, the browser loads `/dashboard` with a GET, and a page reload does not resubmit the form. The same default applies in the other style FastAPI supports, `@app.post("/login", response_class=RedirectResponse)` with the function returning the URL string: the status is 307 unless the decorator also passes `status_code=303`. That style has one advantage over returning the object: the generated OpenAPI schema lists the route's redirect status, so the docs show a 303 response instead of a JSON 200. It has one limit for this route: the function returns only a URL, so a cookie has to come from a `Response` parameter, which FastAPI does merge here because it builds the redirect itself. ## The session cookie A login redirect usually sets a session cookie; call `set_cookie` on the `RedirectResponse` you return, since a returned response is sent as is. `set_cookie` defaults to `httponly=False`, `secure=False` and `samesite="lax"`, so a session cookie should pass `httponly=True` and `secure=True` explicitly. ## Defender's checklist for redirect routes - **Do not redirect to a URL taken from the request** (`?next=...`) without checking it is a path on your own site; an unchecked value turns the login page into an open redirect. - **Pick the status deliberately**: 303 after a form POST, 307 or 308 when an API client must repeat the method. - **Test with redirects not followed**, for example `TestClient.post(..., follow_redirects=False)`, and assert the status and `Location` header; a client that follows redirects automatically can hide which method the second request used. ## Summary for the interview 1. `RedirectResponse` defaults to 307, which preserves the POST. 2. The GET-only target answers 405. 3. `status_code=status.HTTP_303_SEE_OTHER` gives post/redirect/get. 4. Test with redirects not followed, so the 303 and its `Location` header are what the test asserts.
- In FastAPI, what status does @app.get("/docs-home", response_class=RedirectResponse) use when the function returns a URL string?307, the `RedirectResponse` default; FastAPI wraps the returned string as the redirect URL and documents the route as a 307. To use another code, also pass `status_code` on the decorator, for example `status_code=status.HTTP_302_FOUND` or `HTTP_303_SEE_OTHER`.
- In FastAPI, why is it safer to test the login route with follow_redirects=False?The test client follows redirects by default, so a test might only see the final page or the final 405. With `follow_redirects=False` the test asserts the login response itself: the 303 status, the `Location` header and the `Set-Cookie` header, which is what the browser actually receives first.
- Assuming RedirectResponse defaults to 302 Found when no status is passed
- Fixing the 405 by also accepting POST on the dashboard route
- Testing the login route only with redirects followed automatically
- Redirecting to a next parameter from the request without validating it
- Thinking a 307 makes the browser switch to GET on the follow-up