Using requests to post JSON to a web service. Typing out the JSON like this works:
response = requests.post('https://ws.foo.net/search',
json=({
"filters": [
{
"filters": [
{
"field": "type",
"type": "EQ",
"value": "THING"
}
]
},
{
"filters": [
{
"field": "responseCode",
"type": "EQ",
"value": "301"
},
{
"field": "responseCode",
"type": "EQ",
"value": "302"
}
]
},
{
"filters": [
{
"field": "State",
"type": "EQ",
"value": "CONFIRMED"
}
]
}
]
}), auth=('name', 'password'))
I want to use variables in the JSON so constructing that from a dictionary using json.dumps.
Below produces a 400 error:
Could not read JSON: Can not instantiate value of type [simple type, classcom.linkco.ws.v1.model.V1SearchQuery] from JSON String; no single-String constructor/factory method
import json
import requests
jsonObject = {'filters': [{'filters': [{'field': 'type','type': 'EQ','value': 'WEB_SITE'}]},{'filters': [{'field': 'name','type': 'EQ','value': 'something'}]},{'filters': [{'field': 'State','type': 'EQ','value': 'CONFIRMED'}]}]}
response = requests.post('https://ws.foo.net/search', json=json.dumps(jsonObject), auth=('name', 'password'))
print json.dumps(jsonObject)
print '----'
print response.text
I'm printing the json.dumps(jsonObject) to check and it produces valid JSON and works if copied to a REST client I'm using - it's good (well - it's probably not for a reason I've failed to find).