Last updated

API Gateway Communication

This module demonstrates how to authenticate and communicate with the JTL Cloud API Gateway.

Authentication Flow

  1. Obtain a JWT access token using OAuth2 client credentials flow
  2. Use the JWT token in subsequent API requests

getJwt()

Retrieves a JWT access token from the authentication server.

Function: getJwt()

  • Returns: Promise(string) - A promise that resolves to the JWT access token
  • Throws: Error - If the authentication request fails
  • Async: Yes

Implementation:

keep in mind this example reaches the dev environment, hence the url 'https://auth.dev.jtl-cloud.com/oauth2/token' is used.

async function getJwt(): Promise<string> {
    const clientId = 'Your Client ID';
    const clientSecret = 'your Secret';

    const authString = Buffer.from(`${clientId}:${clientSecret}`).toString('base64');

    const response = await fetch('https://auth.dev.jtl-cloud.com/oauth2/token', {
        method: 'POST',
        headers: {
            'Content-Type': 'application/x-www-form-urlencoded',
            Authorization: `Basic ${authString}`,
        },
        body: new URLSearchParams({
            grant_type: 'client_credentials',
        }),
    });
    const data = await response.json();

    if (response.ok) {
        return data.access_token;
    } else {
        throw new Error(`Failed to fetch JWT (${response.status}): ${data.error}`);
    }
}

API Request Pattern

After obtaining the JWT, requests to the API gateway should:

  • Include the JWT token in the Authorization header as a Bearer token
  • Specify the tenant ID in the X-Tenant-ID header
  • Handle any errors appropriately

Example

Again this example reaches the dev environment, hence the url 'https://api.dev.jtl-cloud.com/erp/info' is used.

// 1. Get the JWT token
const jwt = await getJwt();

// 2. Make an authenticated API request
const response = await fetch('https://api.dev.jtl-cloud.com/erp/info', {
        headers: {
                'X-Tenant-ID': tenantId,
                'Authorization': `Bearer ${jwt}`
        }
});