Sorry, something went wrong.
Merging this PR will not alter performance✅ 20 untouched benchmarks Comparing Deadshot1831:deadshot-sse-jsonl-tests-docs (a9b2d87) with master (1e60e32)1 Footnotes |
Sorry, something went wrong.
📝 Docs previewLast commit a9b2d87 at: https://b1ecfcaf.fastapitiangolo.pages.dev Modified Pages |
Sorry, something went wrong.
| If you need to add custom headers to an SSE response, use a dependency that receives a `Response` parameter and sets the headers before the stream starts: | ||
|
|
||
| {* ../../docs_src/server_sent_events/tutorial006_py310.py ln[1:33] hl[3:4,22:23,26:30] *} | ||
|
|
||
| The dependency runs before FastAPI creates the streaming response. | ||
|
|
||
| This is different from setting headers inside the generator body, which runs later, when the response is already streaming. |
There was a problem hiding this comment.
I think this should be explained in a different way.
I would go with:
What do you think?
Sorry, something went wrong.
There was a problem hiding this comment.
Yes, that makes sense. I was focusing more on the final pattern, but starting from the existing Response Headers docs makes the flow clearer.
I’ll adjust the explanation so it first points to the usual Response parameter approach, then explains why setting headers inside a streaming generator is too late, and then introduces the dependency approach. The key reason that works is that dependencies run before FastAPI creates the streaming response, so the headers are set before streaming starts.
Sorry, something went wrong.
Pull Request
Discussion: N/A - docs-only clarification with tutorial test coverage.
Description
This PR documents how to add custom response headers to JSON Lines and SSE streaming endpoints.
FastAPI already documents the common pattern in Response Headers: use a Response parameter and mutate response.headers. This PR adds the streaming-specific caveat. For generator endpoints, setting a header inside the generator body is too late because FastAPI has already prepared the streaming response before the generator starts yielding data.
The examples use a dependency with a Response parameter to set the header before FastAPI creates the streaming response. Dependencies are resolved before the response is prepared, so the header is available at the correct point.
Changes:
Validation
I did not run the full docs build locally because this venv does not have the full docs dependency group installed.