Add API key header example to security tutorial #14370
Open
+126
−0
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.
This PR adds a concrete example to the security tutorial showing how to use an API key passed in an HTTP header and how to validate it in FastAPI.
Fixes #142.
Summary
The new example demonstrates:
X-API-Keyheader.APIKeyHeaderandSecurity.403error messages for:{"detail": "Not authenticated"}{"detail": "Invalid API key"}GET /protected-routethat returns{"message": "You are authorized"}when the API key is correct.The documentation is updated both in English and Spanish to keep the tutorials in sync.
Changes
Example app
Added a new example:
docs_src/security/tutorial_api_key_header.pyKey points:
Defines the API key and header name:
Uses
APIKeyHeaderwithauto_error=False:Defines a dependency that distinguishes between missing and invalid keys:
Protects the route:
Documentation
Updated the security tutorial in both languages to include the new section.
English
docs/en/docs/tutorial/security/index.md## API Key in HeaderAPIKeyHeaderand the constantsAPI_KEYandAPI_KEY_NAME.get_api_keydependency returns different403errors for missing vs invalid keys./protected-route.curlexamples for:Spanish
docs/es/docs/tutorial/security/index.md## API Key en el headercurlexamples, translated text.Tests
Added tests for the new example:
tests/test_tutorial/test_security/test_tutorial_api_key_header.pyThe tests cover the three main cases:
X-API-KeyheaderGET /protected-route403{"detail": "Not authenticated"}GET /protected-routewithX-API-Key: wrong403{"detail": "Invalid API key"}GET /protected-routewithX-API-Key: supersecret200{"message": "You are authorized"}How to run the tests
From the project root: