From f2ae0a7b96f2bde16c9d38c9a11eef75702d0379 Mon Sep 17 00:00:00 2001 From: Bjarke Madsen <bjarke@nordu.net> Date: Wed, 26 Apr 2023 14:39:51 +0200 Subject: [PATCH] Return 404 when hitting invalid /api endpoints --- compendium_v2/routes/default.py | 9 ++++++++- 1 file changed, 8 insertions(+), 1 deletion(-) diff --git a/compendium_v2/routes/default.py b/compendium_v2/routes/default.py index fec92707..eaf14206 100644 --- a/compendium_v2/routes/default.py +++ b/compendium_v2/routes/default.py @@ -11,7 +11,7 @@ Default Endpoints """ import pkg_resources -from flask import Blueprint, jsonify, render_template +from flask import Blueprint, jsonify, render_template, Response from compendium_v2.routes import common @@ -45,6 +45,13 @@ def after_request(resp): @routes.route('/', defaults={'path': ''}, methods=['GET']) @routes.route('/<path:path>', methods=['GET']) def index(path): + is_api = path.startswith('api') + + if is_api: + # return 404 for API requests that don't match a route + return Response(status=404, mimetype='application/json', response='{"error": "Not Found"}') + + # fallback to serving the SPA through index.html for all other requests # https://flask.palletsprojects.com/en/2.0.x/patterns/singlepageapplications/ return render_template('index.html') -- GitLab