🌐 AI搜索 & 代理 主页
Skip to content

Conversation

@Esteban3010
Copy link

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:

  • Using an API key sent in the X-API-Key header.
  • Validating the API key with a dependency using APIKeyHeader and Security.
  • Returning different 403 error messages for:
    • missing/empty header: {"detail": "Not authenticated"}
    • wrong header value: {"detail": "Invalid API key"}
  • Protecting a route GET /protected-route that 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.py

Key points:

  • Defines the API key and header name:

    API_KEY = "supersecret"
    API_KEY_NAME = "X-API-Key"
  • Uses APIKeyHeader with auto_error=False:

    api_key_header = APIKeyHeader(name=API_KEY_NAME, auto_error=False)
  • Defines a dependency that distinguishes between missing and invalid keys:

    async def get_api_key(
        api_key: Optional[str] = Security(api_key_header),
    ) -> str:
        if api_key is None:
            raise HTTPException(
                status_code=status.HTTP_403_FORBIDDEN,
                detail="Not authenticated",
            )
        if api_key != API_KEY:
            raise HTTPException(
                status_code=status.HTTP_403_FORBIDDEN,
                detail="Invalid API key",
            )
        return api_key
  • Protects the route:

    @app.get("/protected-route")
    async def protected_route(api_key: str = Security(get_api_key)):
        return {"message": "You are authorized"}

Documentation

Updated the security tutorial in both languages to include the new section.

English

  • docs/en/docs/tutorial/security/index.md
  • New section: ## API Key in Header
  • It explains:
    • What an API key is and when to use it.
    • How to define APIKeyHeader and the constants API_KEY and API_KEY_NAME.
    • How the get_api_key dependency returns different 403 errors for missing vs invalid keys.
    • How to use the dependency in /protected-route.
    • curl examples for:
      • no header,
      • wrong header value,
      • correct header value.

Spanish

  • docs/es/docs/tutorial/security/index.md
  • New section: ## API Key en el header
  • This mirrors the English section, with the same code and curl examples, translated text.

Tests

Added tests for the new example:

  • tests/test_tutorial/test_security/test_tutorial_api_key_header.py

The tests cover the three main cases:

  1. No X-API-Key header
    • GET /protected-route
    • Response: 403
    • Body: {"detail": "Not authenticated"}
  2. Invalid API key
    • GET /protected-route with X-API-Key: wrong
    • Response: 403
    • Body: {"detail": "Invalid API key"}
  3. Valid API key
    • GET /protected-route with X-API-Key: supersecret
    • Response: 200
    • Body: {"message": "You are authorized"}

How to run the tests

From the project root:

pytest tests/test_tutorial/test_security/test_tutorial_api_key_header.py
Checklist
[x] New example added under docs_src/security.

[x] Documentation updated in English and Spanish.

[x] Tests added for the new example.

[x] Tests passing locally.

@github-actions github-actions bot added the docs Documentation about how to use FastAPI label Nov 19, 2025
@github-actions
Copy link
Contributor

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

docs Documentation about how to use FastAPI

Projects

None yet

Development

Successfully merging this pull request may close these issues.

ApiKey Header documentation

1 participant