Requests after login (Python)

Added by Mikko over 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 (5)

RE: Requests after login (Python) - Added by Nordnet Simon over 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 over 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 8 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()


RE: Requests after login (Python) - Added by sunh 20 days ago

This is the video I missed so much. I'm curious how you can find 먹튀검증 and upload the material I wanted 먹튀검증 I was impressed with your video 스포츠중계 먹튀검증사이트 yours메이저토토사이트. 메이저안전놀이터 the best. we look forward to a lot of 꽁머니 in the future.I have a lot of videos related to 안전놀이터 If you have time, please visit my안전놀이터 and 안전놀이터 꽁머니 along with 안전놀이터, our site 토토사이트 also has the same information. We ask for your interest in our site as well. This was the above 먹튀검증.

RE: Requests after login (Python) - Added by sunh 20 days ago

가장확실한먹튀검증커뮤니티, I really enjoyed reading your post. 먹튀검증 It's very helpful for me. 먹튀신고 Actually, 먹튀 my friend recommended this article. 먹튀검증업체 My friend recommended me 먹튀커뮤니티 to read it 먹튀사이트검증 because it is really good. 먹튀사이트 So I read it, 메이저놀이터 and it was really good. 메이저안전놀이터추천 I think I did a really good job reading it. 메이저놀이터추천 Actually, I'm doing something similar to you. 메이저놀이터 It's not exactly the same, 사설토토 but we have a lot in common. 메이저사설토토 As for what I do, 사설토토사이트추천 I have uploaded 사설토토사이트 a lot of posts on my website. 사설놀이터 If you're interested,안전놀이터 please visit 토토안전놀이터 and read it. 안전놀이터 You won't regret it. 토토사이트 Above all, 토토추천 I'm so glad to 메이저토토사이트 meet someone who is doing something similar. 먹튀없는토토사이트 I hope you will continue to upload good contents like the current post. 토토사이트추천 Thank you. 토토사이트 Have a nice day.

(1-5/5)