Skip to content

Commit

Permalink
add api-key header to oas document (configurable)
Browse files Browse the repository at this point in the history
  • Loading branch information
arbakker committed Jan 18, 2024
1 parent 8209d19 commit ee2bdaa
Show file tree
Hide file tree
Showing 3 changed files with 36 additions and 1 deletion.
4 changes: 3 additions & 1 deletion .vscode/launch.json
Original file line number Diff line number Diff line change
Expand Up @@ -19,7 +19,9 @@
"LOG_LEVEL": "DEBUG",
"DEBUG": "true",
"MAX_SIZE_REQUEST_BODY": "5000000",
"CORS_ALLOW_ORIGINS": "*"
"CORS_ALLOW_ORIGINS": "*",
"API_KEY_IN_OAS": "true",
"EXAMPLE_API_KEY": "FOOBAR"
},
"jinja": true,
"justMyCode": false
Expand Down
10 changes: 10 additions & 0 deletions src/coordinate_transformation_api/settings.py
Original file line number Diff line number Diff line change
Expand Up @@ -89,6 +89,16 @@ class AppSettings(BaseSettings):
default=False,
description="enable access log, defaults to False",
)
api_key_in_oas: bool = Field(
alias="API_KEY_IN_OAS",
default=False,
description="add required api key to oas document",
)
example_api_key: str | None = Field(
alias="EXAMPLE_API_KEY",
default=None,
description="default api key to expose in oas document",
)

@classmethod
def settings_customise_sources( # type: ignore # noqa: PLR0913
Expand Down
23 changes: 23 additions & 0 deletions src/coordinate_transformation_api/util.py
Original file line number Diff line number Diff line change
Expand Up @@ -259,6 +259,29 @@ def init_oas(crs_config) -> tuple[dict, str, str]:
oas["info"]["version"] = version("coordinate_transformation_api")
oas["components"]["schemas"]["CrsEnum"]["enum"] = available_crss
oas["components"]["schemas"]["CrsHeaderEnum"]["enum"] = available_crss_uri

if app_settings.api_key_in_oas:
api_key_header_def = {
"APIKeyHeader": {
"type": "apiKey",
"in": "header",
"name": "apikey",
}
}
security: dict = {"security": [{"APIKeyHeader": []}]}
if app_settings.example_api_key is not None:
api_key_description = f"\n\nDemo API key is `{app_settings.example_api_key}` en is bedoeld voor exploratief gebruik van de API. "
oas["info"]["description"] = (
oas["info"]["description"] + api_key_description
)

oas["components"]["securitySchemes"] = api_key_header_def

for path in oas["paths"]:
if path != "/openapi":
for op in oas["paths"][path]:
oas["paths"][path][op] = oas["paths"][path][op] | security

api_title = oas["info"]["title"]
return (oas, api_title, oas["info"]["version"])

Expand Down

0 comments on commit ee2bdaa

Please sign in to comment.