Skip to Content
0
Aug 04, 2023 at 10:59 AM

Python Service Layer REST API Bearer token not working when calling SQLQueries

149 Views

Hi All,

I'm hoping you can help me, I've got the following Python code which successfully connects to our SAP B1 database and gains a bearer token.

Although when I try to use that token to authenticate an SQLQueries() get request it errors with 401

Query response: {

"error" : {

"code" : 100000027,

"message" : {

"lang" : "en-us",

"value" : "Company database does not exist\n"

}

The code I'm running is below and the SQLQueries('sql05')/List works using Postman.

import requests

# Define the connection settings

base_url = 'https://xxxxxxxxxxxxxxx.net:50000'

username = 'User123'

password = 'Pass1234'

companyDB = 'DBLIVE'

# Build the login URL

login_url = f"{base_url}/b1s/v1/Login"

# Prepare the login payload

payload = {

"CompanyDB": companyDB,

"UserName": username,

"Password": password

}

# Send the login request

response = requests.post(login_url, json=payload)

# Check if the login request was successful

if response.status_code == 200:

# Extract the bearer token from the response

bearer_token = response.json()['SessionId']

print("Login successful!")

print(f"Bearer token: {bearer_token}")

# Build the request URL

query_url = f"{base_url}/b1s/v1/SQLQueries('sql05')/List"

# Define header for making API calls that will hold authentication data

headers = {

'Authorization': 'Bearer '+ bearer_token

}

# Send the query request

query_response = requests.get(query_url, headers=headers)

# Check if the query request was successful

if query_response.status_code == 200:

# Extract the results from the response

results = query_response.json()['results']

# Print the results

for row in results[0]['result']:

print(row)

else:

print(f"Query request failed with status code: {query_response.status_code}")

print(f"Query response: {query_response.text}")

else:

print(f"Login request failed with status code: {response.status_code}")

Any help would be appreciated.

Regard,

Gary