Skip to main content
 首页 » 编程设计

python之将 Flask-Restful API 调整为 JSON API 规范

2024年12月31日8over140

我只使用一种方法构建了一个小型 Flask-Restful API。我的 API 接收一个词和一个 URL 列表,并返回每个 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) 

如果请求的资源调用成功,返回的内容为

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

尽管如此,如果请求调用不成功,返回的内容将不符合 JSON API,如 docs 中所述。 :

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

错误内容:

{"message": "Internal Server Error"} 

当我搜索它时,我找到了 that可以定义一个包含每个错误的字典并将其传递给 Api 对象。

errors = { 
    'INVALID_FIELD': { 
        'message': "Missing or invalid field", 
        'status': 400 
    } 
} 
 
app = Flask(__name__) 
api = flask_restful.Api(app, errors=errors) 

但是,使用具有以下设置的 Postman 测试我的端点时,返回相同的 500 错误消息。我认为我在我的实现中遗漏了一些东西,以便返回我的自定义错误消息。

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

我想根据 JSON API 规范返回正确的自定义错误消息,如下所示:

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

请您参考如下方法:

在有错误的字典中,您使用关键字 INVALID_FIELD。但是您不能自己选择此值。如果您查看 werkzeug 文档 https://werkzeug-docs-cn.readthedocs.io/zh_CN/latest/exceptions.html你会看到每个异常都是一个类。

因此,您应该使用 BadRequest,而不是 INVALID_FIELD,这是与错误代码 400 对应的类的名称。