4

I am completely new to Python. I need to post an authentication request to a website using header and body details. I have posted the code below that I have so far. When I run it, I get syntax error on this line:

req.add_header('API-KEY': 'my_api_key', 'ACCOUNT-ID': 'my_account_id', 'Content-Type': 'application/json; charset=UTF-8', 'VERSION': '2')

Can you please review and let me know where I've gone wrong?

import urllib.request
import json

body = {'identifier': 'my_id', 'password': 'my_encrypted_pwd', 'encryptedPassword': true}

url = 'https://mywebsite.com/gateway/deal/session'
req = urllib.request.Request(url)
req.add_header('API-KEY': 'my_api_key', 'ACCOUNT-ID': 'my_account_id', 'Content-Type': 'application/json; charset=UTF-8', 'VERSION': '2')
jsondata = json.dumps(body)
jsondataasbytes = jsondata.encode('UTF-8')
req.add_header('Content-Length', len(jsondataasbytes))
print (jsondataasbytes)
response = urllib.request.urlopen(req, jsondataasbytes)

1 Answer 1

2

I suggest you should use the requests module, as it's faster and simply better than urllib.request:

response = requests.put(
        url,
        body, headers={'API-KEY': 'my_api_key',
                       'ACCOUNT-ID': 'my_account_id',
                       'Content-Type': 'application/json; charset=UTF-8',
                       'VERSION': '2'
              }
        )

Now you can parse the response you get as usual.

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

Comments

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.