SAP Datasphere : Export Data of AnalyticalModel via Odata URL & Oauth Client of type Technical User

Estimated read time 6 min read

In this blog, I have explained how to export data from an analytical model into CSV file securely using an OData URL and a technical user OAuth client.

Step – 1) Create an Oauth Client with Purpose as Technical User and select required roles. get client ID and secret and save it. How to Guide 

Step – 2) Create Odata_Tech_User_OauthClient.py file with below code 

 

# — IMPORTS —
import requests # For making HTTP requests to token and OData endpoints
import pandas as pd # For handling tabular data from the OData response
import os # For file path resolution and environment variable access
from dotenv import load_dotenv # For loading credentials from a .env file

# — LOAD ENV VARIABLES —
load_dotenv() # Load environment variables from .env file into the runtime

# — CONFIG: Read credentials and endpoints from environment —
odata_url = os.getenv(“ODATA_URL”) # OData service endpoint
token_url = os.getenv(“TOKEN_URL”) # OAuth token endpoint
client_id = os.getenv(“CLIENT_ID”) # OAuth client ID
client_secret = os.getenv(“CLIENT_SECRET”) # OAuth client secret

# — GET TOKEN: Request access token using client credentials —
token_payload = {
“grant_type”: “client_credentials”, # OAuth flow type
“client_id”: client_id, # Injected from .env
“client_secret”: client_secret # Injected from .env
}
token_resp = requests.post(token_url, data=token_payload) # POST request to token endpoint
token_resp.raise_for_status() # Raise error if token request fails
access_token = token_resp.json()[“access_token”] # Extract access token from response

# — CALL ODATA SERVICE: Fetch data using bearer token —
headers = {“Authorization”: f”Bearer {access_token}”} # Auth header with token
response = requests.get(odata_url, headers=headers) # GET request to OData endpoint
response.raise_for_status() # Raise error if data fetch fails

# — PARSE RESULTS: Convert JSON payload to DataFrame —
data = response.json()[“value”] # Extract ‘value’ list from OData response
df = pd.DataFrame(data) # Convert list of records to pandas DataFrame

# — DISPLAY OR EXPORT: Show preview and optionally save to CSV —
print()
print(“🔍 Displaying top rows for quick inspection:”)
print()
print(df.head()) # Display top rows for quick inspection
print()

# — Extract view name from OData URL —
view_name = odata_url.rstrip(“/”).split(“/”)[-1] # Gets ‘AM_EXPORT’ from the URL

# — Construct filename —
filename = f”{view_name}.csv”

# — Display and save —
df.to_csv(filename, index=False)
print(f”📁 Exported data Saved to: {os.path.abspath(filename)}”)

 

Step – 3) Create .env file with all values of variables.

ODATA_URL : Copy the Odata link from analytical model

 

TOKEN_URL : get it from Datasphere -> System -> App Integration page

CLIENT ID & Secret : Get it from Step-1

Step-  4) Create .bat file with blow code 

 

off

chcp 65001 >nul

REM ───────────────────────────────────────────────
REM 🚀 ODATA TECH USER OAUTH CLIENT EXECUTION SCRIPT
REM ───────────────────────────────────────────────

echo.
echo ==============================================
echo 🔄 Starting OData export process…
echo ==============================================

REM — Navigate to script directory —
cd /d “%~dp0”

REM — Run the Python script —
echo 🐍 Running Python script: Odata_Tech_User_OauthClient.py
python Odata_Tech_User_OauthClient.py

REM — Completion message —
echo.
echo ✅ Script execution completed.
echo ==============================================

REM — Keep window open —
pause

 

Keep all files in same directory

Once everything is set up, just double-click the .bat file to run the process. It will execute the Python script and, once finished, generate a .csv file name exactly same name as the analytical model name. As part of the execution, the first five rows of data will also be displayed on screen for quick preview

Thanks

Vikas Parmar

 

 

​ In this blog, I have explained how to export data from an analytical model into CSV file securely using an OData URL and a technical user OAuth client.Step – 1) Create an Oauth Client with Purpose as Technical User and select required roles. get client ID and secret and save it. How to Guide Step – 2) Create Odata_Tech_User_OauthClient.py file with below code  # — IMPORTS —
import requests # For making HTTP requests to token and OData endpoints
import pandas as pd # For handling tabular data from the OData response
import os # For file path resolution and environment variable access
from dotenv import load_dotenv # For loading credentials from a .env file

# — LOAD ENV VARIABLES —
load_dotenv() # Load environment variables from .env file into the runtime

# — CONFIG: Read credentials and endpoints from environment —
odata_url = os.getenv(“ODATA_URL”) # OData service endpoint
token_url = os.getenv(“TOKEN_URL”) # OAuth token endpoint
client_id = os.getenv(“CLIENT_ID”) # OAuth client ID
client_secret = os.getenv(“CLIENT_SECRET”) # OAuth client secret

# — GET TOKEN: Request access token using client credentials —
token_payload = {
“grant_type”: “client_credentials”, # OAuth flow type
“client_id”: client_id, # Injected from .env
“client_secret”: client_secret # Injected from .env
}
token_resp = requests.post(token_url, data=token_payload) # POST request to token endpoint
token_resp.raise_for_status() # Raise error if token request fails
access_token = token_resp.json()[“access_token”] # Extract access token from response

# — CALL ODATA SERVICE: Fetch data using bearer token —
headers = {“Authorization”: f”Bearer {access_token}”} # Auth header with token
response = requests.get(odata_url, headers=headers) # GET request to OData endpoint
response.raise_for_status() # Raise error if data fetch fails

# — PARSE RESULTS: Convert JSON payload to DataFrame —
data = response.json()[“value”] # Extract ‘value’ list from OData response
df = pd.DataFrame(data) # Convert list of records to pandas DataFrame

# — DISPLAY OR EXPORT: Show preview and optionally save to CSV —
print()
print(“🔍 Displaying top rows for quick inspection:”)
print()
print(df.head()) # Display top rows for quick inspection
print()

# — Extract view name from OData URL —
view_name = odata_url.rstrip(“/”).split(“/”)[-1] # Gets ‘AM_EXPORT’ from the URL

# — Construct filename —
filename = f”{view_name}.csv”

# — Display and save —
df.to_csv(filename, index=False)
print(f”📁 Exported data Saved to: {os.path.abspath(filename)}”) Step – 3) Create .env file with all values of variables.ODATA_URL : Copy the Odata link from analytical model TOKEN_URL : get it from Datasphere -> System -> App Integration pageCLIENT ID & Secret : Get it from Step-1Step-  4) Create .bat file with blow code   off

chcp 65001 >nul

REM ───────────────────────────────────────────────
REM 🚀 ODATA TECH USER OAUTH CLIENT EXECUTION SCRIPT
REM ───────────────────────────────────────────────

echo.
echo ==============================================
echo 🔄 Starting OData export process…
echo ==============================================

REM — Navigate to script directory —
cd /d “%~dp0”

REM — Run the Python script —
echo 🐍 Running Python script: Odata_Tech_User_OauthClient.py
python Odata_Tech_User_OauthClient.py

REM — Completion message —
echo.
echo ✅ Script execution completed.
echo ==============================================

REM — Keep window open —
pause Keep all files in same directoryOnce everything is set up, just double-click the .bat file to run the process. It will execute the Python script and, once finished, generate a .csv file name exactly same name as the analytical model name. As part of the execution, the first five rows of data will also be displayed on screen for quick previewThanksVikas Parmar    Read More Technology Blog Posts by Members articles 

#SAP

#SAPTechnologyblog

You May Also Like

More From Author