title | description | author | ms.author | ms.topic | date |
---|---|---|---|---|---|
Build API clients for TypeScript with Microsoft identity authentication |
Learn how use Kiota to build API clients in TypeScript to access APIs that require Microsoft identity authentication. |
jasonjoh |
jasonjoh |
tutorial |
03/20/2023 |
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
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 abstraction package. Additionally, you must either use the Kiota default implementations or provide your own custom implementations of the following packages.
- Authentication (Kiota default Azure authentication)
- HTTP (Kiota default fetch-based implementation)
- Form serialization (Kiota default)
- JSON serialization (Kiota default)
- Text serialization (Kiota default)
- Multipart serialization (Kiota default)
For this tutorial, use the default implementations.
Run the following commands to get the required dependencies.
npm install @microsoft/kiota-abstractions
npm install @microsoft/kiota-authentication-azure
npm install @microsoft/kiota-http-fetchlibrary
npm install @microsoft/kiota-serialization-form
npm install @microsoft/kiota-serialization-json
npm install @microsoft/kiota-serialization-text
npm install @microsoft/kiota-serialization-multipart
npm install @azure/identity
Kiota generates API clients from OpenAPI documents. Create a file named get-me.yml and add the following.
:::code language="yaml" source="~/code-snippets/get-started/azure-auth/get-me.yml":::
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
[!INCLUDE register-azure-app-device-code-intro]
[!INCLUDE register-azure-app-device-code-portal]
[!INCLUDE register-azure-app-device-code-powershell]
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.
:::code language="typescript" source="~/code-snippets/get-started/azure-auth/typescript/index.ts" id="ProgramSnippet":::
Note
This example uses the DeviceCodeCredential class. You can use any of the credential classes from the @azure/identity
library.
To start the application, run the following command in your project directory.
npx ts-node index.ts
- kiota-samples repository contains the code from this guide.
- ToDoItem Sample API implements a sample OpenAPI in ASP.NET Core and sample clients in multiple languages.