In FastAPI 0.143, a yield dependency raises HTTPException(413) in its code after the yield on a successful request; what does the client receive?
answer
- which side of the response
- the status line is already out
- "response already started"
- scope="function" closes earlier
- translate inside except instead
basics
~20 sWith the default request scope the client receives the endpoint's 200, because the response was already sent; the HTTPException only produces a RuntimeError in the server log. Declared with Depends(scope="function"), the 413 replaces the response.
solid answer
~40 sIn FastAPI 0.143 a yield dependency's exit code runs after the response has been sent unless it was declared with `scope="function"`. An `HTTPException` raised there arrives after the status line and body are already out, so Starlette's exception wrapper cannot turn it into a response; it raises `RuntimeError("Caught handled exception, but response already started.")`, the server logs it, and the client keeps its 200. With `Depends(get_workdir, scope="function")` the exit code runs after the endpoint returns but before the response is sent, so the same `HTTPException` becomes the 413 the client sees. The other place an `HTTPException` from a yield dependency works is inside `except`, translating an exception the endpoint raised, because on that path no response exists yet. A check that can change the status usually belongs in the endpoint itself.
code
python · 34 linesimport tempfile
from pathlib import Path
from typing import Annotated
from fastapi import Depends, FastAPI, HTTPException
app = FastAPI()
MAX_OUTPUT_BYTES = 10
def get_workdir():
tmp = tempfile.TemporaryDirectory()
workdir = Path(tmp.name)
try:
yield workdir
used = sum(p.stat().st_size for p in workdir.iterdir())
if used > MAX_OUTPUT_BYTES:
raise HTTPException(status_code=413, detail="Render output too large")
finally:
tmp.cleanup()
@app.post("/renders")
def create_render(workdir: Annotated[Path, Depends(get_workdir)]):
(workdir / "out.txt").write_text("x" * 100)
return {"status": "rendered"}
@app.post("/renders-checked")
def create_render_checked(
workdir: Annotated[Path, Depends(get_workdir, scope="function")],
):
(workdir / "out.txt").write_text("x" * 100)
return {"status": "rendered"}go deeper
Remember that the default yield dependency cleans up after the response is sent, so it is too late there to change the status code.
Explain the table: setup and except can still change the response, request-scoped exit code cannot, function-scoped exit code can.
Recognise the RuntimeError about a response already started in logs as a late HTTPException, and move the check into the endpoint or a function-scoped dependency.
Set the convention that request-scoped exit code is cleanup only and never decides the status, so the API contract does not depend on teardown timing.
## Where a yield dependency can raise A **yield dependency** can raise `fastapi.HTTPException`, at several points, and only some of them can still change what the client receives: | Where it raises | Response already sent? | Client receives | |---|---|---| | Before the `yield` (setup) | no | the `HTTPException`'s status and detail | | In `except`, translating the endpoint's exception | no | the new `HTTPException`'s status | | After the `yield`, default `scope="request"`, endpoint succeeded | **yes** | the endpoint's original response | | After the `yield`, `scope="function"`, endpoint succeeded | no | the `HTTPException`'s status | The difference comes from *when* the exit code runs relative to sending the response. ## Why the default scope cannot change the status FastAPI keeps two exit stacks per request. A yield dependency without `scope`, or with `scope="request"`, is on the **request stack**, which closes only after the response has been fully sent, background tasks included. By then the status line, headers and body are on the wire. When the exit code raises `HTTPException(status_code=413, ...)`, the exception travels up to Starlette's exception wrapper, which normally looks up the handler and sends an error response. It first checks whether a response has started; since one has, it raises instead: - the exception is `RuntimeError("Caught handled exception, but response already started.")`, chained from the `HTTPException`; - the server logs it as an error in the application; - the client has already received the endpoint's 200 and never learns anything went wrong. In tests with `fastapi.testclient.TestClient`, the default `raise_server_exceptions=True` surfaces that `RuntimeError` in the test; with `raise_server_exceptions=False` the test sees the 200. ## How scope="function" changes it `Depends(get_workdir, scope="function")`, available since FastAPI 0.121, puts the dependency on the **function stack**, which closes right after the endpoint returns and **before** the response is sent. An `HTTPException` raised there propagates before anything has gone out, FastAPI's handler builds the error response, and the client receives the 413 with its detail. The endpoint's return value is discarded. The cost is the usual one for function scope: the yielded resource is closed before the response is sent, so it cannot back a streamed body. ## Translating exceptions inside except A different, documented pattern does work in the default scope: 1. the endpoint raises its own exception, say `OwnerError`; 2. FastAPI throws it into the dependency at the `yield`; 3. `except OwnerError as e:` raises `HTTPException(status_code=400, detail=...)`; 4. the new exception reaches FastAPI's handlers, and the client gets the 400. This works because on the error path both exit stacks unwind **before** any response exists. The documentation calls it an advanced technique and notes that raising the `HTTPException` in the endpoint is usually simpler. ## The side effects have already happened Moving the check to `scope="function"` makes the 413 reach the client, but it does not undo anything. The endpoint has already run to completion: files are written, outbound calls are made, and any state it changed stays changed. The client sees an error for a request whose work was done, and may retry it. - If the check can fail, run it **before** the irreversible step, in the endpoint or in setup. - If it can only be judged afterwards, make the work reversible and undo it in the same exit code before raising. - In logs, `RuntimeError: Caught handled exception, but response already started.` with an `HTTPException` as its cause is the signature of a late raise in request-scoped exit code. ## Where a post-condition belongs A check such as "the rendered output must stay under a size limit" decides the status code, so: - put it in the endpoint, after the work, where raising `HTTPException` is ordinary; - or put it in a function-scoped dependency's exit code, accepting that the resource closes early; - keep request-scoped exit code for cleanup that cannot fail the request, such as removing a temporary directory or closing an outbound client, and log failures there rather than raising `HTTPException`. Background tasks attached to the response run before request-scoped exit code, which is a further reason not to treat that exit code as part of the response; how those tasks behave is covered in the material on post-response tasks.
- Why can a yield dependency in the default scope translate the endpoint's exception into an HTTPException that the client does see?On the error path the endpoint produced no response, so both exit stacks unwind before anything is sent. FastAPI throws the endpoint's exception in at the `yield`, the `except` block raises an `HTTPException`, and that new exception reaches the handlers while a response can still be built.
- What should request-scoped exit code do when its own cleanup fails?Log it, and report it through whatever error tracking the service uses. The client already has its response, so raising `HTTPException` only produces a `RuntimeError` in the log. If the failure must change the status, the step belongs in the endpoint or in a function-scoped dependency instead.
- An HTTPException raised after the yield always changes the response status.
- The client receives a 500 when request-scoped exit code raises HTTPException.
- Raising HTTPException inside except is broken in the default request scope too.
- scope="function" only changes resource lifetime and never the status code.
Assumes FastAPI 0.143; since 0.118 request-scoped exit code runs after the response, and 0.121 added scope="function" to run it before.