Skip to content

Commit

Permalink
Make API http errors return JSON
Browse files Browse the repository at this point in the history
Fixes #384
  • Loading branch information
rubenwardy committed Jun 22, 2024
1 parent 29a6a76 commit 04878fc
Showing 1 changed file with 28 additions and 0 deletions.
28 changes: 28 additions & 0 deletions app/blueprints/api/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -14,8 +14,36 @@
# You should have received a copy of the GNU Affero General Public License
# along with this program. If not, see <https://www.gnu.org/licenses/>.

import json
from flask import Blueprint

from .support import error

bp = Blueprint("api", __name__)


from . import tokens, endpoints


@bp.errorhandler(400)
@bp.errorhandler(401)
@bp.errorhandler(403)
@bp.errorhandler(404)
def handle_exception(e):
"""Return JSON instead of HTML for HTTP errors."""
# start with the correct headers and status code from the error
response = e.get_response()
# replace the body with JSON
response.data = json.dumps({
"success": False,
"code": e.code,
"name": e.name,
"description": e.description,
})
response.content_type = "application/json"
return response


@bp.route("/api/<path:path>")
def page_not_found(path):
error(404, "Endpoint or method not found")

0 comments on commit 04878fc

Please sign in to comment.