1

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).

1 Answer 1

1

A small bug is causing you the trouble

response = requests.post('https://ws.foo.net/search', 
                         json=jsonObject # was json.dumps(jsonObject), 
                         auth=('name', 'password'))

This should work fine

See, the request package will convert the python dict to Json (not you ;))

Sign up to request clarification or add additional context in comments.

1 Comment

That did it. Hugely appreciated. Thank you.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.