Iram Khan
Iram Khan

Reputation: 37

x-auth-token not passed in header when making a request

headers = {'x-auth-token': token,'Content-type':'application/json'}  
url2="http://192.168.56.1:8081/whitelist"
print "HEaders",headers
re=requests.get(url2,headers=headers)
print re.content
r = requests.post(url2, data=json.dumps(file_as_inp))
print r
print "code:"+ str(r.status_code)
print "******************"
print "headers:"+ str(r.headers)
print "******************"
print "content:"+ str(r.content)

I am writing a script so as to post data to a webservice. I am passing auth-token and content type in header and a list of json values as payload. The file_as_inp contains list of json values as

[{'ip': '10.1.2.3'}, {'ip': '10.3.4.5'}, {'ip': '10.8.9.A'}, {'ip': '0'}, {'ip':'00'}, {'ip': 'null'}, {'ip': '10.9.4.5'}, {'ip': '10.7.6.2'}]

Headers contains :

{'Content-type': 'application/json', 'x-auth-token': u'313e95e7-ce08-46bf-8891-6d68fc615170'}  

I am running my service on one command prompt and on other command prompt I am running this script. I get response as 200. When I print r.headers i get some output as

headers:{'Content-Length': '57', 'Access-Control-Allow-Headers': 'Content-Type', 'Access-Control-Max-Age': '21600', 'Server': 'Werkzeug/0.11.9 Python/2.7', 'Date': 'Fri, 13 May 2016 04:47:52 GMT', 'Access-Control-Allow-Origin': '*', 'Access-Control-Allow-Methods': 'HEAD, GET, POST, OPTIONS', 'Content-Type': 'text/html;charset=utf-8'}

However, when I print r.content, I get the below line printed :

content:x-auth-token not passed in header, please pass the token.

Can someone tell me where am I going wrong? Why am I getting the above line as output? After I post data to the webservice, I need to perform validations and check if IP is valid or no. But, I am stuck here.

Upvotes: 1

Views: 5638

Answers (1)

JRodDynamite
JRodDynamite

Reputation: 12613

You are not setting the header values when you are calling the POST request. You can change you code to:

r = requests.post(url, data=json.dumps(file_as_inp), headers=headers)

Or the recommended way would be to use the Session object.

The Session object allows you to persist certain parameters across requests. Sessions can also be used to provide default data to the request methods. This is done by providing data to the properties on a Session object:

The x-auth-token will be added onto the header of every request you make using the Session object. Your code should then look something like this:

sess = requests.Session()
sess.headers.update({'x-auth-token': token,'Content-type':'application/json'}  )
url = "http://192.168.56.1:8081/whitelist"

resp = sess.get(url, headers=headers)
print resp.content

resp = sess.post(url, data=json.dumps(file_as_inp))
print resp.content

Upvotes: 3

Related Questions