ketan
ketan

Reputation: 2904

How to send POST Request in python and get proper json response?

I want to get POST Web service data in python. For that purpose, I tried below:

import requests
import json

headers = {'content-type': 'application/json','charset': 'utf-8'}
url = 'https://a.b.c.com/count/WebService.asmx/ReadJSON'
data = {'tick': '123456A123456B'}
response = requests.post(url, data=json.dumps(data), headers=headers)
print response.status_code
print response.text

Above code output:

200
{"a":""}

But Actually, key "a" has some value which I'm not getting. I don't understand it's giving me status code as 200 i.e. OK then why I'm not able to get the proper JSON response. Is I missed something in code?

Upvotes: 2

Views: 4779

Answers (1)

Sraw
Sraw

Reputation: 20224

You should use json=data to pass json in requests but not manually modify headers, and you should use response.json() to get json result if you make sure it is.

import requests

headers = {'charset': 'utf-8'}
url = 'https://a.b.c.com/count/WebService.asmx/ReadJSON'
data = {'tick': '123456A123456B'}
response = requests.post(url, json=data, headers=headers)
print response.status_code
print response.json()

Upvotes: 4

Related Questions