Build API clients for TypeScript

In this tutorial, you build a sample app in TypeScript that calls a REST API that doesn't require 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

Project configuration

In case you're adding a Kiota client to an existing project, the following configuration is required:

  • tsconfig > compilerOptions > esModuleInterop set to "true".
  • tsconfig > compilerOptions > forceConsistentCasingInFileNames set to "true".
  • tsconfig > compilerOptions > lib with an entry of "es2015".
  • tsconfig > compilerOptions > module set to "NodeNext".
  • tsconfig > compilerOptions > moduleResolution set to "NodeNext".
  • tsconfig > compilerOptions > target set to "es2016" or later.

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 abstraction package. Additionally, you must either use the Kiota default implementations or provide your own custom implementations of the following packages.

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-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

Generate the API client

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

openapi: '3.0.2'
info:
  title: JSONPlaceholder
  version: '1.0'
servers:
  - url: https://jsonplaceholder.typicode.com/

components:
  schemas:
    post:
      type: object
      properties:
        userId:
          type: integer
        id:
          type: integer
        title:
          type: string
        body:
          type: string
  parameters:
    post-id:
      name: post-id
      in: path
      description: 'key: id of post'
      required: true
      style: simple
      schema:
        type: integer

paths:
  /posts:
    get:
      description: Get posts
      parameters:
      - name: userId
        in: query
        description: Filter results by user ID
        required: false
        style: form
        schema:
          type: integer
          maxItems: 1
      - name: title
        in: query
        description: Filter results by title
        required: false
        style: form
        schema:
          type: string
          maxItems: 1
      responses:
        '200':
          description: OK
          content:
            application/json:
              schema:
                type: array
                items:
                  $ref: '#/components/schemas/post'
    post:
      description: 'Create post'
      requestBody:
        required: true
        content:
          application/json:
            schema:
              $ref: '#/components/schemas/post'
      responses:
        '201':
          description: Created
          content:
            application/json:
              schema:
                $ref: '#/components/schemas/post'
  /posts/{post-id}:
    get:
      description: 'Get post by ID'
      parameters:
      - $ref: '#/components/parameters/post-id'
      responses:
        '200':
          description: OK
          content:
            application/json:
              schema:
                $ref: '#/components/schemas/post'
    patch:
      description: 'Update post'
      requestBody:
        required: true
        content:
          application/json:
            schema:
              $ref: '#/components/schemas/post'
      parameters:
      - $ref: '#/components/parameters/post-id'
      responses:
        '200':
          description: OK
          content:
            application/json:
              schema:
                $ref: '#/components/schemas/post'
    delete:
      description: 'Delete post'
      parameters:
      - $ref: '#/components/parameters/post-id'
      responses:
        '200':
          description: OK

This file is a minimal OpenAPI description that describes how to call the /posts endpoint in the JSONPlaceholder REST API.

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

kiota generate -l typescript -d posts-api.yml -c PostsClient -o ./client

Create the client application

Create a file in the root of the project named index.ts and add the following code.

import { AnonymousAuthenticationProvider } from '@microsoft/kiota-abstractions';
import { FetchRequestAdapter } from '@microsoft/kiota-http-fetchlibrary';
import { createPostsClient } from './client/postsClient';
import { Post } from './client/models';

// API requires no authentication, so use the anonymous
// authentication provider
const authProvider = new AnonymousAuthenticationProvider();
// Create request adapter using the fetch-based implementation
const adapter = new FetchRequestAdapter(authProvider);
// Create the API client
const client =createPostsClient(adapter);

async function main(): Promise<void> {
  try {
    // GET /posts
    const allPosts = await client.posts.get();
    console.log(`Retrieved ${allPosts?.length} posts.`);

    // GET /posts/{id}
    const specificPostId = 5;
    const specificPost = await client.posts.byPostId(specificPostId).get();
    console.log(`Retrieved post - ID: ${specificPost?.id}, Title: ${specificPost?.title}, Body: ${specificPost?.body}`);

    // POST /posts
    const newPost: Post = {
      userId: 42,
      title: 'Testing Kiota-generated API client',
      body: 'Hello world!',
    };

    const createdPost = await client.posts.post(newPost);
    console.log(`Created new post with ID: ${createdPost?.id}`);

    // PATCH /posts/{id}
    const update: Post = {
      // Only update title
      title: 'Updated title',
    };

    const updatedPost = await client.posts.byPostId(specificPostId).patch(update);
    console.log(`Updated post - ID: ${updatedPost?.id}, Title: ${updatedPost?.title}, Body: ${updatedPost?.body}`);

    // DELETE /posts/{id}
    await client.posts.byPostId(specificPostId).delete();
  } catch (err) {
    console.log(err);
  }
}

main();

Note

The JSONPlaceholder REST API doesn't require any authentication, so this sample uses the AnonymousAuthenticationProvider. For APIs that require authentication, use an applicable authentication provider.

Run the application

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

npx ts-node index.ts

See also