import requests
from datetime import datetime

# replace eu1 with the correct region (eu1, us1, ap1)
# Endpoint to request a token (valid for 30min)
auth_url = "https://ompprod.eu1.sws.siemens.com/oauth/token"
base_url = "https://cloud.eu1.sws.siemens.com/api/optimizemyplantapi/v1/omp"

# Note: The client_id and client_secret can be obtained from the Xcelerator Admin Console
# by creating a Server User for Optimize my plant 
client_id = "<your client_id>"  # replace with your client_id
client_secret = "<your client_secret>"  # replace with your client_secret

payload = 'grant_type=client_credentials&client_id=' + client_id + '&client_secret=' + client_secret
headers = {
  'Content-Type': 'application/x-www-form-urlencoded'
}

response = requests.request("POST", auth_url, headers=headers, data=payload)

if response.status_code != 200:
  print ('Error' + str(response.status_code))
  exit()

# If the response is successful, extract the token and its expiration time
Token = response.json()['access_token']
# Token_expires_in is the number of seconds until the token expires
Token_expires_in = response.json()['expires_in'] 
# Calculate the expiration timestamp
Token_expires = datetime.now().timestamp() + Token_expires_in
# if you reuse the token for multiple requests, you can check if the token is still valid
# by comparing the current timestamp with Token_expires

headers.clear() # reusing previous headers variable, clear it 
# build the header with the bearer token
# set that the result should be in JSON format (XML is not supported)
headers = {
  'Content-Type': 'application/json',
  'Authorization': 'Bearer ' + Token
}

# this is the API to retrieve the list of projects
url = base_url + "/projects"

payload = {}
response = requests.request("GET", url, headers=headers, data=payload)

if response.status_code != 200:
  print ('Error' + str(response.status_code))
  exit()

print(response.json())