0

Using Python 3.5 and requests 2.18.4 I need to send data to another service, and it is currently failing for some reason. Sending is made after I receive and clean data from another service, and eventually get the data verified and set as a native python dict. This works when the data is hardcoded and I am not using the incoming data (hardcoded json string):

def my_post_method(self, url, data):
    # import requests (above)
    return requests.post(
        url,
        data='{"keyA":"valA", "keyB":"valB" ... }',
        headers={'Content-Type': 'application/json'},
    ) # status 200

But I cannot send it with the original data for some reason.

def my_post_method(self, url, data):
    # import requests, json (above)
    d = json.dumps(data)
    return requests.post(
        url,
        data=d,
        headers={'Content-Type': 'application/json'},
    ) # status 400 

d from above: {"keyA":"valA", "keyB":"valB" ... }

I tried to use the requests json parameter instead of data, but the other service is apparently expecting data parameter on the other end. Does it mean that the service I am posting to is waiting on a json-formatted string?

davidism
  • 121,510
  • 29
  • 395
  • 339
camelBack
  • 748
  • 2
  • 11
  • 30
  • Can we know the other service? Is it something public that we can try? – GendoIkari Aug 31 '17 at 19:56
  • Have you tried making the POST with the hard-coded string again? Is it possible that the service is returning 400s because it doesn't want you to make the same request twice? – Rob Watts Aug 31 '17 at 19:59
  • Thank @Rob Watts, but I answered below- for some odd reason, ordering of keys-values was taken into consideration when the receiving end was verifying the incoming data. I really don't know why... – camelBack Aug 31 '17 at 20:12
  • @camelBack I had a similar problem and discovered running dumps twice on the payload worked. The second dumps escapes all of the double quotes in the json string from the first. – user1951756 Jul 02 '19 at 13:12

1 Answers1

2

I would use the argument json in requests.post that accepts Python dictionaries, if you are using at least version 2.4.2 of requests, avoiding json.dumps completely.

More complicated requests

EDIT: I can't reproduce the problem in any way, json should work, it's the only correct way to send a json with a post in modern requests.

GendoIkari
  • 244
  • 1
  • 7