我是制作API的初学者。我已关注博客https://blog.miguelgrinberg.com/post/designing-a-restful-api-with-python-and-flask并能够创建Get-Post API方法。
我正在使用Flask制作Rest API。请参阅下面的代码,我想在API中将其作为输入,并通过将我的代码作为API返回JSON格式的答案。
app = Flask(__name__)
@app.route('/match/api/v1', methods = ['POST'])
def my_form_post():
if not request.json or not 'question' in request.json:
abort(400)
input_text_p = request.json['question'] # access input from curl request
reference_data = request.json['data'] # to access data field from the API request
path = 'airtel_faq.xlsx'
question_list, answer_list = read_excel_file(path) # reading some reference data from an excel file
input_text = input_text_p.translate(None, string.punctuation) # remove punctuation
final_answer = find_similarity(input_text, answer_list, question_list)
print "Final Answer is : ", final_answer
values = [
{'id' : 1,
'answer' : final_answer # answer I want in JSON
'done' : False
}
]
return jsonify({'values': values}), 201
if __name__ == '__main__':
app.run(debug = True)
我正在尝试将请求中的数据标记的哈希输入传递给API。我不知道该怎么做。我正在提出的卷曲请求是错误的:
Failed to decode JSON object: Expecting ',' delimiter or '}': line 1 column 80 (char 79)
我正在制作的卷曲请求:
curl -i -H "Content-Type: application/json" -X POST -d '{"question":"Hi","cutoff":"0.3", "data":"{"q":"hello whats going on","a":"I am fine","type":"1"}"}' http://localhost:5000/match/api
请让我知道如何做到这一点。我是否必须在脚本中包含任何内容。或者有没有办法通过给文件路径传递API调用中的JSON文件。
答案 0 :(得分:0)
为了解析JSON请求,它需要是有效的JSON。试试这个请求:
curl -i -H "Content-Type: application/json" -X POST -d '{"question": "Hi", "cutoff": "0.3", "data": {"q": "hello whats going on", "a": "I am fine", "type": "1"}}' http://localhost:5000/match/api