Reputation: 43
I am trying to write a webserver with Flask and e.g. have following function for post:
@app.route('/v1/tasks', methods=['POST'])
def post():
data=request.get_json()
title=data["title"]
tasks.append(json.dumps({"id": len(tasks), "title": title, "is_completed": "false"}))
index=len(tasks)-1
return json.dumps({"id":index}), 200
title=data["title"] throws following error:
TypeError: string indices must be integers
The input format for POST should be:
{title: "Test Task 2"}
I am confused because I saw a different post function, where access the contents of the JSON worked like this:
@app.route('/post', methods=['POST'])
def post():
data=request.get_json()
dictionary[data["key"]]=data["value"]
data["message"]="success"
return json.dumps(data)
What do I need to change so that I can access the title from the input JSON?
Thank you for your help!
Upvotes: 0
Views: 569
Reputation: 269
There is nothing wrong. Verify if you are using the correct MIME media type for posting JSON, which is application/json. Test your Flask server with this code and see if it works correctly.
import requests
response = requests.post('http://localhost:5000/v1/tasks', json={'title': "Test Task 2"})
print(response.status_code)
Upvotes: 1