Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Looking for example Python code for Netsuite API using OAuth?

Netsuite's documentation is not forthcoming. Does anyone have code they've written that will help me generate a valid signature.

like image 393
Justin H. Avatar asked Oct 16 '15 15:10

Justin H.


2 Answers

There is some sample code in the NetSuite Suite answers site, but you'll have to log in to access it.

https://netsuite.custhelp.com/app/answers/detail/a_id/42165/kw/42165

Here is the code from the answer that I was able to make work. The only difference is that their code broke by trying to encode the timestamp as an int. I typecasted it to a str and the encoding worked fine. The keys/tokens/realm are from their demo code. Insert your own and you should be good to go.

import oauth2 as oauth
import requests
import time

url = "https://rest.netsuite.com/app/site/hosting/restlet.nl?script=992&deploy=1"
token = oauth.Token(key="080eefeb395df81902e18305540a97b5b3524b251772adf769f06e6f0d9dfde5", secret="451f28d17127a3dd427898c6b75546d30b5bd8c8d7e73e23028c497221196ae2")
consumer = oauth.Consumer(key="504ee7703e1871f22180441563ad9f01f3f18d67ecda580b0fae764ed7c4fd38", secret="b36d202caf62f889fbd8c306e633a5a1105c3767ba8fc15f2c8246c5f11e500c")

http_method = "GET"  
realm="ACCT123456"

params = {
    'oauth_version': "1.0",
    'oauth_nonce': oauth.generate_nonce(),
    'oauth_timestamp': str(int(time.time())),
    'oauth_token': token.key,
    'oauth_consumer_key': consumer.key
}

req = oauth.Request(method=http_method, url=url, parameters=params)
signature_method = oauth.SignatureMethod_HMAC_SHA1()
req.sign_request(signature_method, consumer, token)
header = req.to_header(realm)
headery = header['Authorization'].encode('ascii', 'ignore')
headerx = {"Authorization": headery, "Content-Type":"application/json"}
print(headerx)
conn = requests.get("https://rest.netsuite.com/app/site/hosting/restlet.nl?script=992&deploy=1",headers=headerx)
print(conn.text)
like image 191
Tyrel Denison Avatar answered Nov 14 '22 22:11

Tyrel Denison


Just for reference, I recently did this in Python3 using requests_oauthlib and it worked with standard use of the library:

from requests_oauthlib import OAuth1Session
import json

url = 'https://xxx.restlets.api.netsuite.com/app/site/hosting/restlet.nl?script=xxx&deploy=xxx'

oauth = OAuth1Session(
    client_key='xxx',
    client_secret='xxx',
    resource_owner_key='xxx',
    resource_owner_secret='xxx',
    realm='xxx')

payload = dict(...)
resp = oauth.post(
    url,
    headers={'Content-Type': 'application/json'},
    data=json.dumps(payload),
)

print(resp)
like image 25
Ilmari Aalto Avatar answered Nov 14 '22 22:11

Ilmari Aalto