REST API软错误和警告
我正在设计一个REST API,里面有一个输入比较灵活的接口。
基本上,理想情况下我们希望输入是一个48x48的数组,但只要是数组,我们可以比较聪明地调整它的大小到正确的尺寸。
调整大小的操作并不太费资源,但我觉得用户应该知道他们提供的输入并不是最理想的。不过,我希望这个错误提示不会太打扰用户。
我认为这个情况下仍然可以返回HTTP状态码200,但我也可以接受其他的意见。
有没有什么被广泛接受的方法可以在REST响应中包含一些元数据呢?
我没有找到类似的东西,但我觉得这个请求应该不会太奇怪。
作为参考,我使用的是flask
,下面是示例代码:
class Function(MethodView):
def post(self):
post_array = np.array(json.loads(request.form['data']))
if post_array.shape != (48, 48):
post_array = post_array.resize((48,48)) # Add some warning
return process(post_array)
1 个回答
0
正如Jonathon Reinhart所提到的,把警告信息放在响应里是最好的做法。响应一定要返回200这个状态码。
from flask import Flask, request, jsonify # jsonify is helpful for ensuring json in response
class Function(MethodView):
def post(self):
# create a response body dict with an empty warnings list
response_body = {
'warnings': [],
'process_result': None
}
# create a guard in case POST request body is not JSON
if request.json:
post_array = np.array(json.loads(request.form['data']))
if post_array.shape != (48, 48):
post_array = post_array.resize((48,48))
# add a warning to the response body
warning = {'data_shape_warning': 'the supplied data was not 48 x 48'}
response_body['warnings'].append(warning)
# compute the process and add the result to the response body
result = process(post_array)
response_body['process_result'] = result
return response_body, 200
# action to take if the POST body is not JSON
else:
warning = {'data_format_warning': 'POST request data was not JSON'}
response_body['warnings'].append(warning)
return jsonify(response_body), 200