Skip to content

Latest commit

 

History

History
340 lines (233 loc) · 9.53 KB

File metadata and controls

340 lines (233 loc) · 9.53 KB

Getting Started with iTwins Client

This guide will help you get up and running with the iTwins Client library, from installation through your first API calls.

Table of Contents

Prerequisites

Before getting started, ensure you have:

  • Node.js 18+ and a package manager (npm, yarn, or pnpm)
  • TypeScript 4.5+ (if using TypeScript)
  • Valid iTwin Platform credentials - see iTwin Developer Portal

Installation

Install the iTwins Client:

# Using npm
npm install @itwin/itwins-client

# Using yarn
yarn add @itwin/itwins-client

# Using pnpm
pnpm add @itwin/itwins-client

Authentication Setup

The iTwins Client requires an access token string. You'll need to set up authentication with the iTwin Platform:

  1. Register your application at the iTwin Developer Portal
  2. Get your client credentials (client ID, client secret, redirect URIs)
  3. Implement authentication flow using one of the iTwin.js authentication packages

Basic Authentication Example

import { TestUtility } from "@itwin/oidc-signin-tool";

// For testing/development - use appropriate auth for production
const userCredentials = {
  email: "your-test-email@example.com",
  password: "your-password",
};

const accessToken: string = await TestUtility.getAccessToken(userCredentials);

Your First iTwin Query

Once you have authentication set up, making your first API call is straightforward:

import { ITwinsClient } from "@itwin/itwins-client";
import type { BentleyAPIResponse, MultiITwinMinimalResponse } from "@itwin/itwins-client";

async function getMyITwins(): Promise<void> {
  // Initialize the client
  const client = new ITwinsClient();

  // Get your access token (implementation depends on your auth setup)
  const accessToken: string = await getAccessToken(); // Your auth implementation

  // Make your first API call
  const response: BentleyAPIResponse<MultiITwinMinimalResponse> =
    await client.getITwins(accessToken, {
      subClass: "Project",
      top: 10
    });

  // Check for errors
  if (response.error) {
    console.error("API Error:", response.error.message);
    return;
  }

  // Success! Use the data
  const iTwins = response.data!.iTwins;
  console.log(`Found ${iTwins.length} iTwins:`);

  iTwins.forEach(itwin => {
    console.log(`- ${itwin.displayName} (${itwin.id})`);
  });
}

// Run your first query
getMyITwins().catch(console.error);

Environment Configuration

The iTwins Client supports different deployment environments (development, QA, production):

Using Global Configuration

// Development environment
globalThis.IMJS_URL_PREFIX = "dev-";

// QA environment
globalThis.IMJS_URL_PREFIX = "qa-";

// Production (default)
globalThis.IMJS_URL_PREFIX = undefined;

// Now all client instances will use the configured environment
const client = new ITwinsClient();

Using Custom URLs

// Custom base URL for specific deployments
const client = new ITwinsClient("https://your-custom-api.bentley.com/itwins");

Environment Variables (Node.js)

// Bridge from process.env in Node.js applications
globalThis.IMJS_URL_PREFIX = process.env.IMJS_URL_PREFIX;

Redirect Configuration

The iTwins Client supports configurable redirect limits for federated architecture scenarios where API endpoints may redirect to different services:

// Set maximum redirect limit (default is 5)
globalThis.IMJS_MAX_REDIRECTS = 10;

// Or use environment variable
globalThis.IMJS_MAX_REDIRECTS = parseInt(process.env.IMJS_MAX_REDIRECTS || "5");

// Create client with custom max redirects via constructor
const client = new ITwinsClient(10);

Why Redirects? In federated architecture, the iTwin Platform may redirect requests to specialized services (e.g., repository services on different domains). The client automatically follows these redirects while enforcing security validation.

Security Notes:

  • Only HTTPS redirects to trusted Bentley domains (*.api.bentley.com) are allowed
  • Redirect loop protection prevents infinite redirect chains
  • Default limit of 5 redirects is suitable for most scenarios
  • Increase only if you encounter legitimate multi-hop redirect scenarios

Error Handling:

  • 508 Loop Detected: Redirect limit exceeded, possible redirect loop
  • 502 Bad Gateway: Invalid redirect (missing Location header or untrusted domain)
  • 403 Forbidden: Redirects not allowed for this endpoint
const response = await client.getRepositoryResourceByUri(accessToken, iTwinId, resourceUri);

if (response.error) {
  if (response.status === 508) {
    console.error("Too many redirects - possible redirect loop");
  } else if (response.status === 502) {
    console.error("Invalid redirect:", response.error.message);
  }
}

Development Setup

If you're contributing to the iTwins Client or building from source:

Clone and Build

git clone https://github.com/iTwin/itwins-client.git
cd itwins-client
pnpm install
pnpm build

Development Commands

# Build the library
pnpm build

# Run tests
pnpm test

# Run tests with coverage
pnpm test:coverage

# Run linting
pnpm lint

# Build API documentation
pnpm docs

# Clean build artifacts
pnpm clean

Testing Setup

For integration testing, you'll need to configure test credentials and environments.

Environment File Setup For Bentley Developers

az login  # Authenticate with Azure CLI

./setup-env.ps1 # Set up .env file with required variables

Environment File Setup For Non-Bentley Developers

Create a .env file in the root directory with the following variables:

# Environment Configuration
IMJS_URL_PREFIX=""                    # Environment must be empty

# OIDC Configuration (required for authentication)
IMJS_OIDC_BROWSER_TEST_CLIENT_ID="spa-your-client-id-here"
IMJS_OIDC_BROWSER_TEST_REDIRECT_URI="http://localhost:3000/signin-callback"
IMJS_OIDC_BROWSER_TEST_SCOPES="itwin-platform"
IMJS_OIDC_AUTHING_BROWSER_TEST_SCOPES="itwin-platform"

# Test User Authentication (for testing only)
IMJS_ITWIN_TEST_USER="your-test-email@example.com"
IMJS_ITWIN_TEST_USER_PASSWORD="your-test-password"

# Test Data (required for integration tests)
IMJS_TEST_PROJECT_ID="your-test-project-itwin-id"
IMJS_TEST_ASSET_ID="your-test-asset-itwin-id"

Test User Requirements

Your test user must have appropriate permissions:

  • Project Administrator or ITwin Owner role on test iTwins
  • Connect Services Admin role for creating iTwins (if testing CRUD operations)
  • Access to both Project and Asset level iTwins for comprehensive testing

Running Tests

# Install dependencies
pnpm install

# Build the project
pnpm build

# Run integration tests
pnpm test

Browser E2E Tests (Playwright)

The browser E2E tests validate redirect behavior using real browser fetch implementations (Chromium, Firefox, WebKit).

# Run browser E2E tests
pnpm test:e2e

# Run with Playwright UI
pnpm test:e2e:ui

For more details about testing, see the test documentation and existing test files in src/test/integration/.

Next Steps

Now that you have the basics working, explore these areas:

Documentation

Additional Resources


Troubleshooting

Common Issues

Authentication Errors (401)

  • Verify your access token is valid and not expired
  • Check that your application has the correct scopes
  • Ensure you're using the right environment (dev/qa/prod)

Not Found Errors (404)

  • Verify iTwin IDs are correct and accessible to your user
  • Check that you have permissions to access the requested resources
  • Ensure you're targeting the correct environment

Validation Errors (422)

  • Review the error.details array for specific validation failures
  • Check required fields and data types in your requests
  • Verify enum values match the expected API constants

Network/Timeout Issues

  • Check your internet connection and firewall settings
  • Verify the API endpoint URLs are accessible
  • Consider implementing retry logic for transient failures

Getting Help


Ready to build amazing iTwin applications? Start with the examples