Kafka4PresidentNow
Kafka4PresidentNow

Reputation: 396

Adjust Flask-Restful API to JSON API specification

I built a small Flask-Restful API with only one method. My API receives a word and a list of URL's and returns the number of occurrences of the given word for each URL.

from flask import Flask, request, jsonify
from flask_restful import Resource, Api
import sys
sys.path.append("..")

from word_count import WordCount


app = Flask(__name__)
api = Api(app=app)

class WordApp(Resource):
    def get(self):
        word = request.args.get('word')
        url = request.args.get('url').split(",")
        return {'data': WordCount(url, word).count_words()}


api.add_resource(WordApp, '/')

if __name__ == '__main__':
    app.run(debug=False)

If the requested resource call was successful, the content returned is

{"data": {"foo": {"http://www.foobar.com": 42}}}

Although, if the request call was unsuccessful, the content returned is not conformed JSON API, as described in docs:

Including the ‘status’ key will set the Response’s status code. If not specified it will default to 500.

Error content:

{"message": "Internal Server Error"}

As I search about it, I found that is possible to define an dict containing each error and pass it to Api object.

errors = {
    'INVALID_FIELD': {
        'message': "Missing or invalid field",
        'status': 400
    }
}

app = Flask(__name__)
api = flask_restful.Api(app, errors=errors)

However, testing my endpoint with Postman with the following settings, the same 500 error message is returned. I think that I am missing something in my implementation, in order to return my custom error messages.

http://127.0.0.1:5000/?word=to

I'd like to return proper custom error messages according to JSON API specification, like this:

{
    "error": {
        "message": "Missing or invalid field",
        "code": 400
    }
}

Upvotes: 2

Views: 471

Answers (1)

Tristan
Tristan

Reputation: 2088

In your dictionary with errors you use the key INVALID_FIELD. However you cannot choose this value yourself. If you take a look at the werkzeug documentation https://werkzeug-docs-cn.readthedocs.io/zh_CN/latest/exceptions.html you see every exception is a class.

So instead of INVALID_FIELD you should use BadRequest, the name of the class that corresponds to error code 400.

Upvotes: 1

Related Questions