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.
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)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With