Skip to content

Accessing Industrial IoT APIs from self-hosted applications

This section describes how self-hosted applications can access Industrial IoT APIs with/without being integrated into Insights Hub. This way you can utilize Industrial IoT services to enrich your own applications.

  • Create an application in Developer Cockpit, generate the App Credentials (it can be generated with/without App registration).
  • Use these credentials inside your code to access Industrial IoT APIs.

Info

If required, you can integrate your Self-hosted application to Insights Hub. For more information, see self-hosted integration into Insights Hub. If you are not willing to promote your application from Developer Cockpit to Operator Cockpit or access your application through Insights Hub portal, follow the same process.

Prerequisites

For this Getting Started you need:

  • MindAccess DevOps Plan - this is your Insights Hub account (tenant).
  • Outbound Traffic Upgrade - this includes a data volume for consuming Industrial IoT services from outside of Insights Hub. To get this upgrade, your tenant admin needs to contact their assigned Account Executive or Customer Success Manager.
  • mdsp:core:TenantAdmin role

Note

Application Credentials are only required as technical users for an application. Applications can access other tenants' data using the Token Management Service, if necessary.

Application Credentials

Applications must send their app credentials to the Token Management Service in order to request a token. App credentials consist of a client ID and a client secret. They are created after uploading an application to the Developer Cockpit or Operator Cockpit and must be provided as environment variables of the application.
Access for an application must be issued manually in the "Authorization Management" in order to create app credentials. For Cloud Foundry applications, the Operator Cockpit automatically provides the app credentials as environment variables of the application.

For more information on fetching the app credentials from Operator Cockpit refer App credentials.

App credentials are version specific and must be updated, if a new version of an application is uploaded. This also means that the app credentials issued in Developer Cockpit are not valid anymore, once the application has been transferred to the operator tenant.

In order to revoke the credentials, de-register the application.

App credentials expire after a maximum of 365 days. Once the App credentials completes 365 days, rotate the application credentials. For more information refer Rotate Application credentials.

Attention

  • App credentials are created per account. If you follow the DevOps Application Lifecycle, you need one set of application credentials for your Dev account and another for your Ops account.
  • App credentials cannot be used by mobile apps. Refer How To for integrating Insights Hub applications into native mobile apps.
  • It is required to only use one set of app credentials per application instance. This ensures that only one part of your system is affected, if the credentials are compromised.

Generating a Token

This section describes how to use app credentials to generate bearer token using Token Manager Service:

POST /api/technicaltokenmanager/v3/oauth/token HTTP/1.1
Host: gateway.{region}.{mindsphere.domain}
X-SPACE-AUTH-KEY: Bearer {ApplicationCredentialID: ApplicationCredentialSecret as Base64 encoded string}
Content-Type: application/json
{
  "grant_type": "client_credentials",
  "appName": "application name",
  "appVersion": "version",
  "hostTenant": "TenantName",
  "userTenant": "Tenantname"
}

To get the token, retrieve the content of access_token from the 200 success response.

The following example shows how to request an access_token using curl and jq:

curl -X POST 'https://gateway.{region}.{mindsphere.domain}/api/technicaltokenmanager/v3/oauth/token' \
-H 'X-SPACE-AUTH-KEY: Bearer $(echo -n {AppCredentialID}:{AppCredentialSecret} | base64)' \
-H 'Content-Type: application/json' \
-d '{
      "grant_type": "client_credentials",
      "appName": "application name",
      "appVersion": "version",
      "hostTenant": "TenantName",
      "userTenant": "Tenantname"
}'

Postman Example

The below postman collection should be imported in the postman. After successful import, you can replace the values.

Postman
  {
    "info": {
      "_postman_id": "8b0ad76a-9f63-4946-9597-2443252645a0",
      "name": "Application Credential Token Generation with Example",
      "schema": "https://schema.getpostman.com/json/collection/v2.1.0/collection.json"
    },
    "item": [
      {
        "name": "Generate App Credential Bearer Token",
        "event": [
          {
            "listen": "prerequest",
            "script": {
              "id": "7ed5b9aa-8e45-4d05-b1b4-6324300e6e8a",
              "exec": [
                "var id = '{Application Credential ID}';\r",
                "var secret = '{ Application Credential Secret}';\r",
                "pm.environment.set(\"base64token\", btoa(id + ':' + secret));"
              ],
              "type": "text/javascript"
            }
          },
            {
              "listen": "test",
              "script": {
                "id": "93b90d1f-2f5e-4487-a3f8-caac49b55cec",
                "exec": [
                  "var jsonData = pm.response.json();\r",
                  "pm.globals.set(\"BearerToken\", 'Bearer ' + jsonData.access_token);"
                ],
                "type": "text/javascript"
              }
            }
        ],
          "request": {
            "method": "POST",
            "header": [
              {
                "key": "X-SPACE-AUTH-KEY",
                "value": "Bearer {{ base64token }}",
                "type": "text"
              },
              {
                "key": "Content-Type",
                "value": "application/json",
                "type": "text"
              }
            ],
            "body": {
              "mode": "raw",
              "raw": "{\r\n\t\"grant_type\": \"client_credentials\",\r\n\t\"appName\":\t\"{Application Name}\",\r\n\t\"appVersion\": \"{Application Version }\",\r\n\t\"hostTenant\": \"{Host Tenant Name}\",\r\n\t\"userTenant\": \"{User Tenant Name}\"\r\n} "
            },
            "url": {
              "raw": "https://gateway.eu1.mindsphere.io/api/technicaltokenmanager/v3/oauth/token",
              "protocol": "https",
              "host": [
                "gateway",
                "eu1",
                "mindsphere",
                "io"
              ],
              "path": [
                "api",
                "technicaltokenmanager",
                "v3",
                "oauth",
                "token"
              ]
            }
          },
          "response": []
        },
        {
          "name": "Get Tenant Users ( IAM )",
          "request": {
            "method": "GET",
            "header": [
              {
                "key": "Authorization",
                "value": "{{ BearerToken }}",
                "type": "text"
              }
            ],
            "url": {
              "raw": "https://gateway.eu1.mindsphere.io/api/im/v3/Users",
              "protocol": "https",
              "host": [
                "gateway",
                "eu1-int",
                "mindsphere",
                "io"
              ],
              "path": [
              "api",
              "im",
              "v3",
              "Users"
              ]
            },
            "description": "This API lists all the users of specific tenant"
          },
          "response": []
        }
    ],
    "protocolProfileBehavior": {}
  }

Info

The issued token is valid for 30 minutes. You have to request a new token after the 30 minutes have expired.

For more information on Token management refer Token Management service.

Calling Industrial IoT Endpoints

Create another request to an API endpoint with the following header keys:

Authorization: Bearer {token}
Content-Type: application/x-www-form-urlencoded

The following example shows how to request a list of all users of your account from the Identity Management API. Note that in this example the region is specified as eu1.

GET /api/identitymanagement/v3/Users HTTP/1.1
Host: gateway.eu1.mindsphere.io
Authorization: Bearer {token}

Info

You will only receive a success response, if you pass a valid token to Bearer {token}. In the same way you can use all MindpShere APIs.

Code Example (Python3)

We use Python3 and the requests_oauthlib to connect to the Industrial IoT IAM API.

In this example you get a token from Token Manager Service and use it to fetch all users and print those with the role. Replace the placeholders {region} and {mindsphere domain} in the code below with your region and Insights Hub domain, For example: https://gateway.eu1.mindsphere.io.

import base64
import requests

## Example URL: https://gateway.eu1.mindsphere.io
URL = "https://gateway.{{ region }}.{{ mindsphere_domain }}";
TOKEN_ENDPOINT = '/api/technicaltokenmanager/v3/oauth/token'
IAM_ENDPOINT = '/api/im/v3/Users'

#Replace values for {{ appName }}, {{ appVersion }}, {{ hostTenant }}, {{ userTenant }}
payload = """
{
      "appName": "{{ appName }}",
      "appVersion": "{{ appVersion }}",
      "hostTenant": "{{ hostTenant }}",
      "userTenant": "{{ userTenant }}"
}
"""

#Encoding of App Credentials in Base64 format and passing the Basic authentication with client_id and client_secret
#Replace values for {{ client_id }}, {{ client_secret }}

encoded = base64.b64encode(b'{{ client_id }}:{{ client_secret }}').decode()
headers = {
  'X-SPACE-AUTH-KEY': 'Basic ' + encoded,
  'Content-Type': 'application/json'
}

token_res = requests.post(url = URL+TOKEN_ENDPOINT, headers = headers, data = payload)
data = token_res.json()

#Token Generated using App Credentials
token = data['access_token']

print(data)

auth_headers = {
  'Authorization': 'Bearer ' + token,
'Content-Type': 'application/json'
}

# sending get request and saving the response as response object
iam_response = requests.get(url = URL+IAM_ENDPOINT, headers = auth_headers)

# extracting users data in json format
users = iam_response.json()

#Users List
print(users)

Accessing 3rd party APIs from application within or outside Insights Hub

In order to add the external API dependencies to your application, refer the chapter "Provisioned API dependencies for applications" in Developer Cockpit documentation. To access the external hosted API, refer Accessing Industrial IoT /Token APIs.

Info

Advanced Token Exchange (ATE) or provisioned APIs is required only when the UI and API are hosted in Insights Hub, but on different tenants. To access any application hosted on Insights Hub, the only requirement is to have any type of application credentials.


Last update: December 6, 2023

Except where otherwise noted, content on this site is licensed under the Development License Agreement.