Issue
I am trying to make a simple api in Flask, the first step being getting the POST json data. (I just want to print it for now) This is my code and when I request /api with json data, it returns a 500 error. Any thoughts on why this is happening?
from flask import Flask, request, Response
app = Flask(__name__)
@app.route('/')
def root_response():
return "Hello World."
@app.route('/api', methods=['POST', 'GET'])
def api_response():
if request.method == 'POST':
return request.json
if __name__ == '__main__':
app.run()
The curl command:
$ curl -H "Content-Type: application/json" --data @body.json http://127.0.0.1:5000/api
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 3.2 Final//EN">
<title>500 Internal Server Error</title>
<h1>Internal Server Error</h1>
<p>The server encountered an internal error and was unable to complete your request. Either the server is overloaded or there is an error in the application.</p>
body.json:
{
"please": "print",
"me": "now"
}
Solution
First what you want to do is enable debug mode so Flask will actually tell you what the error is. (And you get the added benefit of flask reloading every time you modify your code!)
if __name__ == '__main__':
app.debug = True
app.run()
Then we find out our error:
TypeError: 'dict' object is not callable
You're returning request.json, which is a dictionary. You need to convert it into a string first. It's pretty easy to do:
def api_response():
from flask import jsonify
if request.method == 'POST':
return jsonify(**request.json)
There you are! :)
Answered By - Theron Luhn
0 comments:
Post a Comment
Note: Only a member of this blog may post a comment.