Muokkaa

Jaa


Build API clients for a command line interface (CLI)

In this tutorial, you build a sample command line interface (CLI) app that calls a REST API that doesn't require authentication.

Required tools

A command line tool is required. We recommend:

Create a project

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

dotnet new console -o KiotaPostsCLI
cd KiotaPostsCLI
dotnet new gitignore

Project configuration

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

  • *.csproj > TargetFramework set to "net6" or later. More information
  • *.csproj > LangVersion set to "latest". More information
  • *.csproj > Nullable set to "enable".

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 and the cli-commons package. For more information about Kiota dependencies, see the dependencies documentation.

For this tutorial, use the default implementations.

Run the following commands to get the required dependencies.

dotnet add package Microsoft.Kiota.Bundle
dotnet add package Microsoft.Kiota.Cli.Commons --prerelease

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 CLI -c PostsClient -n KiotaPostsCLI.Client -d ./posts-api.yml -o ./src/Client

Tip

Add --exclude-backward-compatible if you want to reduce the size of the generated client and are not concerned about potentially source breaking changes with future versions of Kiota when updating the client.

Create the client application

The final step is to update the Program.cs file that was generated as part of the console application, replacing its contents with the following code.

using System.CommandLine.Builder;
using System.CommandLine.Parsing;
using KiotaPostsCLI.Client;
using Microsoft.Kiota.Abstractions;
using Microsoft.Kiota.Abstractions.Authentication;
using Microsoft.Kiota.Cli.Commons.Extensions;
using Microsoft.Kiota.Http.HttpClientLibrary;
using Microsoft.Kiota.Serialization.Form;
using Microsoft.Kiota.Serialization.Json;
using Microsoft.Kiota.Serialization.Text;

var rootCommand = new PostsClient().BuildRootCommand();
rootCommand.Description = "Kiota Posts CLI";

var builder = new CommandLineBuilder(rootCommand)
    .UseDefaults()
    .UseRequestAdapter(context =>
    {
        var authProvider = new AnonymousAuthenticationProvider();
        var adapter = new HttpClientRequestAdapter(authProvider);
        adapter.BaseUrl = "https://jsonplaceholder.typicode.com";

        // Register default serializers
        ApiClientBuilder.RegisterDefaultSerializer<JsonSerializationWriterFactory>();
        ApiClientBuilder.RegisterDefaultSerializer<TextSerializationWriterFactory>();
        ApiClientBuilder.RegisterDefaultSerializer<FormSerializationWriterFactory>();

        // Register default deserializers
        ApiClientBuilder.RegisterDefaultDeserializer<JsonParseNodeFactory>();
        ApiClientBuilder.RegisterDefaultDeserializer<TextParseNodeFactory>();
        ApiClientBuilder.RegisterDefaultDeserializer<FormParseNodeFactory>();

        return adapter;
    }).RegisterCommonServices();

return await builder.Build().InvokeAsync(args);

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 invoke the CLI app, run the following commands in your project directory.

GET /posts

dotnet run -- posts list

GET /posts/{id}

dotnet run -- posts get --post-id 5

POST /posts

dotnet run -- posts create --body '{ "userId": 42, "title": "Testing Kiota-generated API client", "body": "Hello world!" }'

PATCH /posts/{id}

dotnet run -- posts patch --post-id 5 --body '{ "title": "Updated title" }'

DELETE /posts/{id}

dotnet run -- posts delete --post-id 5

See also