Skip to content

Getting started consuming APIs

This guide will help you getting started consuming APIs using the LKAB API Management platform.

API portal

We provide an API Portal to help you explore and examine in more detail the APIs published in LKAB's API Management platform.
This is the entry point when you're about to start consuming api's.
When signed-in to the API portal, for each published api, you will be able to:

  • Find contact information to request access to the given api.
  • Read detailed information about the api.
  • Download OpenAPI specifications to facilitate the setup of your API consumer
  • Review example datamodels and the schemas for the datamodels returned from api operations etc

Sign-in

To sign-in to the API Portal you need to become a member of the 'Developer@LKAB team'. This team is a general forum where we share dev related information, and is open for all of you working with LKAB projects, as a partner/consultant or employee.
Apply for membership to 'Developer @ LKAB' team here: Developer@LKAB team

When approved you sign-in using the 'Sign in using Azure AD' button.
Sign in using Azure AD

On first signin you'll have to complete your contact details.
Complete signup

Click 'Explore APIs' to browse the published api's.
Explore APIs

Try out APIs using the API portal

Each published API in LKAB's API Management has individual access control, using OAuth2, that is controlled by the respective API owner.
To be able to use the "Try it" function in the API portal, the API owner needs to provide so-called "Delegated permission" for your user account.

More info

API Access

Since we use OAuth2 to control access to the api's, your application will need an App registration to be able to request an access token for the given api.

App registration naming and separation

To ensure security, we create one App registrations for production environment access and another App registration for dev, test and stage environment access.

For api consumers (i.e. api clients) we recommend the following naming pattern:
{consuming system name}-api-client-[test | prod]

E.g. if the consuming system is named 'Boomi' the corresponding App registrations would be named:
boomi-api-client-test (will only have access to dev, test and stage environments)
boomi-api-client-prod (will only have access to production environments)

App registration creation

Visit the App registration blade in Azure (LKAB tenant) and follow the 'App registration client' guide to create your client App registration.

If there are other people that need to access this app registration. Make sure that you add them as owners.

Supported authorization flows

Client credentials flow

Add a application permission which is described below here

Implicit and Authorization Code with PKCE

Add a delegated permission. More info on how to to setup postman to use this flow here

Request access to the api

Select 'API Permissions' in the left menu pane and then select 'Add a permission'

API Permission

Select 'APIs my organization uses' and start typing the name of the api, e.g. 'ip21'

Search api

Select the api we need permission to access. Note! If your client is a '-test' client, select the '-test' api.
If our consuming client is a daemon service, i.e. using Client Credentials flow, select 'Application permissions'.

When using Client credentials flow a client secret is nedded when requesting tokens. The recommended lifetime for this secret is 6 months. After that the secret must be updated. The owners of the app registration will be notified through email when the secret is about to expire.

If the api have different permissions configured (think 'roles'), select the permission your app requires, and click 'Add permissions' button.
Request app permissions

At the time of writing, all permission of type 'Application' will need to be Granted by LKAB centrally.
Copy the url from your browser and send an email to API Management team with the url of the App registration to be granted access.

Firewall

The server hosting your API client will need access to the following:

Source Destination Protocol Port (Destination) Motivation
{your api client host} login.microsoftonline.com TCP 443 Request token for API access via LKAB API Management
{your api client host} dev.api.lomi.lkab.com TCP 443 API request LKAB API Management (DEV)
{your api client host} test.api.lomi.lkab.com TCP 443 API request LKAB API Management (TEST)
{your api client host} stage.api.lomi.lkab.com TCP 443 API request LKAB API Management (STAGE)
{your api client host} api.lomi.lkab.com TCP 443 API request LKAB API Management (PRODUCTION)

Clients on LKAB network

If you are hosting your API client on a server/container runtime within LKABs network you will have to request firewall port openings from your hosting servers to LKABs API Management gateway (in practice to the IP address of the Web Application Firewall guarding the API Management gateway).
Remember to request firewall changes for dev, test and stage as well as your production environment.

We've created a firewall change request template, to download and complete with your api client host ip-addresses (download link in the Links section).
Replace the templates {On-prem...} placeholders with your api-client host ip-addresses.

Send the completed Firewall change request to servicedesk@lkab.com

Testing with Postman

Postman is a convenient free tool to test your client access to the api. Download Postman and install on your computer.
In this example we will call the 'LKAB.SensorData.IP21.API' using Client Credentials flow.

Download API Specification

Open your browser an go to the API Portal to find the API we want to try out.
Request app permissions

  • Click the 'Explore APIs' button.

Request app permissions

  • If needed use the search bar to find the API we are about to try out, and click the API name link.

Request app permissions

  • Download the API definition by selecting the 'Open API 3 (YAML)' in the 'API definition' dropdown. Your browser will download the Open API defintion file.

Import API definition to Postman

In Postman, import the OpenAPI definition.
Request app permissions

  • Click 'Import'
  • Click 'OpenAPI' and browse to the downloaded api0022-lkab-ip21.yaml file.

Request app permissions

  • Expand the 'Show advanced settings'.

Request app permissions

  • For 'Folder organization', select 'Tags'
  • Click 'Import' button

Use Application Permissions

Configure OAuth 2.0 Client Credentials Flow Authorization

In the Postman 'Scratch Pad', select 'LKAB.SensorData.IP21.API'.
Request app permissions

Select the Authorization tab and select 'OAuth 2.0'.

Request app permissions

Ensure the following fields are set:
Request app permissions

  • Type: OAuth 2.0
  • Add auth to: Request headers
  • Header Prefix: Bearer

Before entering the 'Configure New Token' section, open a browser and open up the 'Overview' page for your client App registration: Azure AD App Registration Blade.

In the 'Configure New Token' section:
Request app permissions

  • Token Name: name your token as you find convenient
  • Grant Type: Client Credentials
  • Access Token URL: Use the v2.0 endpoint: https://login.microsoftonline.com/74c901f0-6a97-4cfa-8505-9542ce009b27/oauth2/v2.0/token
  • Client ID: Enter your App registration Client ID, in Azure AD this is always a GUID, named 'Application (client) ID' on the overview page.
  • Client secret: Enter your App registration Client secret. You create your secret, if not already created, in the 'Certificates & Secrets' section.
    • NOTE! You need to copy the secret upon creation, once created, the secret cannot be read again.
  • Scope: For Client Credentials flow the Scope is always {Target API Application ID URI}/.default. E.g. https://test.api.lkab.com/ip21/.default
    • To lookup the target api App ID URI, go to 'API Permissions'
    • Click the API you need to find scope for.
    • In the 'Request API permissions' dialog, the Appliction ID URI is below the name in the top left corner. E.g. https://test.api.lkab.com/ip21
    • Add '/.default' to the Application ID URI to construct the default scope used in Client Credentials flow. E.g. E.g. https://test.api.lkab.com/ip21/.default
  • Client Authentication: Send client credentials in the body

Note! Remember to Save your collections 'Autorization' settings by clicking the 'Save' button.

Request app permissions

Request the access token

When the above fields are completed, click the 'Get New Access Token' button.
Note! If your token request fails, expand the 'Console' at the bottom to view error messages that might give an idea about what wen't wrong.

If authentication succeeds, click the 'Proceed' button, and then click the 'Use token' button.
Note! For debugging purpose, you might need to view the content of the token. A good online tool is jwt.io. Just copy the 'Access Token' content from Postman to the 'Encoded' field, to see the decoded claims.

Request app permissions

Use the access token for API request

Select the API operation you would like to try out in Postman. We will use the operation 'GetCurrentDataPoint'.
Select the 'Authorization' tab and verify that we use 'Inherit auth from parent', meaning we will use the collections OAuth 2.0 token we configured earlier.

Request app permissions

Switch to the 'Params' tab, fill in the tag-name query-parameter with the IP21 tag to query, and the serverAlias path-parameter with the IP21 server alias where the IP21 tag is configured.

Request app permissions

Send the request by clicking the 'Send' button.

Request app permissions

Verify the Response Status code is '200 OK'.
If so, your request has succeeded and the client App registration has sufficient permissions to call the api. If you receive some error response code (i.e. other than '200 OK'), use the Postman console to review the error message.

Use Delegated Permissions

If you want to test your api with delegated permissions you can follow this guide. Note that to make this work your personal ad account must be assigned to at lest one role in the enterprise application for the api you want to access.

Unfortunately Postman is not compatible with the PKCE flow for Azure AD. Azure AD requires that a Origin header i sent during token retrieval but the Postman App doesn't enable you to add headers during the authorization flow. More info on Azure AD PKCE. The only option at the moment in Postman is to enable Implicit flow which is not recommended by security reasons.

Therefore the below screenshots and example is made with a similar tool called Insomnia

Request app permissions Add the callback for the insomnia client.

Request app permissions Add the api permissions you want for your client

Request app permissions Choose delegated permissions with the wanted api permissions.

Insomnia auth setup

Request app permissions

  1. OAuth 2.0
  2. Authorization Code
  3. https://login.microsoftonline.com/74c901f0-6a97-4cfa-8505-9542ce009b27/oauth2/authorize
  4. https://login.microsoftonline.com/74c901f0-6a97-4cfa-8505-9542ce009b27/oauth2/v2.0/token
  5. Application (client) ID of the app registration
  6. Use PKCE
  7. https://insomnia.redirecturl.local
  8. Scope, for example https://test.api.lkab.com/asyncapi/portal/api.access Request app permissions
  9. In request body

Testing with curl

You can use the command line tool curl to do simple testing of credentials or API's. Prerequisite for this example is a client app registration in Azure AD for OAuth 2 client credentials flow. The app registration will give you a client id and client secret that can be used together with the scope for the API to request for access tokens.

The example below first sets a couple of variables for better readability, you can include the values directly in the curl command if you want. The output from the token request is piped to the jq command to extract the access token, which is saved in the accessToken variable.

> clientId=AAA
> clientSecret=BBB
> scope=https://[test.]api.lkab.com/{path}/.default
> tokenUrl=https://login.microsoftonline.com/74c901f0-6a97-4cfa-8505-9542ce009b27/oauth2/v2.0/token
> contentType="Content-Type: application/x-www-form-urlencoded"
> requestBody="grant_type=client_credentials&client_id=$clientId&client_secret=$clientSecret&scope=$scope"
> accessToken=$(curl -S -X POST -H "$contentType" -d "$requestBody" "$tokenUrl" | jq -r ".access_token")

You can inspect the access token with the following command. Check for the roles claim, if it's missing something is probably wrong.

> jq -R 'split(".") | .[1] | @base64d | fromjson' <<< "$accessToken"

Using the access token, you can now query the API. This is a simple GET request:

> curl -S -X GET -H "Authorization: Bearer $accessToken" "https://[{dev|test|stage}.]api.lomi.lkab.com/{base-path}/{api-path}[?{query-parameters}]"

Code example

This example presents a really simple console application using .net/C# and the Microsoft Identity Web authentication library. Prerequisite for this example is a client app registration in Azure AD for OAuth 2 client credentials flow.

First the project file (.csproj), declaring a reference to the Microsoft.Identity.Web.DownstreamApi package.

<Project Sdk="Microsoft.NET.Sdk">

  <PropertyGroup>
    <OutputType>Exe</OutputType>
    <TargetFramework>net7.0</TargetFramework>
    <ImplicitUsings>enable</ImplicitUsings>
    <Nullable>enable</Nullable>
  </PropertyGroup>

  <ItemGroup>
    <PackageReference Include="Microsoft.Identity.Web.DownstreamApi" Version="2.12.4" />
  </ItemGroup>

  <ItemGroup>
    <None Update="appsettings.json">
      <CopyToOutputDirectory>PreserveNewest</CopyToOutputDirectory>
    </None>
  </ItemGroup>
</Project>

In the appsettings.json file you configure one section for AzureAd and one for the API to be used.

{
  "AzureAd": {
    "Instance": "https://login.microsoftonline.com/",
    "TenantId": "74c901f0-6a97-4cfa-8505-9542ce009b27",
    "ClientId": "AAA",
    "ClientCredentials": [
      {
        "SourceType": "ClientSecret",
        "ClientSecret": "BBB"
      }
    ]
  },

  "MyApi": {
    "BaseUrl": "https://[{dev|test|stage}.]api.lomi.lkab.com/{base-path}",
    "Scopes": [ "https://[test.]api.lkab.com/{path}/.default" ]
  }
}

And finally the application, here presented using the top-level statements feature (ie no Main method) available starting with C# 9, just doing a simple GET request.

using Microsoft.Extensions.DependencyInjection;
using Microsoft.Identity.Abstractions;
using Microsoft.Identity.Web;

var tokenAcquirerFactory = TokenAcquirerFactory.GetDefaultInstance();

tokenAcquirerFactory.Services
    .AddDownstreamApi("MyDownstreamApi", tokenAcquirerFactory.Configuration.GetSection("MyApi"));

var sp = tokenAcquirerFactory.Build();

var api = sp.GetRequiredService<IDownstreamApi>();

var result = await api.GetForAppAsync<object>("MyDownstreamApi",
    options =>
    {
        options.RelativePath = "{api-path}[?{query-parameters}]";
    });

Console.WriteLine(result);

The above example is more or less stolen from this GitHub repo and more documentation can be found in this How-to: Non-interactive app that calls a web API.