2022-09-22

How to make subsequent request to SAP Business One Service Layer from Django

I want to use Django to make requests to SAP Business One Service Layer. SAP B1 Service Layer requires initial login to establish a session. I am able to authenticate and get a correct response with a returned session ID from the Service Layer. There is a 30 minute timeout after successful login if there is no activity. How can I save a session from another server (in this case the Service layer) to make additional requests? Below is code of the initial SAP post request to the Login endpoint.

def AuthSAP(request):
     sap_url = "https://sap_url.com:50000/b1s/v2/Login"
    
     headers = {
        "authkey": "XXXXXXXXXXXXXXXXXXXX",
        "Accept": "*/*",
        "Content-Type": "text/plain",
    }

    data = {
        "CompanyDB": "XXXXXXXX",
        "UserName": "XXXXXXXX",
        "Password": "XXXXXXX"
    }

    response = requests.post(sap_url, headers=headers, json=data)

    print("JSON Response ", response.json())
    return HttpResponse(response.json(), content_type='application/json')

When I make additional request to the Service Layer I get an error from the JSON Response. Any insight or suggestions is much appreciated. Thank you.

For example, if I make another request to any other end point I will get the error message below (GET https://sap_url.com:50000/b1s/v2/Orders).

/* Subsequent Calls require header info with authkey. Body not needed */

def GetOpenOrders(request):

sap_url = "https://sap_url.com:50000/b1s/v2/Orders"
headers = {
    "authkey": "XXXXXXXXXXXXXXXXXXXX",
    "Accept": "*/*",
    "Content-Type": "text/plain",
}

response = requests.get(sap_url, headers=headers)
print("JSON Response ", response.json())
return HttpResponse(response.json(), content_type='application/json')
JSON Response  {'error': {'code': '301', 'message': 'Invalid session or session already timeout.'}}



No comments:

Post a Comment