Requests after login (Python)

Added by Mikko almost 8 years ago

Hello,

I have succeed login with python example, but what after that?
Document explain that after login the session key should be used as both HTTP auth username and password.
Looking other examples (Java etc..) I have tried all kind of new params field.
Here is one example I have tried after login:

49 # Get session_key
50 sk = j["session_key"]
51
52 # Try to make new auth param using session_key
53 # v1.16 doc (Authentication): The session key should be used as both HTTP auth username and password.
54 buf = base64.b64encode(sk)+':'+base64.b64encode(sk)
55 rsa=RSA.load_pub_key('NEXTAPI_TEST_public.pem')
56 encrypted_hash = rsa.public_encrypt(buf, RSA.pkcs1_padding)
57 hash = base64.b64encode(encrypted_hash)
58 params = urllib.urlencode({'service': 'NEXTAPI', 'auth': hash})
59
60 # Now try to get accounts
61 conn.request('GET','https://'+BASE_URL+'/'+API_VERSION+'/accounts',params,headers)
62 r=conn.getresponse()
63 response=r.read()
64 j = json.loads(response)
65 print_json(j)

This does not work because I get 'error:Invalid session'
How should I cerate that 'auth param' for rest of session request.


Replies (3)

RE: Requests after login (Python) - Added by Nordnet Simon almost 8 years ago

Hi, If you use the example https://api.test.nordnet.se/projects/api/wiki/Code_examples#Login-example-in-Python then you see an output of the login response. The output looks like this.


skip_phrase:True
system_running:True
valid_version:True
country:SE
expires_in:300
environment:test
private_feed
  encrypted:True
  hostname:priv.api.test.nordnet.se
  port:443
session_key:d10cb2534556982bd01442034acf68fdbd8da77e
public_feed
  encrypted:True
  hostname:pub.api.test.nordnet.se
  port:443

The session_key field must be used as username and password in in the Basic Auth: field in the header.

Add this after the example (please note that I am not a Python expert and there might be much easier way to solve this):

# Get accounts

session_key = j['session_key'] # Get the session_key from the login response

print 'Session key: %s' % session_key

basic_auth = 'Basic ' + urllib.quote(base64.b64encode('%s:%s' % (session_key,session_key)).strip())

headers['Authorization'] = basic_auth

conn.request('GET', 'https://'+BASE_URL+'/'+API_VERSION + '/accounts', '', headers)
r=conn.getresponse()
response=r.read()
print response


RE: Requests after login (Python) - Added by Mikko almost 8 years ago

Thanks,

Now it works. Actually there becomes immediatelly new error,
because account 'Alias' name is null ptr. Anyway now I can
continue. Account summary,ledgers,... succesfully read.

P.S. I have never written anythin python code, not even anything
web code at all. Is there some language that you recommend
for web programming? I start this nExt-API test with ruby but
something fails, then changed to python and that login example
works.

RE: Requests after login (Python) - Added by mika over 7 years ago

Hi,

Attached more comprehensive python example. It covers pretty much full REST API.
Simon/others, please replace earlier python example with this one.

Br,
Mika

# nordnet API test 
# https://api.test.nordnet.se/
import time
import base64
import requests
import json
from M2Crypto import RSA

def print_json(j,prefix=''):
    if prefix=='':
        print '*'*20
    if not isinstance(j,list):
        j=[j]
    for d in j:
        for key, value in d.items():
            if isinstance (value,dict):
                print '%s%s' % (prefix,key)
                print_json(value, prefix+'  ')
            else:
                print '%s%s:%s' % (prefix,key,value)

timestamp = int(round(time.time()*1000))
timestamp = str(timestamp)
mylogin, mypassword = open('mycredentials.txt','r').read().split('\n')
login = base64.b64encode(mylogin)
password = base64.b64encode(mypassword)
phrase = base64.b64encode(timestamp)
buf = login+':'+password+':'+phrase
rsa=RSA.load_pub_key('NEXTAPI_TEST_public.pem')
encrypted_hash = rsa.public_encrypt(buf, RSA.pkcs1_padding)
hash = base64.b64encode(encrypted_hash)

BASE_URL='api.test.nordnet.se/next'
API_VERSION='1'
URL = 'https://%s/%s' % (BASE_URL,API_VERSION)

def req(cmd=''):
    r=requests.get(URL + '/%s' % cmd ,auth = auth, headers=headers)
    return json.loads(r.text)

def touch(): requests.put(URL+'/login/%s' % session_key, auth = auth, headers=headers)

def logout():    
    r=requests.delete(URL + '/login/%s' % session_key, auth = auth, headers=headers)
    print_json(json.loads(r.text))

def buy(identifier,marketID,price,volume,currency): 
    r = requests.post(URL + '/accounts/%s/orders' % account_id,
        data={'identifier':identifier,'marketID':marketID,'price':price,'volume':volume,'currency':currency,'side':'buy'}, 
        auth=auth, headers=headers).text
    return json.loads(r)

def delete_order(order_id): return json.loads(requests.delete(URL+'/accounts/%s/orders/%s' % (account_id, order_id), auth=auth, headers=headers).text)

def f2():
    global headers, params, session_key, auth, account_id
    headers = {"Content-type": "application/x-www-form-urlencoded","Accept": "application/json",'Accept-Language':'en'}
    params = {'service': 'NEXTAPI', 'auth': hash}
    r = requests.get(URL, headers = headers)
    print_json(json.loads(r.text))

    r=requests.post(URL + '/login',data=params, headers=headers)
    print_json(json.loads(r.text))

    rj=json.loads(r.text)
    session_key=rj['session_key']
    auth = (session_key,session_key)

    print_json(req('accounts'))
    account_id = req('accounts')[0]['id']

    print_json(req('accounts/%s' % account_id))
    print_json(req('accounts/%s/ledgers' % account_id))
    print_json(req('accounts/%s/positions' % account_id))
    if 1:
        print_json(req('accounts/%s/orders' % account_id)) # Exchange orders
        print_json(req('accounts/%s/trades' % account_id)) # Exchange trades
        print_json(req('instruments?query=abb&type=A&country=SE'))
        print_json(req('instruments?identifier=101&marketID=11'))
        print_json(req('instruments?list=11,101;11,817;11,939')) 
        print_json(req('chart_data?marketID=11&identifier=101')) # response = u'error': u'Instrument not found'}
        #print_json(req('lists/26'))
        print_json(req('markets'))
        print_json(req('indices'))
        print_json(req('ticksizes/11002'))
##        print_json(req('derivatives/WNT'))

    r=buy(101,11,80,2,'SEK')
    print print_json(r)
    print_json(req('accounts/%s/orders' % account_id))
    print_json(delete_order(r['orderID']))
    print_json(req('accounts/%s/orders' % account_id))

f2()


(1-3/3)