0

I'm developing a REST API with flask flask-restx. I want all my response will be formatted like this

{
"code": 200,
"status": "success",
"message": "OK",
"data": {
         
     }
}
from flask import request
from flask_restx import Resource
from ..service.quiz_services import QuizService
from ..utils.dto import QuizDto

api = QuizDto.api


@api.route("/")
class QuizController(Resource):
    def post(self):
        data = request.json
        return QuizService.create_quiz(data)

When do I make GET request on the following URL, it returns

{
    "message": "The method is not allowed for the requested URL."
}

which is expected as I don't have get method in the QuizController class, How can I customize this Error Message?

davidism
  • 121,510
  • 29
  • 395
  • 339
Shahrear Bin Amin
  • 1,075
  • 13
  • 31
  • in the Flask file you have only `def post(self):` so if there is no GET function in `class QuizController(Resource):` it will return "The method is not allowed. Try to add before the post function: ` def get(self): return { "message": "OK", } `. You can put whatever you want in the return dictionary - JSON – Gandalf The Gray Oct 09 '21 at 22:44

1 Answers1

0

You can catch for a specific exception on app-level

@app.errorhandler(Exception)
def catch_error(err):
    return "hello", 400

If you want to catch only 404 exceptions you can use this:

from werkzeug.exceptions import NotFound
@app.errorhandler(NotFound)
def catch_error(err):
    return "hello", 400
Ammar Aslam
  • 560
  • 2
  • 16