Automatically support HEAD method for all GET routes#15356
Open
Herrtian wants to merge 1 commit intofastapi:masterfrom
Open
Automatically support HEAD method for all GET routes#15356Herrtian wants to merge 1 commit intofastapi:masterfrom
Herrtian wants to merge 1 commit intofastapi:masterfrom
Conversation
RFC 7231 §4.3.2 states that the server SHOULD send the same header fields in response to a HEAD request as it would have sent for GET. Starlette does this by default but FastAPI's APIRoute did not. This adds automatic HEAD support by overriding matches() and handle() on APIRoute to accept HEAD requests when the route has GET in its methods. Key design decisions: - HEAD is NOT added to self.methods, so it stays out of the OpenAPI schema - Explicit HEAD routes still work and appear in OpenAPI when declared - The match promotion only happens when HEAD is not already in methods, so explicit @app.head() or methods=["GET","HEAD"] are unaffected - POST/PUT/DELETE/PATCH routes are not affected Closes fastapi#1773
f0b347d to
fb78a21
Compare
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Add this suggestion to a batch that can be applied as a single commit.This suggestion is invalid because no changes were made to the code.Suggestions cannot be applied while the pull request is closed.Suggestions cannot be applied while viewing a subset of changes.Only one suggestion per line can be applied in a batch.Add this suggestion to a batch that can be applied as a single commit.Applying suggestions on deleted lines is not supported.You must change the existing code in this line in order to create a valid suggestion.Outdated suggestions cannot be applied.This suggestion has been applied or marked resolved.Suggestions cannot be applied from pending reviews.Suggestions cannot be applied on multi-line comments.Suggestions cannot be applied while the pull request is queued to merge.Suggestion cannot be applied right now. Please check back later.
Closes #1773
GET routes now respond to HEAD requests automatically, matching what Starlette does (RFC 7231 §4.3.2).
HEAD is not added to
self.methods, so it won't show up in the OpenAPI schema. Instead,APIRoute.matches()promotes HEAD→GET at routing time, andhandle()lets it through.If you explicitly define a
@app.head()route, it still works and appears in the schema as before.Includes 10 new tests covering the various cases (path params, response models, routers, explicit HEAD, etc). Updated one existing test that relied on the old 405 behavior.