Skip to content

Commit

Permalink
api.main: add middleware for HTTP requests
Browse files Browse the repository at this point in the history
Instead of returning HTTP 404 error when request URL
has no version number prefix, redirect the request
with '/latest' version.
e.g. when user tries to access `http://localhost:8001`,
redirect it to `http://localhost:8001/latest`.
The middleware will check the version from the request
path with available API versions using `API_VERSIONS`
list. The list will be initialized on app startup event
with `init_api_versions` handler.

Signed-off-by: Jeny Sadadia <[email protected]>
  • Loading branch information
Jeny Sadadia authored and gctucker committed Oct 23, 2023
1 parent 5bbc5cc commit 99d7b3f
Showing 1 changed file with 20 additions and 0 deletions.
20 changes: 20 additions & 0 deletions api/main.py
Original file line number Diff line number Diff line change
Expand Up @@ -49,6 +49,14 @@
user_scopes={"admin": "Superusers",
"users": "Regular users"})
pubsub = None # pylint: disable=invalid-name
API_VERSIONS = []


@app.on_event('startup')
async def init_api_versions():
"""Startup event handler to initialize list of API versions"""
global API_VERSIONS
API_VERSIONS = ['latest', 'v0']


@app.on_event('startup')
Expand Down Expand Up @@ -685,6 +693,7 @@ async def put_regression(regression_id: str, regression: Regression,
on_startup=[
pubsub_startup,
create_indexes,
init_api_versions,
]
)

Expand All @@ -701,3 +710,14 @@ async def put_regression(regression_id: str, regression: Regression,
sub_app.app.add_exception_handler(
errors.InvalidId, invalid_id_exception_handler
)


@app.middleware("http")
async def redirect_http_requests(request: Request, call_next):
"""Redirect request with version prefix when no version is provided"""
path = request.scope['path']
prefix = path.split('/')[1]
if prefix not in API_VERSIONS:
request.scope['path'] = '/latest' + path
response = await call_next(request)
return response

0 comments on commit 99d7b3f

Please sign in to comment.