简体   繁体   中英

Creating authenticated Python API call

I'm a little, well lot!, lost with how to make an API call using Python. I have done a number as trials successfully but now I am trying to build an app I am lost. The instructions below is all I am provided. I am unsure how to get beyond my code

MHL = urlopen('http://new.mhl.nsw.gov.au/services/mhladas/getAccessKey.json.php')

which then asks for username etc.

eg {u'access_key': None, u'error': u'No username has been entered'}

How do I send my details back to be authenticated by their server? and then have the request returned with the data I want? Happy to be directed to a tutorial on this or any help is truly appreciated. Not understanding how to convert their instructions into relevant Python code

4.1 Login – Request access key You need to make a login request to begin using the service. This login provides you with a limited time access key. You need to provide this key for any subsequent requests you make.

http://new.mhl.nsw.gov.au/services/mhladas/getAccessKey.json.php

Request {"username":"user@myserver.com","password":"abc123"} Example response {"access_key":" MjAxMy0wNS0x…”,”error":null}

4.2 Get Station List Use this function to list the stations you have available to you. http://new.mhl.nsw.gov.au/services/mhladas/getStationList.json.php Request {"username":"test@mhl.nsw.gov.au","access_key": " MjAxMy0wNS0x…"}

Information you have provided in the question is not clear. I am assuming you have to post request with username and password parameter. First of all use python request to do such things easily. pip install requests . Then try this.

payload = {'username': 'user@myserver.com', 'password': 'abc123'}
r = requests.post("http://new.mhl.nsw.gov.au/services/mhladas/getAccessKey.json.php", data = payload)
print r

To make a POST with urllib , you need to encode data with urlencode , and pass it as param to urlopen

import urllib

data = urllib.urlencode({"username":"buddy","password":"inches"})
post = urllib.urlopen('http://new.mhl.nsw.gov.au/services/mhladas/getStationList.json.php', data)

print post.code
print post.read()

Another way is to use requests as Sar009 suggested

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM