Build API clients for TypeScript with Microsoft identity authentication

Required tools

Create a project

Run the following commands in the directory where you want to create a new project.

npm init
npm install -D typescript ts-node
npx tsc --init

Add dependencies

Before you can compile and run the generated API client, you need to make sure the generated source files are part of a project with the required dependencies. Your project must have a reference to the bundle package. For more information about kiota dependencies, refer to the dependencies documentation.

Run the following commands to get the required dependencies.

npm install @microsoft/kiota-bundle
npm install @microsoft/kiota-authentication-azure
npm install @azure/identity

Generate the API client

Kiota generates API clients from OpenAPI documents. Create a file named get-me.yml and add the following.

openapi: 3.0.3
info:
  title: Microsoft Graph get user API
  version: 1.0.0
servers:
  - url: https://graph.microsoft.com/v1.0/
paths:
  /me:
    get:
      responses:
        200:
          description: Success!
          content:
            application/json:
              schema:
                $ref: "#/components/schemas/microsoft.graph.user"
components:
  schemas:
    microsoft.graph.user:
      type: object
      properties:
        id:
          type: string
        displayName:
          type: string

You can then use the Kiota command line tool to generate the API client classes.

kiota generate -l typescript -d get-me.yml -c GetUserApiClient -o ./client

Register an application

To be able to authenticate with the Microsoft identity platform and get an access token for Microsoft Graph, you need to create an application registration. You can install the Microsoft Graph PowerShell SDK and use it to create the app registration, or register the app manually in the Azure Active Directory admin center.

The following instructions register an app and enable device code flow for authentication.

  1. Open a browser and navigate to the Azure Active Directory admin center. Sign in with your Azure account.

  2. Select Azure Active Directory in the left-hand navigation, then select App registrations under Manage.

  3. Select New registration. On the Register an application page, set the values as follows.

    • Set Name to Kiota Test Client.
    • Set Supported account types to Accounts in any organizational directory and personal Microsoft accounts.
    • Leave Redirect URI blank.
  4. Select Register. On the Overview page, copy the value of the Application (client) ID and save it.

  5. Select Authentication under Manage.

  6. Locate the Advanced settings section. Set the Allow public client flows toggle to Yes, then select Save.

Create the client application

Create a file in the root of the project named index.ts and add the following code. Replace YOUR_CLIENT_ID with the client ID from your app registration.

import { DeviceCodeCredential } from '@azure/identity';
import { AzureIdentityAuthenticationProvider } from '@microsoft/kiota-authentication-azure';
import { FetchRequestAdapter } from '@microsoft/kiota-http-fetchlibrary';
import { createGetUserApiClient } from './client/getUserApiClient';

const clientId = 'YOUR_CLIENT_ID';

// The auth provider will only authorize requests to
// the allowed hosts, in this case Microsoft Graph
const allowedHosts = new Set<string>([ 'graph.microsoft.com' ]);
const graphScopes = [ 'User.Read' ];

const credential = new DeviceCodeCredential({
  clientId: clientId,
  userPromptCallback: (deviceCodeInfo) => {
    console.log(deviceCodeInfo.message);
  }
});

const authProvider =
  new AzureIdentityAuthenticationProvider(credential, graphScopes, undefined, allowedHosts);
const adapter = new FetchRequestAdapter(authProvider);

const client = createGetUserApiClient(adapter);

async function GetUser(): Promise<void> {
  try {
    const me = await client.me.get();
    console.log(`Hello ${me?.displayName}, your ID is ${me?.id}`);
  } catch (err) {
    console.log(err);
  }
}

GetUser();

Note

This example uses the DeviceCodeCredential class. You can use any of the credential classes from the @azure/identity library.

Run the application

To start the application, run the following command in your project directory.

npx ts-node index.ts

See also