Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Flask-restful: How to only response to requests come with ('Accept':'application/json')?

I have a json api APP, working well.Now I want it only accept and response json, not response to text/html request. App looks like this:

class Books(Resource):
    def get(self):
        return json.dumps(data)

Someone can help? Thanks.

like image 912
longnight Avatar asked Mar 18 '23 14:03

longnight


1 Answers

You could use a preprocessing request handler to reject all request with the wrong MimeType. There is a property of the Request object (not documented tought, but present at least on Flask 0.10) named is_json

Given your Flask app is called application, you could use something like :

from flask import request, abort, jsonify

@application.before_request
def only_json():
    if not request.is_json: 
        abort(400)  # or any custom BadRequest message

I would also use the Flask jsonify function to build your reponse, it will ensure that the response is well formatted in json, and also sets the right headers.

class Books(Resource):
    def get(self):
        return jsonify(data)
like image 79
afrancais Avatar answered Apr 06 '23 07:04

afrancais