简体   繁体   中英

SurveyMonkey API Error400 on bad JSON string when JSON string for creating survey poll is valid

I was looking into ways to create surveys programmatically and came across SurveyMonkey APIs. I manually created an empty survey on my account and created a draft app and got an access token from there. And then I copied & pasted the example code from the API doc on the section of creating a survey question to try it out.

You can also see the code here where the survey ID and the page ID were obtained by using the /surveys and /surveys/{id}/pages end points.

However, I get this following error.

{u'error': {u'docs': u'https://developer.surveymonkey.com/api/v3/#error-codes', u'message': u'The body provided was not a proper JSON string.', u'http_status_code': 400, u'id': u'1001', u'name': u'Bad Request'}}

I checked that the JSON object is valid and contains all the required parameters as specified in the doc. I also tried some smaller, simpler questions and still no success. If I passed in an empty JSON object, it does complain about the missing required parameters. I was wondering if someone could point out what I'm doing wrong. Thank you!

The issue is you aren't actually sending the body as json properly.

url = "https://api.surveymonkey.net/v3/surveys/%s/pages/%s/questions" % (survey_id, page_id)
r = s.post(url, data=payload)
print r.json()

You need to json.dumps(payload)

import json
url = "https://api.surveymonkey.net/v3/surveys/%s/pages/%s/questions" % (survey_id, page_id)
r = s.post(url, data=json.dumps(payload))
print r.json()

In newer version of the requests library you can use the json kwarg for that.

url = "https://api.surveymonkey.net/v3/surveys/%s/pages/%s/questions" % (survey_id, page_id)
r = s.post(url, json=payload)
print r.json()

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM