b1995
b1995

Reputation: 1

How do I set up a connection to the NetSuite API in Python?

Does anyone have experience connecting to the NetSuite API?

I have followed the documentation, created new role with API access with my admin user account, enabled REST API features, created tokens and keys, still getting 401 error when trying to connect in my Python code. Using PyCharm as IDE.

Here is my code -

import requests
from requests_oauthlib import OAuth1

# Replace these with your actual NetSuite credentials
account_id = 'my_account_id'
consumer_key = 'my_consumer_key'
consumer_secret = 'my_consumer_secret'
token = 'my_token '
token_secret = 'my_token_secret'

url = f'https://{account_id}.suitetalk.api.netsuite.com/services/rest/record/v1/customer'
auth = OAuth1(consumer_key, consumer_secret, token, token_secret, signature_method='HMAC-SHA256')
headers = {
    'Content-Type': 'application/json'
}

response = requests.get(url, auth=auth, headers=headers)
if response.status_code == 200:
    print(response.json())
else:
    print(f"Error: {response.status_code} - {response.json()}")

Error -

C:\\Users\\username\\AppData\\Local\\Programs\\Python\\Python313\\python.exe C:\\Users\\username\\PycharmProjects\\NetSuiteAPI\\netsuite_integration.py 

Error: 401 - {'type': 'https://www.rfc-editor.org/rfc/rfc9110.html#section-15.5.2', 'title': 'Unauthorized', 'status': 401, 'o:errorDetails': \[{'detail': 'Invalid login attempt.', 'o:errorCode': 'INVALID_LOGIN_ATTEMPT'}\]}

Process finished with exit code 0

Upvotes: 0

Views: 58

Answers (1)

brddawg
brddawg

Reputation: 452

fellow PyCharm fan here. There are a few things different from what i'm running day to day and what you have is the realm=realm (account_id) and signature_type='auth_header' in your OAuth1 function. Additionally, you'll need to 'encrypt' or hash as a part of the call. Here's what I'm running:

# Python libraries required
import requests
from requests_oauthlib import OAuth1
import hmac
import hashlib
import base64

# NetSuite OAuth credentials can be saved seperately & imported
# Application ID: <>
# Application Name: <>
credentials = {
    'consumer': {
    'key': '<>',
    'secret': '<>'
},
'token': {
    'key': '<>',
    'secret': '<>'
},
'realm': '<>',
'suitetalk_url': 
'https://<>.suitetalk.api.netsuite.com/services/rest/record/v1/'
}

# Creates a SHA-256 HMAC hash of the base string using the given key.
def hash_function(base_string, key):
    """
    :param base_string: The base string to hash.
    :param key: The secret key used for hashing.
    :return: The base64-encoded hash string.
    """
    return base64.b64encode(
        hmac.new(key.encode(), base_string.encode(), hashlib.sha256).digest()
    ).decode()

 # Initializes and returns an OAuth1 session.
 def get_oauth_session(consumer_key, consumer_secret, token_key, token_secret, realm):
    """
   :param consumer_key: OAuth consumer key.
   :param consumer_secret: OAuth consumer secret.
   :param token_key: OAuth token key.
   :param token_secret: OAuth token secret.
   :param realm: OAuth realm (NetSuite account ID).
   :return: OAuth1 session object.
   """
   return OAuth1(
    client_key=consumer_key,
    client_secret=consumer_secret,
    resource_owner_key=token_key,
    resource_owner_secret=token_secret,
    signature_method='HMAC-SHA256',
    signature_type='auth_header',
    realm=realm
    )

# Initialize OAuth session
oauth = get_oauth_session(
    credentials['consumer']['key'],
    credentials['consumer']['secret'],
    credentials['token']['key'],
    credentials['token']['secret'],
    credentials['realm']
    )

# This block will only run if this file is executed directly, not when imported.
if __name__ == "__main__":
    print("OAuth session initialized:", oauth)

When this is set up correctly, you can import this file into other files in your project to run the OAuth process.

Upvotes: 0

Related Questions