Build API clients for .NET

In this tutorial, you will build a sample app in .NET that calls a REST API that does not require authentication.

Required tools

Create a project

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

dotnet new console -o KiotaPosts
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 "netstandard2.0" or "netstandard2.1" or "net462" or "net6" or above. More information
  • *.csproj > LangVersion set to "7.3" or above or "preview" or "latest". More information

The following configuration is recommended:

  • *.csproj > Nullable set to "enable".

Add dependencies

Before you can compile and run the generated API client, you will 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 of the following packages.

For this tutorial, you will use the default implementations.

Run the following commands to get the required dependencies.

dotnet add package Microsoft.Kiota.Abstractions
dotnet add package Microsoft.Kiota.Http.HttpClientLibrary
dotnet add package Microsoft.Kiota.Serialization.Form
dotnet add package Microsoft.Kiota.Serialization.Json
dotnet add package Microsoft.Kiota.Serialization.Text
dotnet add package 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 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 CSharp -c PostsClient -n KiotaPosts.Client -d ./posts-api.yml -o ./Client

Create the client application

The final step is to update the Program.cs file that was generated as part of the console application to include the code below.

using KiotaPosts.Client;
using KiotaPosts.Client.Models;
using Microsoft.Kiota.Abstractions.Authentication;
using Microsoft.Kiota.Http.HttpClientLibrary;

// API requires no authentication, so use the anonymous
// authentication provider
var authProvider = new AnonymousAuthenticationProvider();
// Create request adapter using the HttpClient-based implementation
var adapter = new HttpClientRequestAdapter(authProvider);
// Create the API client
var client = new PostsClient(adapter);

try
{
    // GET /posts
    var allPosts = await client.Posts.GetAsync();
    Console.WriteLine($"Retrieved {allPosts?.Count} posts.");

    // GET /posts/{id}
    var specificPostId = 5;
    var specificPost = await client.Posts[specificPostId].GetAsync();
    Console.WriteLine($"Retrieved post - ID: {specificPost?.Id}, Title: {specificPost?.Title}, Body: {specificPost?.Body}");

    // POST /posts
    var newPost = new Post
    {
        UserId = 42,
        Title = "Testing Kiota-generated API client",
        Body = "Hello world!"
    };

    var createdPost = await client.Posts.PostAsync(newPost);
    Console.WriteLine($"Created new post with ID: {createdPost?.Id}");

    // PATCH /posts/{id}
    var update = new Post
    {
        // Only update title
        Title = "Updated title"
    };

    var updatedPost = await client.Posts[specificPostId].PatchAsync(update);
    Console.WriteLine($"Updated post - ID: {updatedPost?.Id}, Title: {updatedPost?.Title}, Body: {updatedPost?.Body}");

    // DELETE /posts/{id}
    await client.Posts[specificPostId].DeleteAsync();
}
catch (Exception ex)
{
    Console.WriteLine($"ERROR: {ex.Message}");
    Console.WriteLine(ex.StackTrace);
}

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

Run the following command in your project directory to start the application.

dotnet run

See also