0% found this document useful (0 votes)
605 views191 pages

Openapi Kiota

Uploaded by

Ana Grossmuller
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
605 views191 pages

Openapi Kiota

Uploaded by

Ana Grossmuller
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 191

Tell us about your PDF experience.

Kiota documentation
Use Kiota to generate API clients to call any OpenAPI-described API.

About Kiota

e OVERVIEW

What is Kiota?

Use Kiota

p CONCEPT

Kiota design

API client experience

Authentication

Middleware handlers

Get started

b GET STARTED

Install Kiota

f QUICKSTART

Build API clients for .NET

Build API clients for CLI

Build API clients for Go

Build API clients for Java

Build API clients for PHP

Build API clients for Python

Build API clients for TypeScript


Microsoft identity authentication

g TUTORIAL

.NET tutorial

CLI tutorial

Go tutorial

Java tutorial

PHP tutorial

Python tutorial

Ruby tutorial

TypeScript tutorial

Extending Kiota libraries

e OVERVIEW

Abstractions

e OVERVIEW

Authentication

Serialization
Welcome to Kiota
Article • 09/16/2024

Kiota is a command line tool for generating an API client to call any OpenAPI-described
API you're interested in. The goal is to eliminate the need to take a dependency on a
different API client library for every API that you need to call. Kiota API clients provide a
strongly typed experience with all the features you expect from a high quality API SDK,
but without having to learn a new library for every HTTP API.

Get started with Kiota

Features
Provides support for a wide range of languages: C#, CLI, Go, Java, PHP, Python,
Ruby, and TypeScript
Uses the full capabilities of OpenAPI descriptions
Enables low effort implementation of new language support
Generates only the source code necessary by building on a core library
Minimizes external dependencies
Uses JSON Schema descriptions to generate primitive based model
serialization/deserialization code
Enables generation of code for only a specified subset of an OpenAPI description
Generates code that enables IDE autocomplete to aid in API resource discovery
Enables full access to HTTP capabilities

Next steps
To discover more about the developer experience that Kiota API clients provide,
see Kiota API client experience.
For details about how to use Kiota to generate API clients, see Using the Kiota tool.
To gain a better understanding of how Kiota works and how to extend it for other
languages, see Kiota design overview.
Install Kiota
Article • 05/24/2024

Kiota can be accessed in the following ways.

Download binaries
Run in Docker
Install as .NET tool
Build from source
Install the Visual Studio Code extension (preview)
Run in GitHub Actions (preview)
Install with asdf (UNOFFICIAL)
Install with Homebrew (UNOFFICIAL)
REST API Client Code Generator extension for Visual Studio (UNOFFICIAL)

Download binaries
You can download the latest version for your operating system.

ノ Expand table

Operating system Download

Linux (x64) linux-x64.zip

macOS (arm64) osx-arm64.zip

macOS (x64) osx-x64.zip

Windows (x64) win-x64.zip

Windows (x86) win-x86.zip

All releases

Run in Docker
You can run Kiota in our Docker container with one of the following commands.

bash

Bash
docker run -v /some/output/path:/app/output \
-v /some/input/description.yml:/app/openapi.yaml \
mcr.microsoft.com/openapi/kiota generate --language csharp -n namespace-
prefix

 Tip

You can alternatively use the --openapi parameter with a URI instead of volume
mapping.

To generate a client library from an online OpenAPI description and into the current
directory:

bash

Bash

docker run -v ${PWD}:/app/output mcr.microsoft.com/openapi/kiota \


generate --language typescript -n gfx -d \
https://raw.githubusercontent.com/microsoftgraph/msgraph-sdk-
powershell/dev/openApiDocs/v1.0/Mail.yml

Install as .NET tool


If you have the .NET SDK installed, you can install Kiota as a .NET tool.

To install the tool, execute the following command.

Bash

dotnet tool install --global Microsoft.OpenApi.Kiota

Build from source


1. Clone the Kiota repository .

2. Install the .NET SDK 8.0 .

3. Open the solution with Visual Studio and right select publish or execute the
following command:
Bash

dotnet publish ./src/kiota/kiota.csproj -c Release -


p:PublishSingleFile=true -r <runtime-identifiers>

ノ Expand table

Runtime identifier Value

Linux (x64) linux-x64

macOS (arm64) osx-arm64

macOS (x64) osx-x64

Windows (x64) win-x64

Windows (x86) win-x86

7 Note

Refer to .NET runtime identifier catalog so select the appropriate runtime for
your platform.

For example, the following command builds for Windows (x64).

Bash

dotnet publish ./src/kiota/kiota.csproj -c Release -


p:PublishSingleFile=true -r win-x64

4. Navigate to the output directory (usually under src/kiota/bin/Release/net7.0 ).

5. Run kiota.exe ... .

Install the Visual Studio Code extension


1. Open the Marketplace page of the extension
2. Select on the Install button.

7 Note
The Kiota Visual Studio Code extension is currently in public preview and is subject
to change.

Run in GitHub actions


You can use the setup Kiota GitHub Action in your workflow to automate client refresh
and more by adding a reference to it in your workflow definition and using the CLI just
like you would locally.

YAML

steps:
- uses: actions/checkout@v3

- uses: microsoft/[email protected]

- name: Update kiota clients in the repository


run: kiota update -o . # for a complete documentation of the CLI
commands see https://aka.ms/kiota/docs
working-directory: src # assumes client is under the src path in your
repository

7 Note

The setup Kiota GitHub Action in public preview and is subject to change.

Install with asdf

) Important

The asdf Kiota plugin is maintained and distributed by the community and is not an
official Microsoft plugin. Microsoft makes no warranties, express or implied, with
respect to the plugin or its use. Use of this plugin is at your own risk. Microsoft shall
not be liable for any damages arising out of or in connection with the use of this
plugin.

The community made Kiota available as an asdf plugin . To install the asdf-kiota
plugin, follow these instructions:

Bash
asdf plugin add kiota
# or
asdf plugin add kiota https://github.com/asdf-community/asdf-kiota.git

# Show all installable versions


asdf list-all kiota

# Install specific version


asdf install kiota latest

# Set a version globally (on your ~/.tool-versions file)


asdf global kiota latest

# Now kiota commands are available


kiota --version

Install with Homebrew

) Important

The Homebrew formula for Kiota is maintained and distributed by the community
and is not an official Microsoft plugin. Microsoft makes no warranties, express or
implied, with respect to the plugin or its use. Use of this plugin is at your own risk.
Microsoft shall not be liable for any damages arising out of or in connection with
the use of this plugin.

The community made Kiota available as a Homebrew formula for macOS running on
x64 and arm64 architectures. To install, follow these instructions:

Bash

brew install kiota

REST API Client Code Generator

) Important

The REST API Client Code Generator extension for Visual Studio is maintained and
distributed by the community and is not an official Microsoft Visual Studio
extension. Microsoft makes no warranties, express or implied, with respect to the
extension or its use. Use of this extension is at your own risk. Microsoft shall not be
liable for any damages arising out of or in connection with the use of this
extension.

REST API Client Code Generator is a collection of Visual Studio C# custom tool code
generators for OpenAPI specifications. This extension installs Kiota on-demand and adds
the required NuGet packages to build the generated code to the project. The generated
code is created as a "code-behind" file to the OpenAPI specifications file in the .NET
project. This extension offers same-day releases for new Kiota versions, but this requires
updating the extension, which can be configured to be automatically.

Installation
1. From Visual Studio (Windows), using the Manage Extensions dialog box (Tools ->
Manage Extensions), search for extension called REST API Client Code Generator.
This extension is available for Visual Studio 2022 for AMD64 and ARM64 and
Visual Studio 2019

7 Note

For Visual Studio for Mac, follow these instructions

2. Select on the Download button. To complete the installation, restart Visual Studio.

3. Follow these instructions for generating code.

Next steps
For details on running Kiota, see Using the Kiota tool.
Using the Kiota tool
Article • 10/01/2024

7 Note

For information on installing Kiota, see Get started with Kiota.

Configuration environment variables


The following table provides the list of environment variables that can be used to
configure the experience for the Kiota CLI.

ノ Expand table

Environment variable name Description Default


value

KIOTA_CONSOLE_COLORS_ENABLED Enable/disable output colorization true

KIOTA_CONSOLE_COLORS_SWAP Enable/disable inverting the color scheme of the false


output

KIOTA_TUTORIAL_ENABLED Enable/disable displaying extra hints after true


commands execution

KIOTA_OFFLINE_ENABLED Enable/disable checking for updates before false


commands execution

Commands
Kiota offers the following commands to help you build your API client:

search: search for APIs and their description from various registries.
download: download an API description.
show: show the API paths tree for an API description.
generate: generate a client for any API from its description.
update: update existing clients from previous generations.
info: show languages and runtime dependencies information.
login: signs in to private API descriptions repositories.
logout: signs out from private API description repositories.
Description search
Kiota search accepts the following parameters while searching for APIs and their
descriptions.

Bash

kiota search <searchTerm>


[(--clear-cache | --cc)]
[(--log-level | --ll) <level>]
[(--version | -v) <version>]

7 Note

The search command requires access to internet and cannot be used offline.

Mandatory arguments

Search term
The term to use during the search for APIs and their descriptions.

If multiple results are found, Kiota presents a table with the different results.

The following example returns multiple results.

Bash

kiota search github

This command returns the following display.

Bash

Key Title Description


Versions
apisguru::github.com GitHub v3 REST API GitHub's v3 REST API.
1.1.4
apisguru::github.com:api.github.com GitHub v3 REST API GitHub's v3 REST API.
1.1.4
apisguru::github.com:ghes-2.18 GitHub v3 REST API GitHub's v3 REST API.
1.1.4
apisguru::github.com:ghes-2.19 GitHub v3 REST API GitHub's v3 REST API.
1.1.4
apisguru::github.com:ghes-2.20 GitHub v3 REST API GitHub's v3 REST API.
1.1.4
apisguru::github.com:ghes-2.21 GitHub v3 REST API GitHub's v3 REST API.
1.1.4
apisguru::github.com:ghes-2.22 GitHub v3 REST API GitHub's v3 REST API.
1.1.4
apisguru::github.com:ghes-3.0 GitHub v3 REST API GitHub's v3 REST API.
1.1.4
apisguru::github.com:ghes-3.1 GitHub v3 REST API GitHub's v3 REST API.
1.1.4

If the search term is an exact match with one of the results' key, the search command
displays a detailed view of the result.

Bash

kiota search apisguru::github.com

Bash

Key: apisguru::github.com
Title: GitHub v3 REST API
Description: GitHub's v3 REST API.
Service: https://support.github.com/contact
OpenAPI: https://raw.githubusercontent.com/github/rest-api-
description/main/descriptions/api.github.com/api.github.com.json

Optional parameters
The search command accepts optional parameters commonly available on the other
commands:

--clear-cache
--log-level
--version

Description download
Kiota download downloads API descriptions to a local from a registry and accepts the
following parameters.

It isn't mandatory to download the description locally for generation as the generation
command can download the description directly. However, having a local copy of the
description can be helpful to inspect it, determine which API paths are needed, and come
up with the filters for generation.
7 Note

The download command requires access to internet and cannot be used offline.

Bash

kiota download <searchTerm>


[--clear-cache | --cc]
[--clean-output | --co]
[(--log-level | --ll) <level>]
[(--version | -v) <version>]
[(--output | -o) <path>]
[--disable-ssl-validation | --dsv]

Mandatory arguments

Search term
The search term to use to locate the description. The description is downloaded only if an
exact key match occurs. You can use the search command to find the key of the API
description before downloading it.

Bash

kiota download apisguru::github.com

Optional parameters
The download command accepts optional parameters commonly available on the other
commands:

--clean-output
--clear-cache
--log-level
--output
--version
--disable-ssl-validation

Description show
Kiota show accepts the following parameters when displaying the API paths tree for a
description.
Bash

kiota show [(--openapi | -d) <path>]


[(--log-level | --ll) <level>]
[--clear-cache | --cc]
[(--version | -v) <version>]
[(--search-key | -k) <searchKey>]
[(--max-depth | --m-d) <maximumDepth>]
[(--include-path | -i) <glob pattern>]
[(--exclude-path | -e) <glob pattern>]
[--disable-ssl-validation | --dsv]

Example
The following command with the provided options displays the following result.

Bash

kiota show -d https://raw.githubusercontent.com/microsoftgraph/msgraph-sdk-


powershell/dev/openApiDocs/v1.0/Mail.yml -i **/messages

Bash

/
└─users
└─{user-id}
├─mailFolders
│ └─{mailFolder-id}
│ ├─childFolders
│ └─messages
└─messages

Optional Parameters
The show command accepts optional parameters commonly available on the other
commands:

--openapi
--clear-cache
--log-level
--include-path
--exclude-path
--version
--search-key
--disable-ssl-validation
Client generation
Kiota generate accepts the following parameters during the generation.

Bash

kiota generate (--openapi | -d) <path>


(--language | -l) <language>
[(--output | -o) <path>]
[(--class-name | -c) <name>]
[(--namespace-name | -n) <name>]
[(--log-level | --ll) <level>]
[--backing-store | -b]
[--exclude-backward-compatible | --ebc]
[--additional-data | --ad]
[(--serializer | -s) <classes>]
[(--deserializer | --ds) <classes>]
[--clean-output | --co]
[--clear-cache | --cc]
[(--structured-mime-types | -m) <mime-types>]
[(--include-path | -i) <glob pattern>]
[(--exclude-path | -e) <glob pattern>]
[(--disable-validation-rules | --dvr) <rule name>]
[--disable-ssl-validation | --dsv]
[(--type-access-modifier | --tam) <access modifier>]

7 Note

The output directory will also contain a kiota-lock.json lock file in addition to client
sources. This file contains all the generation parameters for future reference as well as
a hash from the description. On subsequent generations, including updates, the
generation will be skipped if the description and the parameters have not changed
and if clean-output is false. The lock file is meant to be committed to the source
control with the generated sources.

Mandatory parameters
openapi
language

Optional parameters
The generate command accepts optional parameters commonly available on the other
commands:

--clear-cache
--clean-output
--include-path
--exclude-path
--log-level
--output
--disable-ssl-validation

--backing-store (-b)

Enables backing store for models. Defaults to false .

Bash

kiota generate --backing-store

--exclude-backward-compatible (--ebc)

Whether to exclude the code generated only for backward compatibility reasons or not.
Defaults to false .

To maintain compatibility with applications that depends on generated clients, Kiota emits
extra code marked as obsolete. New clients don't need this extra backward compatible
code. The code marked as obsolete will be removed in the next major version of Kiota. Use
this option to omit emitting the backward compatible code when generating a new client,
or when the application using the existing client being refreshed doesn't depend on
backward compatible code.

Bash

kiota generate --exclude-backward-compatible

--additional-data (--ad)

Include the 'AdditionalData' property for generated models. Defaults to true .

Bash

kiota generate --additional-data false

--class-name (-c)
The class name to use for the core client class. Defaults to ApiClient .

Accepted values

The provided name MUST be a valid class name for the target language.

Bash

kiota generate --class-name MyApiClient

--deserializer (--ds)

The fully qualified class names for deserializers.

These values are used in the client class to initialize the deserialization providers.

Since version 1.11 this parameter also supports a none key to generate a client with no
deserialization providers in order to enable better portability.

Defaults to the following values.

ノ Expand table

Language Default deserializers

C# Microsoft.Kiota.Serialization.Json.JsonParseNodeFactory ,
Microsoft.Kiota.Serialization.Json.JsonParseNodeFactory ,
Microsoft.Kiota.Serialization.Text.TextParseNodeFactory

Go github.com/microsoft/kiota-serialization-form-go/FormParseNodeFactory ,
github.com/microsoft/kiota-serialization-json-go/JsonParseNodeFactory ,
github.com/microsoft/kiota-serialization-text-go/TextParseNodeFactory

Java com.microsoft.kiota.serialization.TextParseNodeFactory ,
com.microsoft.kiota.serialization.JsonParseNodeFactory ,
com.microsoft.kiota.serialization.TextParseNodeFactory

PHP Microsoft\Kiota\Serialization\Json\JsonParseNodeFactory ,
Microsoft\Kiota\Serialization\Text\TextParseNodeFactory

Python kiota_serialization_json.json_parse_node_factory.JsonParseNodeFactory ,
kiota_serialization_text.text_parse_node_factory.TextParseNodeFactory

Ruby microsoft_kiota_serialization/json_parse_node_factory

TypeScript @microsoft/kiota-serialization-form.FormParseNodeFactory , @microsoft/kiota-


serialization-json.JsonParseNodeFactory , @microsoft/kiota-serialization-
Language Default deserializers

text.TextParseNodeFactory

Accepted values

One or more module names that implement IParseNodeFactory .

Bash

kiota generate --deserializer Contoso.Json.CustomDeserializer

--disable-validation-rules (--dvr)

The name of the OpenAPI description validation rule to disable. Or all to disable all
validation rules including the rules defined in OpenAPI.net.

Kiota runs a set of validation rules before generating the client to ensure the description
contains accurate information to build great client experience.

Accepted values

Rules:

DivergentResponseSchema: returns a warning if an operation defines multiple


different successful response schemas. (200, 201, 202, 203)
GetWithBody: returns a warning if a GET request has a body defined.
InconsistentTypeFormat: returns a warning if an inconsistent type/format pair is
defined. (for example, type: string, format: int32)
KnownAndNotSupportedFormats: returns a warning if a known format isn't
supported for generation. (for example, email, uri, ...)
MissingDiscriminator: returns a warning if an anyOf or oneOf schema is used without
a discriminator property name.
MultipleServerEntries: returns a warning if multiple servers are defined.
NoContentWithBody: returns a warning if a response schema is defined for a 204
response.
NoServerEntry: returns a warning if no servers are defined.
UrlFormEncodedComplex: returns a warning if a URI form encoded response has a
schema that contains complex properties.

Bash
kiota generate --disable-validation-rules NoServerEntry

--namespace-name (-n)

The namespace to use for the core client class specified with the --class-name option.
Defaults to ApiSdk .

Accepted values

The provided name MUST be a valid module or namespace name for the target language.

Bash

kiota generate --namespace-name MyAppNamespace.Clients

Accepted values

A valid URI to an OpenAPI description in the local filesystem or hosted on an HTTPS server.

Bash

kiota generate --openapi https://contoso.com/api/openapi.yml

--serializer (-s)

The fully qualified class names for serializers.

These values are used in the client class to initialize the serialization providers.

Since version 1.11 this parameter also supports a none key to generate a client with no
serialization providers in order to enable better portability.

Defaults to the following values.

ノ Expand table

Language Default deserializer

C# Microsoft.Kiota.Serialization.Form.FormSerializationWriterFactory ,
Microsoft.Kiota.Serialization.Json.JsonSerializationWriterFactory ,
Microsoft.Kiota.Serialization.Text.TextSerializationWriterFactory ,
Microsoft.Kiota.Serialization.Multipart.MultipartSerializationWriterFactory
Language Default deserializer

Go github.com/microsoft/kiota-serialization-form-go/FormSerializationWriterFactory ,
github.com/microsoft/kiota-serialization-json-go/JsonSerializationWriterFactory ,
github.com/microsoft/kiota-serialization-text-go/TextSerializationWriterFactory ,
github.com/microsoft/kiota-serialization-multipart-go/MultipartSerializationWriterFactory

Java com.microsoft.kiota.serialization.FormSerializationWriterFactory ,
com.microsoft.kiota.serialization.JsonSerializationWriterFactory ,
com.microsoft.kiota.serialization.TextSerializationWriterFactory ,
com.microsoft.kiota.serialization.MultipartSerializationWriterFactory

PHP Microsoft\Kiota\Serialization\Json\JsonSerializationWriterFactory ,
Microsoft\Kiota\Serialization\Text\TextSerializationWriterFactory

Python kiota_serialization_json.json_serialization_writer_factory.JsonSerializationWriterFactory ,
kiota_serialization_text.text_serialization_writer_factory.TextSerializationWriterFactory

Ruby microsoft_kiota_serialization/json_serialization_writer_factory

TypeScript @microsoft/kiota-serialization-form.FormSerializationWriterFactory , @microsoft/kiota-


serialization-json.JsonSerializationWriterFactory , @microsoft/kiota-serialization-
text.TextSerializationWriterFactory , @microsoft/kiota-serialization-
multipart.MultipartSerializationWriterFactory

Accepted values

One or more module names that implement ISerializationWriterFactory .

Bash

kiota generate --serializer Contoso.Json.CustomSerializer

--structured-mime-types (-m)

The MIME types to use for structured data model generation with their preference weight.
Any type without a preference has its preference defaulted to 1. Accepts multiple values.
The notation style and the preference weight logic follow the convention defined in
RFC9110 .

Default values:

application/json;q=1
application/x-www-form-urlencoded;q=0.2

multipart/form-data;q=0.1
text/plain;q=0.9
7 Note

Only request body types or response types with a defined schema will generate
models, other entries will default back to stream/byte array.

7 Note

In a scenario where the client application needs to upload/download a binary object


of a type that matches a structured mime types entry (e.g. uploading a JSON report
that came from the file storage), the recommendation is generate an additional client
for that operation excluding this type, which will result in a method accepting a
stream for the request body or returning a stream for the response.

Accepted values

Any valid MIME type that matches a request body type or a response type in the OpenAPI
description.

Examples
Bash

kiota generate --structured-mime-types application/json

--type-access-modifier (--tam)

Controls the accessibility level for generated client types.

This can be useful to reduce the scope of visibility in library scenarios where you do not
want to expose the generated types to consuming projects.

Default value:

Public

7 Note

This is currently only available for --language CSharp

Available for commands: generate.


Accepted values
Public

Internal

Protected

Examples
Bash

kiota generate --type-access-modifier Internal

Language information
Kiota info accepts the following parameters when displaying language information like
their maturity level or dependencies needed at runtime.

Bash

kiota info [(--openapi | -d) <path>]


[(--language | -l) <language>]
[(--log-level | --ll) <level>]
[--clear-cache | --cc]
[(--version | -v) <version>]
[(--search-key | -k) <searchKey>]
[(--dependency-type | --dt) <typeKey>]
[(--json)]

Example - global
The following command with the provided options displays the following result.

Bash

kiota info

Bash

Language Maturity Level


CLI Preview
CSharp Stable
Go Stable
Java Preview
PHP Stable
Python Stable
Ruby Experimental
Swift Experimental
TypeScript Experimental

Example - with language


The following command with the provided options displays the following result.

Bash

kiota info -l CSharp

Bash

The language CSharp is currently in Stable maturity level.


After generating code for this language, you need to install the following
packages:
dotnet add package Microsoft.Kiota.Abstractions --version 1.6.1
dotnet add package Microsoft.Kiota.Http.HttpClientLibrary --version 1.3.0
dotnet add package Microsoft.Kiota.Serialization.Form --version 1.1.0
dotnet add package Microsoft.Kiota.Serialization.Json --version 1.1.1
dotnet add package Microsoft.Kiota.Authentication.Azure --version 1.1.0
dotnet add package Microsoft.Kiota.Serialization.Text --version 1.1.0
dotnet add package Microsoft.Kiota.Serialization.Multipart --version 1.1.0

Optional Parameters
The info command accepts optional parameters commonly available on the other
commands:

--openapi
--clear-cache
--log-level
--language
--version
--search-key
--dependency-type
--json

--json

Using the --json optional parameter renders the output in a machine parsable format:

Bash
kiota info -l CSharp --json

JSON

{
"maturityLevel": "Stable",
"dependencyInstallCommand": "dotnet add package {0} --version {1}",
"dependencies": [
{
"name": "Microsoft.Kiota.Abstractions",
"version": "1.6.1",
"type": "abstractions"
},
{
"name": "Microsoft.Kiota.Http.HttpClientLibrary",
"version": "1.2.0",
"type": "http"
},
{
"name": "Microsoft.Kiota.Serialization.Form",
"version": "1.1.0",
"type": "serialization"
},
{
"name": "Microsoft.Kiota.Serialization.Json",
"version": "1.1.1",
"type": "serialization"
},
{
"name": "Microsoft.Kiota.Authentication.Azure",
"version": "1.1.0",
"type": "authentication"
},
{
"name": "Microsoft.Kiota.Serialization.Text",
"version": "1.1.0",
"type": "serialization"
},
{
"name": "Microsoft.Kiota.Serialization.Multipart",
"version": "1.1.0",
"type": "serialization"
},
{
"name": "Microsoft.Kiota.Bundle",
"version": "1.1.0",
"type": "bundle"
}
],
"clientClassName": "",
"clientNamespaceName": ""
}
--dependency type (--dt)

Since: 1.18.1

The type of dependencies to display when used in combination with the language option.
Does not impact the json output. Accepts multiple values. Default empty.

Bash

kiota info --language CSharp --dependency-type authentication

Accepted values:

ノ Expand table

Value Description Requirement

Abstractions Define the core concepts of the language. Build time

Additional Required in addition to the abstractions or bundle. Build time

Authentication Implement authentication providers. Optional

Bundle Include abstractions, serialization and HTTP dependencies for


simpler management.

HTTP Implement the request adapter with a specific HTTP client. Runtime

Serialization Implement serialization and deserialization for a given format. Runtime

When no value is provided the info command will display:

All dependencies when no bundle is available.


Bundle, authentication and additional dependencies when a bundle is available.

Client update
Kiota update accepts the following parameters during the update of existing clients. This
command searches for lock files in the output directory and all its subdirectories and
triggers generations to refresh the existing clients using settings from the lock files.

Bash

kiota update [(--output | -o) <path>]


[(--log-level | --ll) <level>]
[--clean-output | --co]
[--clear-cache | --cc]
Optional parameters
The generate command accepts optional parameters commonly available on the other
commands:

--clear-cache
--clean-output
--log-level
--output

Sign in
Use kiota login to sign in to private repositories and search for/display/generate clients
for private API descriptions. This command makes subcommands available to sign in to
specific authentication providers.

Sign in to GitHub
Bash

kiota login github <device|pat>


[(--log-level | --ll) <level>]
[(--pat) <patValue>]

Use kiota login github device to sign in using a device code, you're prompted to sign-in
using a web browser.

Use kiota login github pat --pat patValue to sign in using a Personal Access Token you
previously generated. You can use either a classic personal access token (PAT) or a granular
PAT. A classic PAT needs the repo permission and to be granted access to the target
organizations. A granular PAT needs a read-only permission for the contents scope under
the repository category and they need to be consented for all private repositories or
selected private repositories.

7 Note

For more information about adding API descriptions to the GitHub index, see Adding
an API to search.

Optional parameters
The generate command accepts optional parameters commonly available on the other
commands:

--log-level

Sign out
Use kiota logout to sign out from a private repository containing API descriptions.

Bash

kiota logout github


[(--log-level | --ll) <level>]

Optional parameters
The generate command accepts optional parameters commonly available on the other
commands:

--log-level

Common parameters
The following parameters are available across multiple commands.

--clean-output (--co)

Delete the output directory before generating the client. Defaults to false.

Available for commands: download, generate.

Bash

kiota <command name> --clean-output

--clear-cache (--cc)

Clears the currently cached file for the command. Defaults to false.

Cached files are stored under %TEMP%/kiota/cache and valid for one (1) hour after the
initial download. Kiota caches API descriptions during generation and static index files
during search.
Bash

kiota <command name> --clear-cache

--exclude-path (-e)

A glob pattern to exclude paths from generation. Accepts multiple values.

Bash

kiota <command name> --exclude-path **/users/** --exclude-path **/groups/**

You can also filter specific HTTP methods by appending #METHOD to the pattern, replacing
METHOD with the HTTP method to filter. For example, **/users/**#GET .

 Tip

An --exclude-path pattern can be used in combination with the --include-path


argument. A path item is included when (no include pattern is included OR it matches
an include pattern) AND (no exclude pattern is included OR it doesn't match an
exclude pattern).

--include-path (-i)

A glob pattern to include paths from generation. Accepts multiple values. If this parameter
is absent, everything is included.

Bash

kiota <command name> --include-path **/users/** --include-path **/groups/**

You can also filter specific HTTP methods by appending #METHOD to the pattern, replacing
METHOD with the HTTP method to filter. For example, **/users/**#GET .

 Tip

An --include-path pattern can be used in combination with the --exclude-path


argument. A path item is included when (no include pattern is included OR it matches
an include pattern) AND (no exclude pattern is included OR it doesn't match an
exclude pattern).
--openapi (-d)

The location of the OpenAPI description in JSON or YAML format to use to generate the
SDK. Accepts a URL or a local path.

Available for commands: info, show, generate.

Bash

kiota <command name> --openapi https://description.url/description.yml

--language (-l)

The target language for the generated code files or for the information.

Available for commands: info, generate.

Accepted values
csharp

go
java

php

python
ruby

shell
swift

typescript

Bash

kiota <command name> --language java

--log-level (--ll)

The log level to use when logging events to the main output. Defaults to warning .

Available for commands: all.

Accepted values
critical
debug

error
information

none

trace
warning

Bash

kiota <command name> --log-level information

--output (-o)

The output directory or file path for the generated code files. Defaults to ./output for
generate and ./output/result.json for download.

Available for commands: download, generate.

Accepted values
A valid path to a directory (generate) or a file (download).

Bash

kiota <command name> --output ./src/client

--search-key (-k)

The search key to use to fetch the Open API description. This parameter can be used in
combination with the version option. Shouldn't be used in combination with the --openapi
option. Default empty.

Available for commands: info and show .

Bash

kiota <command name> --search-key apisguru::github.com:api.github.com

--version (-v)
Select a specific version of the API description. No default value.

Available for commands: download, search.

Bash

kiota <command name> --version beta

--disable-ssl-validation (--dsv)

The disable SSL validation is an option that allows users to disable SSL certificate
validation. When this option is set to true, the SSL certificates presented by HTTPS servers
of the OpenAPI description file aren't validated. Disabling validation can be useful in
development or testing environments with self-signed certificates.

Available for commands: generate, show, and download.

Bash

kiota <command name> --disable-ssl-validation


Kiota API client quick starts
Article • 05/24/2024

Kiota quick starts are step-by-step exercises that guide you through generating an API
client for a basic OpenAPI. It also provides steps to create a basic application that uses
the generated client. These quick starts use the JSONPlaceholder REST API .

7 Note

Completed code for these quickstarts is available in the kiota-samples GitHub


repository.

ノ Expand table

Quick start GitHub location

CLI microsoft/kiota-samples/get-started/quickstart/cli

.NET microsoft/kiota-samples/get-started/quickstart/dotnet

Go microsoft/kiota-samples/get-started/quickstart/go

Java microsoft/kiota-samples/get-started/quickstart/java

PHP microsoft/kiota-samples/get-started/quickstart/php

Python microsoft/kiota-samples/get-started/quickstart/python

TypeScript microsoft/kiota-samples/get-started/quickstart/typescript
Build API clients for .NET
Article • 10/01/2024

In this tutorial, you build a sample app in .NET that calls a REST API that doesn't require
authentication.

Required tools
.NET SDK 8.0

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

Bash

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", "netstandard2.1", "net462", or


"net6" or later. More information
*.csproj > LangVersion set to "preview", "latest", or "7.3" or later. 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 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.


Bash

dotnet add package Microsoft.Kiota.Bundle

Generate the API client


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

YAML

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.

Bash

kiota generate -l CSharp -c PostsClient -n KiotaPosts.Client -d ./posts-


api.yml -o ./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 to include the following code.

C#

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);
}

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

Bash

dotnet run

See also
kiota-samples repository contains the code from this guide.
Microsoft Graph sample using Microsoft identity platform authentication
ToDoItem Sample API implements a sample OpenAPI in ASP.NET Core and
sample clients in multiple languages.
Build API clients for a command line
interface (CLI)
Article • 10/01/2024

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:

Windows Terminal (or equivalent on MacOS/linux)


.NET SDK 7.0

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

Bash

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, refer to the dependencies documentation.
For this tutorial, use the default implementations.

Run the following commands to get the required dependencies.

Bash

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.

YAML

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.

Bash

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.

C#
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);

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

dotnet run -- posts list

GET /posts/{id}
Bash

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

POST /posts
Bash

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

PATCH /posts/{id}
Bash

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

DELETE /posts/{id}
Bash

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


See also
kiota-samples repository contains the code from this guide.
Microsoft Graph sample using Microsoft identity platform authentication
ToDoItem Sample API implements a sample OpenAPI in ASP.NET Core and
sample clients in multiple languages.
Build API clients for Go
Article • 10/01/2024

In this tutorial, you build a sample app in Go that calls a REST API that doesn't require
authentication.

Required tools
Go 1.20

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

Bash

go mod init kiota_posts

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

go.mod > go set to version 18 or above.

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.

Bash

go get github.com/microsoft/kiota-bundle-go
Generate the API client
Kiota generates API clients from OpenAPI documents. Create a file named posts-api.yml
and add the following.

YAML

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.

Bash

kiota generate -l go -c PostsClient -n kiota_posts/client -d ./posts-api.yml


-o ./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


Create a file in the root of the project named main.go and add the following code.

Go

package main

import (
"context"
"fmt"
"log"

"kiota_posts/client"
"kiota_posts/client/models"

auth "github.com/microsoft/kiota-abstractions-go/authentication"
bundle "github.com/microsoft/kiota-bundle-go"
)
func main() {
// API requires no authentication, so use the anonymous
// authentication provider
authProvider := auth.AnonymousAuthenticationProvider{}

// Create request adapter using the net/http-based implementation


adapter, err := bundle.NewDefaultRequestAdapter(&authProvider)
if err != nil {
log.Fatalf("Error creating request adapter: %v\n", err)
}

// Create the API client


client := client.NewPostsClient(adapter)

// GET /posts
allPosts, err := client.Posts().Get(context.Background(), nil)
if err != nil {
log.Fatalf("Error getting posts: %v\n", err)
}
fmt.Printf("Retrieved %d posts.\n", len(allPosts))

// GET /posts/{id}
specificPostId := int32(5)
specificPost, err :=
client.Posts().ByPostIdInteger(specificPostId).Get(context.Background(),
nil)
if err != nil {
log.Fatalf("Error getting post by ID: %v\n", err)
}
fmt.Printf("Retrieved post - ID: %d, Title: %s, Body: %s\n",
*specificPost.GetId(), *specificPost.GetTitle(), *specificPost.GetBody())

// POST /posts
newPost := models.NewPost()
userId := int32(42)
newPost.SetUserId(&userId)
title := "Testing Kiota-generated API client"
newPost.SetTitle(&title)
body := "Hello world!"
newPost.SetBody(&body)

createdPost, err := client.Posts().Post(context.Background(), newPost,


nil)
if err != nil {
log.Fatalf("Error creating post: %v\n", err)
}
fmt.Printf("Created new post with ID: %d\n", *createdPost.GetId())

// PATCH /posts/{id}
update := models.NewPost()
newTitle := "Updated title"
update.SetTitle(&newTitle)

updatedPost, err :=
client.Posts().ByPostIdInteger(specificPostId).Patch(context.Background(),
update, nil)
if err != nil {
log.Fatalf("Error updating post: %v\n", err)
}
fmt.Printf("Updated post - ID: %d, Title: %s, Body: %s\n",
*updatedPost.GetId(), *updatedPost.GetTitle(), *updatedPost.GetBody())

// DELETE /posts/{id}
_, err =
client.Posts().ByPostIdInteger(specificPostId).Delete(context.Background(),
nil)
if err != nil {
log.Fatalf("Error deleting post: %v\n", err)
}
fmt.Printf("Deleted post\n")
}

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

Bash

go run .

See also
kiota-samples repository contains the code from this guide.
Microsoft Graph sample using Microsoft identity platform authentication
ToDoItem Sample API implements a sample OpenAPI in ASP.NET Core and
sample clients in multiple languages.
Build API clients for Java
Article • 10/01/2024

In this tutorial, you build a sample app in Java that calls a REST API that doesn't require
authentication.

Required tools
OpenJDK 17
Gradle 7.4

Create a project
Use Gradle to initialize a Java application project.

Bash

gradle init --dsl groovy --test-framework junit --type java-application --


project-name kiotaposts --package kiotaposts

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

build.gradle > compileJava > sourceCompatibility set to "1.8" or later. (or


equivalent if you're not using gradle)
build.gradle > compileJava > targetCompatibility set to "1.8" or later. (or
equivalent if you're not using gradle)
Java Development Kit (JDK) version 17 or above.

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.

Edit ./app/build.gradle to add the following dependencies.


7 Note

Find current version numbers for Kiota packages at Nexus Repository Manager .

Gradle

implementation 'jakarta.annotation:jakarta.annotation-api:3.0.0'
implementation 'com.microsoft.kiota:microsoft-kiota-bundle:1.5.0'

Generate the API client


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

YAML

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.

Bash

kiota generate -l java -c PostsClient -n kiotaposts.client -d ./posts-


api.yml -o ./app/src/main/java/kiotaposts/client --ds none -s none

 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 ./app/src/main/java/kiotaposts/App.java file that was
generated as part of the console application, replacing its contents with the following
code.
Java

package kiotaposts;

import java.util.List;

import com.microsoft.kiota.authentication.AnonymousAuthenticationProvider;
import com.microsoft.kiota.bundle.DefaultRequestAdapter;

import kiotaposts.client.PostsClient;
import kiotaposts.client.models.Post;

public class App {

public static void main(String[] args) {


// API requires no authentication, so use the anonymous
// authentication provider
final AnonymousAuthenticationProvider authProvider =
new AnonymousAuthenticationProvider();
final DefaultRequestAdapter adapter = new
DefaultRequestAdapter(authProvider);

final PostsClient client = new PostsClient(adapter);

// GET /posts
final List<Post> allPosts = client.posts().get();
System.out.printf("Retrieved %d posts.%n", allPosts.size());

// GET /posts/{id}
final Integer specificPostId = 5;
final Post specificPost =
client.posts().byPostId(specificPostId).get();
System.out.printf("Retrieved post - ID: %d, Title: %s, Body: %s%n",
specificPost.getId(), specificPost.getTitle(),
specificPost.getBody());

// POST /posts
final Post newPost = new Post();
newPost.setUserId(42);
newPost.setTitle("Testing Kiota-generated API client");
newPost.setBody("Hello world!");

final Post createdPost = client.posts().post(newPost);


System.out.printf("Created new post with ID: %d%n",
createdPost.getId());

// PATCH /posts/{id}
final Post update = new Post();
// Only update title
update.setTitle("Updated title");

final Post updatedPost =


client.posts().byPostId(specificPostId).patch(update);
System.out.printf("Updated post - ID: %d, Title: %s, Body: %s%n",
updatedPost.getId(), updatedPost.getTitle(),
updatedPost.getBody());

// DELETE /posts/{id}
client.posts().byPostId(specificPostId).delete();
}
}

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

Bash

./gradlew --console plain run

See also
kiota-samples repository contains the code from this guide.
Microsoft Graph sample using Microsoft identity platform authentication
ToDoItem Sample API implements a sample OpenAPI in ASP.NET Core and
sample clients in multiple languages.

(UNOFFICIAL) Community tools and libraries

) Important

The Kiota Community tools and libraries are maintained and distributed by the
community and are not official Microsoft tools and libraries. Microsoft makes no
warranties, express or implied, with respect to the tools and libraries or their use.
Use of the tools and libraries at your own risk. Microsoft shall not be liable for any
damages arising out of or in connection with the use of the tools and libraries.
There are community tools and libraries to make it easy for you to get started with Kiota
and to better harmonize the class path according to the rest of your stack:

Kiota Maven Plugin


Kiota Jackson Serialization
Kiota Http VertX
Kiota Http JDK
Kiota Quarkus Extension
Build API clients for PHP
Article • 06/25/2024

In this tutorial, you build a sample app in PHP that calls a REST API that doesn't require
authentication.

Required tools
PHP ^7.4 or ^8.0
Composer

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

Bash

composer init

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

composer.json > require > php set to "php": "^8.0 || ^7.4" 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.

HTTP (Kiota default Guzzle-based implementation )


JSON serialization (Kiota default )
Text serialization (Kiota default )

For this tutorial, use the default implementations.


Run the following commands to get the required dependencies.

Bash

composer require microsoft/kiota-abstractions


composer require microsoft/kiota-http-guzzle
composer require microsoft/kiota-serialization-json
composer require microsoft/kiota-serialization-text

Generate the API client


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

YAML

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.

Bash

kiota generate -l PHP -d ../posts-api.yml -c PostsApiClient -n


KiotaPosts\Client -o ./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.

Add the following to your composer.json to set your namespaces correctly:

JSON

"autoload": {
"psr-4": {
"KiotaPosts\\Client\\": "client/"
}
}

To ensure the newly generated classes can be imported, update the autoload paths
using:

Bash

composer dumpautoload

Create the client application


Create a file in the root of the project named main.php and add the following code.

PHP

<?php

use KiotaPosts\Client\PostsApiClient;
use KiotaPosts\Client\Models\Post;
use Microsoft\Kiota\Abstractions\ApiException;
use
Microsoft\Kiota\Abstractions\Authentication\AnonymousAuthenticationProvider;
use Microsoft\Kiota\Http\GuzzleRequestAdapter;

require __DIR__.'/vendor/autoload.php';

try {
$authProvider = new AnonymousAuthenticationProvider();
$requestAdapter = new GuzzleRequestAdapter($authProvider);
$client = new PostsApiClient($requestAdapter);

// GET /posts
$allPosts = $client->posts()->get()->wait();
$postCount = sizeof($allPosts);
echo "Retrieved {$postCount} posts.\n";

// GET /posts/{id}
$specificPostId = 5;
$specificPost = $client->posts()->byPostId($specificPostId)->get()-
>wait();
echo "Retrieved post - ID: {$specificPost->getId()}, Title:
{$specificPost->getTitle()}, Body: {$specificPost->getBody()}\n";

// POST /posts
$newPost = new Post();
$newPost->setUserId(42);
$newPost->setTitle("Testing Kiota-generated API client");
$newPost->setBody("Hello world!");
$createdPost = $client->posts()->post($newPost)->wait();
echo "Created new post with ID: {$createdPost->getId()}\n";

// PATCH /posts/{id}
$update = new Post();
// Only update title
$update->setTitle("Updated title");

$updatedPost = $client->posts()->byPostId($specificPostId)-
>patch($update)->wait();
echo "Updated post - ID: {$updatedPost->getId()}, Title: {$updatedPost-
>getTitle()}, Body: {$updatedPost->getBody()}\n";

// DELETE /posts/{id}
$client->posts()->byPostId($specificPostId)->delete()->wait();
}catch (ApiException $ex) {
echo $ex->getMessage();
}
?>

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

Bash

php main.php

See also
kiota-samples repository contains the code from this guide.
Microsoft Graph sample using Microsoft identity platform authentication
ToDoItem Sample API implements a sample OpenAPI in ASP.NET Core and
sample clients in multiple languages.
Build API clients for Python
Article • 06/25/2024

In this tutorial, you build a sample app in Python that calls a REST API that doesn't
require authentication.

Required tools
Python 3.8+
pip 20.0+
asyncio or any other supported async environment, for example, AnyIO, Trio.

Create a project
Create a directory to contain the new project.

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

pyproject.toml > project > requires-python set to ">=3.8".

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:

HTTP (Kiota default HTTPX-based implementation )


JSON serialization (Kiota default )
Text serialization (Kiota default )

For this tutorial, use the default implementations.

Run the following commands to get the required dependencies:

Bash
pip install microsoft-kiota-abstractions
pip install microsoft-kiota-http
pip install microsoft-kiota-serialization-json
pip install microsoft-kiota-serialization-text
pip install microsoft-kiota-serialization-form
pip install microsoft-kiota-serialization-multipart

 Tip

It is recommended to use a package manager/virtual environment to avoid


installing packages system wide. Read more here .

Generate the API client


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

YAML

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.

Bash

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


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


Create a file in the root of the project named main.py and add the following code.
Python

import asyncio
from kiota_abstractions.authentication.anonymous_authentication_provider
import (
AnonymousAuthenticationProvider)
from kiota_http.httpx_request_adapter import HttpxRequestAdapter
from client.posts_client import PostsClient
from client.models.post import Post

async def main():


# You may need this if your're using asyncio on windows
# See: https://stackoverflow.com/questions/63860576
#
asyncio.set_event_loop_policy(asyncio.WindowsSelectorEventLoopPolicy())

# API requires no authentication, so use the anonymous


# authentication provider
auth_provider = AnonymousAuthenticationProvider()
# Create request adapter using the HTTPX-based implementation
request_adapter = HttpxRequestAdapter(auth_provider)
# Create the API client
client = PostsClient(request_adapter)

# GET /posts
all_posts = await client.posts.get()
print(f"Retrieved {len(all_posts)} posts.")

# GET /posts/{id}
specific_post_id = "5"
specific_post = await client.posts.by_post_id(specific_post_id).get()
print(f"Retrieved post - ID: {specific_post.id}, " +
f"Title: {specific_post.title}, " +
f"Body: {specific_post.body}")

# POST /posts
new_post = Post()
new_post.user_id = 42
new_post.title = "Testing Kiota-generated API client"
new_post.body = "Hello world!"

created_post = await client.posts.post(new_post)


print(f"Created new post with ID: {created_post.id}")

# PATCH /posts/{id}
update = Post()
# Only update title
update.title = "Updated title"

updated_post = await
client.posts.by_post_id(specific_post_id).patch(update)
print(f"Updated post - ID: {updated_post.id}, " +
f"Title: {updated_post.title}, " +
f"Body: {updated_post.body}")
# DELETE /posts/{id}
await client.posts.by_post_id(specific_post_id).delete()

# Run main
asyncio.run(main())

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

Bash

python3 main.py

See also
kiota-samples repository contains the code from this guide.
Microsoft Graph sample using Microsoft identity platform authentication
ToDoItem Sample API implements a sample OpenAPI in ASP.NET Core and
sample clients in multiple languages.
Build API clients for TypeScript
Article • 10/01/2024

In this tutorial, you build a sample app in TypeScript that calls a REST API that doesn't
require authentication.

Required tools
NodeJS 18 or above
TypeScript 5 or above

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

Bash

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 bundle package . For more information about kiota
dependencies, refer to the dependencies documentation.
Run the following commands to get the required dependencies.

Bash

npm install @microsoft/kiota-bundle

Generate the API client


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

YAML

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.

Bash

kiota generate -l typescript -d posts-api.yml -c PostsClient -o ./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


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

TypeScript

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();

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

Bash

npx ts-node index.ts

See also
kiota-samples repository contains the code from this guide.
Microsoft Graph sample using Microsoft identity platform authentication
ToDoItem Sample API implements a sample OpenAPI in ASP.NET Core and
sample clients in multiple languages.
Build API clients for .NET with Microsoft
identity authentication
Article • 10/01/2024

In this tutorial, you generate an API client that uses Microsoft identity authentication to
access Microsoft Graph.

Required tools
.NET SDK 8.0
Kiota CLI

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

.NET CLI

dotnet new console -o GetUserClient


dotnet new gitignore

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.

.NET CLI

dotnet add package Microsoft.Kiota.Bundle


dotnet add package Microsoft.Kiota.Authentication.Azure
dotnet add package Azure.Identity

Generate the API client


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

YAML

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.

Bash

kiota generate -l csharp -d get-me.yml -c GetUserApiClient -n


GetUserClient.ApiClient -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.
Azure portal

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


The final step is to update the Program.cs file that was generated as part of the console
application to include the following code. Replace YOUR_CLIENT_ID with the client ID
from your app registration.

C#

using Azure.Identity;
using GetUserClient.ApiClient;
using Microsoft.Kiota.Authentication.Azure;
using Microsoft.Kiota.Bundle;

// The auth provider will only authorize requests to


// the allowed hosts, in this case Microsoft Graph
var allowedHosts = new[] { "graph.microsoft.com" };
var graphScopes = new[] { "User.Read" };

var options = new DeviceCodeCredentialOptions


{
ClientId = "YOUR_CLIENT_ID",
DeviceCodeCallback = (code, cancellation) =>
{
Console.WriteLine(code.Message);
return Task.FromResult(0);
},
};

var credential = new DeviceCodeCredential(options);

var authProvider = new AzureIdentityAuthenticationProvider(credential,


allowedHosts, scopes: graphScopes);
var requestAdapter = new DefaultRequestAdapter(authProvider);
var client = new GetUserApiClient(requestAdapter);

var me = await client.Me.GetAsync();


Console.WriteLine($"Hello {me.DisplayName}, your ID is {me.Id}");

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

.NET CLI

dotnet run

See also
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.
Build API clients for a command line
interface (CLI) with Microsoft identity
authentication
Article • 10/01/2024

In this tutorial, you generate an API client that uses Microsoft identity authentication to
access Microsoft Graph.

Required tools
A command line tool is required. We recommend:

Windows Terminal (or equivalent on MacOS/linux)


.NET SDK 8.0

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

Bash

dotnet new console -o GetUserClient


dotnet new gitignore

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, refer to the dependencies documentation.

Run the following commands to get the required dependencies.

Bash

dotnet add package Microsoft.Kiota.Bundle


dotnet add package Microsoft.Kiota.Cli.Commons --prerelease
dotnet add package Azure.Identity
dotnet add package Microsoft.Extensions.DependencyInjection
dotnet add package Microsoft.Extensions.Hosting

Generate the API client


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

YAML

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.

Bash

kiota generate --openapi get-me.yml --language CLI -c GetUserApiClient -n


GetUserClient.ApiClient -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.

Azure portal

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


The final step is to update the Program.cs file that was generated as part of the console
application to include the following code. Replace YOUR_CLIENT_ID with the client ID
from your app registration.

C#

using System.CommandLine.Builder;
using System.CommandLine.Parsing;
using Azure.Identity;
using GetUserClient.ApiClient;
using Microsoft.Kiota.Authentication.Azure;
using Microsoft.Kiota.Cli.Commons.Extensions;
using Microsoft.Kiota.Bundle;

var rootCommand = new GetUserApiClient().BuildRootCommand();


rootCommand.Description = "CLI description";

// Set up services
var builder = new CommandLineBuilder(rootCommand)
.UseDefaults()
.UseRequestAdapter(ic =>
{
// The auth provider will only authorize requests to
// the allowed hosts, in this case Microsoft Graph
var allowedHosts = new[] { "graph.microsoft.com" };
var graphScopes = new[] { "User.Read" };
var options = new DeviceCodeCredentialOptions
{
ClientId = "YOUR_CLIENT_ID",
DeviceCodeCallback = (code, cancellation) =>
{
Console.WriteLine(code.Message);
return Task.FromResult(0);
},
};
var credential = new DeviceCodeCredential(options);

var authProvider = new


AzureIdentityAuthenticationProvider(credential, allowedHosts, scopes:
graphScopes);
var adapter = new DefaultRequestAdapter(authProvider);
adapter.BaseUrl = "https://graph.microsoft.com/v1.0";
return adapter;
}).RegisterCommonServices();

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

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

Bash

dotnet run -- me get


See also
kiota-samples repository contains the code from this guide.
More CLI samples
ToDoItem Sample API implements a sample OpenAPI in ASP.NET Core and
sample clients in multiple languages.
Build API clients for Go with Azure
authentication
Article • 10/01/2024

In this tutorial, you generate an API client that uses Microsoft identity authentication to
access Microsoft Graph.

Required tools
Go 1.20

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

Bash

go mod init getuser

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.

Bash

go get github.com/microsoft/kiota-bundle-go
go get github.com/microsoft/kiota-authentication-azure-go
go get github.com/Azure/azure-sdk-for-go/sdk/azidentity

Generate the API client


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

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.

Bash

kiota generate -l go -d ../get-me.yml -c GraphApiClient -n getuser/client -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.

Azure portal
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 getuser.go and add the following code.
Replace YOUR_CLIENT_ID with the client ID from your app registration.

Go

package main

import (
"context"
"fmt"

"getuser/client"

"github.com/Azure/azure-sdk-for-go/sdk/azidentity"
azure "github.com/microsoft/kiota-authentication-azure-go"
bundle "github.com/microsoft/kiota-bundle-go"
)

func main() {
clientId := "YOUR_CLIENT_ID"
// The auth provider will only authorize requests to
// the allowed hosts, in this case Microsoft Graph
allowedHosts := []string{"graph.microsoft.com"}
graphScopes := []string{"User.Read"}

credential, err :=
azidentity.NewDeviceCodeCredential(&azidentity.DeviceCodeCredentialOptions{
ClientID: clientId,
UserPrompt: func(ctx context.Context, dcm
azidentity.DeviceCodeMessage) error {
fmt.Println(dcm.Message)
return nil
},
})

if err != nil {
fmt.Printf("Error creating credential: %v\n", err)
}

authProvider, err :=
azure.NewAzureIdentityAuthenticationProviderWithScopesAndValidHosts(
credential, graphScopes, allowedHosts)

if err != nil {
fmt.Printf("Error creating auth provider: %v\n", err)
}

adapter, err := bundle.NewDefaultRequestAdapter(authProvider)

if err != nil {
fmt.Printf("Error creating request adapter: %v\n", err)
}

client := client.NewGraphApiClient(adapter)

me, err := client.Me().Get(context.Background(), nil)

if err != nil {
fmt.Printf("Error getting user: %v\n", err)
}

fmt.Printf("Hello %s, your ID is %s\n", *me.GetDisplayName(),


*me.GetId())
}

7 Note

This example uses the DeviceCodeCredential class. You can use any of the
credential classes from the azidentity library.
Run the application
To start the application, run the following command in your project directory.

Bash

go run .

See also
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.
Build API clients for Java with Microsoft
identity authentication
Article • 10/01/2024

Required tools
Java Development Kit (JDK) 16
Gradle 7.4

Create a project
Use Gradle to initialize a Java application project.

Bash

gradle init --dsl groovy --test-framework junit --type java-application --


project-name getuserclient --package getuserclient

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.

For this tutorial, use the default implementations.

Edit ./app/build.gradle to add the following dependencies.

7 Note

Find current version numbers for Kiota packages at Nexus Repository Manager .

Gradle

implementation 'jakarta.annotation:jakarta.annotation-api:3.0.0'
implementation 'com.microsoft.kiota:microsoft-kiota-bundle:1.5.0'
implementation 'com.microsoft.kiota:microsoft-kiota-authentication-
azure:1.5.0'
implementation 'com.azure:azure-identity:1.13.3'

Generate the API client


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

YAML

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 SDK classes.

Bash

kiota generate -l java -d get-me.yml -c GetUserApiClient -n


getuserclient.apiclient -o ./app/src/main/java/getuserclient/apiclient --ds
none -s none

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.

Azure portal

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


The final step is to update the ./app/src/main/java/getuserclient/App.java file that was
generated as part of the console application to include the following code. Replace
YOUR_CLIENT_ID with the client ID from your app registration.

Java

package getuserclient;
import com.azure.identity.DeviceCodeCredential;
import com.azure.identity.DeviceCodeCredentialBuilder;
import
com.microsoft.kiota.authentication.AzureIdentityAuthenticationProvider;
import com.microsoft.kiota.bundle.DefaultRequestAdapter;

import getuserclient.apiclient.GetUserApiClient;
import getuserclient.apiclient.models.User;

public class App {

public static void main(String[] args) {


final String clientId = "YOUR_CLIENT_ID";

// The auth provider will only authorize requests to


// the allowed hosts, in this case Microsoft Graph
final String[] allowedHosts = new String[] { "graph.microsoft.com"
};
final String[] graphScopes = new String[] { "User.Read" };

final DeviceCodeCredential credential = new


DeviceCodeCredentialBuilder()
.clientId(clientId)
.challengeConsumer(challenge ->
System.out.println(challenge.getMessage()))
.build();

final AzureIdentityAuthenticationProvider authProvider =


new AzureIdentityAuthenticationProvider(credential,
allowedHosts, graphScopes);
final DefaultRequestAdapter adapter = new
DefaultRequestAdapter(authProvider);

final GetUserApiClient client = new GetUserApiClient(adapter);

try {
final User me = client.me().get();
System.out.printf("Hello %s, your ID is %s%n",
me.getDisplayName(), me.getId());
} catch (Exception err) {
System.out.printf("Error: %s%n", err.getMessage());
}
}
}

7 Note

This example uses the DeviceCodeCredential class. You can use any of the
credential classes from the com.azure.identity library.
Run the application
To start the application, run the following command in your project directory.

Bash

./gradlew --console plain run

See also
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.
Build API clients for PHP with Microsoft
identity authentication
Article • 03/28/2023

In this tutorial, you generate an API client that uses Microsoft identity authentication to
access Microsoft Graph.

Required tools
PHP ^7.4 or ^8.0
Composer

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

Bash

composer 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 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 Guzzle-based implementation )
JSON serialization (Kiota default )
Text serialization (Kiota default )

For this tutorial, use the default implementations.

Run the following commands to get the required dependencies.

Bash
composer require microsoft/kiota-abstractions
composer require microsoft/kiota-http-guzzle
composer require microsoft/kiota-authentication-phpleague
composer require microsoft/kiota-serialization-json
composer require microsoft/kiota-serialization-text

Generate the API client


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

YAML

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.

Bash

kiota generate -l PHP -d get-me.yml -c GraphApiClient -n GetUser\Client -o


./client

Add the following to your composer.json to set your namespaces correctly:


JSON

"autoload": {
"psr-4": {
"GetUser\\Client\\": "client/"
}
}

To ensure the newly generated classes can be imported, update the autoload paths
using:

Bash

composer dumpautoload

Register an application
To be able to authenticate with the Microsoft Entra 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 Microsoft Entra admin center.

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

Azure portal

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.
Set Redirect URI platform to Web, and set the value to
http://localhost .
4. Select Register. On the Overview page, copy the value of the Application
(client) ID and save it.

5. Select Certificates & secrets under Manage. Select the New client secret
button. Enter a value in Description and select one of the options for Expires
and select Add.

6. Copy the Value of the new secret before you leave this page. It is never
displayed again. Save the value for later.

Create the client application


Create a file in the root of the project named GetUser.php and add the following code.
Replace the $clientId and $clientSecret with your credentials from the previous step.

Use the following steps to get an authorization code.

) Important

Authorization codes are short-lived, typically expiring after 10 minutes. You should
get a new authorization code just before running the example.

1. Open your browser and paste in the following URL, replacing YOUR_CLIENT_ID with
the client ID of your app registration.

HTTP

https://login.microsoftonline.com/common/oauth2/v2.0/authorize?
client_id=YOUR_CLIENT_ID&response_type=code&redirect_uri=https%3A%2F%2Ffanyv88.com%3A443%2Fhttp%2Fl
ocalhost&response_mode=query&scope=User.Read

2. Sign in with your Microsoft account. Review the requested permissions and grant
consent to continue.

3. Once authentication completes, your browser will redirect to http://localhost .


The browser displays an error that can be safely ignored.

4. Copy the URL from your browser's address bar.

5. Copy everything in the URL between code= and & . This value is the authorization
code.
Replace the $authorizationCode with your authorization code.

PHP

<?php

use GetUser\Client\GraphApiClient;
use Microsoft\Kiota\Abstractions\ApiException;
use Microsoft\Kiota\Authentication\Oauth\AuthorizationCodeContext;
use Microsoft\Kiota\Authentication\PhpLeagueAuthenticationProvider;
use Microsoft\Kiota\Http\GuzzleRequestAdapter;

require __DIR__.'/vendor/autoload.php';

try {
$clientId = 'clientId';
$clientSecret = 'secret';
$authorizationCode = 'authCode';

$tenantId = 'common';
$redirectUri = 'http://localhost';

// The auth provider will only authorize requests to


// the allowed hosts, in this case Microsoft Graph
$allowedHosts = ['graph.microsoft.com'];
$scopes = ['User.Read'];

$tokenRequestContext = new AuthorizationCodeContext(


$tenantId,
$clientId,
$clientSecret,
$authorizationCode,
$redirectUri
);

$authProvider = new
PhpLeagueAuthenticationProvider($tokenRequestContext, $scopes,
$allowedHosts);
$requestAdapter = new GuzzleRequestAdapter($authProvider);
$client = new GraphApiClient($requestAdapter);

$me = $client->me()->get()->wait();
echo "Hello {$me->getDisplayName()}, your ID is {$me->getId()}";

} catch (ApiException $ex) {


echo $ex->getMessage();
}
?>

7 Note
This example uses the AuthorizationCodeContext class. You can use any of the
credential classes from the kiota-authentication-phpleague library.

Run the application


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

Bash

php GetUser.php

See also
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.
Build API clients for Python with
Microsoft identity authentication
Article • 05/24/2024

In this tutorial, you generate an API client that uses Microsoft identity authentication to
access Microsoft Graph.

Required tools
Python 3.8+
pip 20.0+
asyncio or any other supported async environment, for example, AnyIO, Trio.

Create a project
Create a directory to contain the new project.

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.

Authentication (Kiota default Azure authentication )


HTTP (Kiota default HTTPX-based implementation )
JSON serialization (Kiota default )
Text serialization (Kiota default )

For this tutorial, use the default implementations.

Run the following commands to get the required dependencies.

Bash

pip install microsoft-kiota-abstractions


pip install microsoft-kiota-authentication-azure
pip install microsoft-kiota-http
pip install microsoft-kiota-serialization-json
pip install microsoft-kiota-serialization-text
pip install azure-identity

 Tip

It is recommended to use a package manager/virtual environment to avoid


installing packages system wide. Read more here .

Generate the API client


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

YAML

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.

Bash

kiota generate -l python -d get-me.yml -c GetUserApiClient -n client -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.

Azure portal

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 get_user.py and add the following code.
Replace YOUR_CLIENT_ID with the client ID from your app registration.
Python

import asyncio
from azure.identity import DeviceCodeCredential
from kiota_authentication_azure.azure_identity_authentication_provider
import (
AzureIdentityAuthenticationProvider)
from kiota_http.httpx_request_adapter import HttpxRequestAdapter
from client.get_user_api_client import GetUserApiClient

async def main():


# You may need this if your're using asyncio on windows
# See: https://stackoverflow.com/questions/63860576
#
asyncio.set_event_loop_policy(asyncio.WindowsSelectorEventLoopPolicy())

client_id = 'YOUR_CLIENT_ID'
graph_scopes = ['User.Read']

credential = DeviceCodeCredential(client_id)
auth_provider = AzureIdentityAuthenticationProvider(credential,
scopes=graph_scopes)

request_adapter = HttpxRequestAdapter(auth_provider)
client = GetUserApiClient(request_adapter)

user_me = await client.me.get()


print(f"Hello {user_me.display_name}, your ID is {user_me.id}")

# Run main
asyncio.run(main())

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

Bash

python3 get_user.py

See also
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.
Build API clients for Ruby with Microsoft
identity authentication
Article • 05/24/2024

In this tutorial, you generate an API client that uses Microsoft identity authentication to
access Microsoft Graph.

Required tools
Ruby 3
Bundler

Create a project
Create a new file named Gemfile in the root directory of your project.

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.

Authentication (Kiota default Azure authentication )


HTTP (Kiota default Faraday-based implementation )
JSON serialization (Kiota default )

For this tutorial, use the default implementations.

1. Edit your Gemfile and add the following code.

Ruby

source 'https://rubygems.org'

gem "microsoft_kiota_abstractions"
gem "microsoft_kiota_serialization_json"
gem "microsoft_kiota_authentication_oauth"
gem "microsoft_kiota_faraday"
2. To install dependencies, run the following command.

Bash

bundle install

Generate the API client


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

YAML

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.

Bash

kiota generate -l ruby -d get-me.yml -n Graph -o ./client

Lastly, create a file called graph.rb in the client folder that was created by Kiota. Add
the following code:
Ruby

# frozen_string_literal: true
module Graph
end

Register an application
To be able to authenticate with the Microsoft Entra 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 Microsoft Entra admin center.

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

Azure portal

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.
Set Redirect URI platform to Web, and set the value to
http://localhost .

4. Select Register. On the Overview page, copy the value of the Application
(client) ID and save it.

5. Select Certificates & secrets under Manage. Select the New client secret
button. Enter a value in Description and select one of the options for Expires
and select Add.
6. Copy the Value of the new secret before you leave this page. It is never
displayed again. Save the value for later.

Create the client application


Create a file in the root of the project named get_user.rb and add the following code.
Replace the client_id and client_secret with your credentials from the previous step.

Use the following steps to get an authorization code.

) Important

Authorization codes are short-lived, typically expiring after 10 minutes. You should
get a new authorization code just before running the example.

1. Open your browser and paste in the following URL, replacing YOUR_CLIENT_ID with
the client ID of your app registration.

HTTP

https://login.microsoftonline.com/common/oauth2/v2.0/authorize?
client_id=YOUR_CLIENT_ID&response_type=code&redirect_uri=https%3A%2F%2Ffanyv88.com%3A443%2Fhttp%2Fl
ocalhost&response_mode=query&scope=User.Read

2. Sign in with your Microsoft account. Review the requested permissions and grant
consent to continue.

3. Once authentication completes, your browser will redirect to http://localhost .


The browser displays an error that can be safely ignored.

4. Copy the URL from your browser's address bar.

5. Copy everything in the URL between code= and & . This value is the authorization
code.

Replace the auth_code with your authorization code.

Ruby

# frozen_string_literal: true
require 'microsoft_kiota_serialization_json'
require 'microsoft_kiota_abstractions'
require 'microsoft_kiota_authentication_oauth'
require 'microsoft_kiota_faraday'
require_relative './client/get_user_api_client'

client_id = 'CLIENT_ID'
client_secret = 'CLIENT_SECRET'
auth_code = 'AUTH_CODE'

tenant_id = 'common'
redirect_uri = 'http://localhost'

# The auth provider will only authorize requests to


# the allowed hosts, in this case Microsoft Graph
allowed_hosts = ['graph.microsoft.com']
graph_scopes = ['User.Read']
token_request_context =
MicrosoftKiotaAuthenticationOAuth::AuthorizationCodeContext
.new(tenant_id, client_id, client_secret, redirect_uri, auth_code)

auth_provider =
MicrosoftKiotaAuthenticationOAuth::OAuthAuthenticationProvider
.new(token_request_context, allowed_hosts, graph_scopes)

request_adapter = MicrosoftKiotaFaraday::FaradayRequestAdapter
.new(auth_provider,
MicrosoftKiotaSerializationJson::JsonParseNodeFactory.new,
MicrosoftKiotaSerializationJson::JsonSerializationWriterFactory.new)

client = GetUser::GetUserApiClient.new(request_adapter)

me = client.me().get().resume

puts "Hi! My name is #{me.display_name}, and my ID is #{me.id}."

Run the application


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

Bash

ruby ./get_user.rb

See also
kiota-samples repository contains the code from this guide.
Build API clients for TypeScript with
Microsoft identity authentication
Article • 10/01/2024

Required tools
NodeJS 18
TypeScript

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

Bash

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.

Bash

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

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.

Bash

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.

Azure portal
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.

TypeScript

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();

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

Bash

npx ts-node index.ts

See also
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.
Kiota design overview
Article • 05/24/2024

The Kiota SDK code generation process is designed to take an OpenAPI description,
parse it, and generate a set of classes that make it simple for developers to make HTTP
requests to the operations described by the OpenAPI.

OpenAPI description
The OpenAPI description is parsed using the Microsoft.OpenApi.NET library. This library
can accept OpenAPI V2 or V3, in JSON or YAML format and provided as either a String ,
Stream , or TextReader . This library can parse and validate 100,000 lines of OpenAPI

YAML/sec and therefore meets the scaling requirements for Kiota.

The output of this library is an OpenAPIDocument object that is a DOM for the OpenAPI
description. It provides a dictionary of PathItem objects that correspond to the
resources made available by the API. However, each PathItem object uses a URL path
string as their unique identifier. Most SDK code generators take this flat list of PathItem
objects, expand down to the Operation object supported for each PathItem , and
generate a class with methods that correspond to those operations. For large APIs, this
approach creates a class with a large surface area and makes it challenging to create
readable and discoverable method names, especially for APIs with a deeply nested
hierarchy.

HTTP APIs scale in size naturally due to the hierarchical nature of the URL path. In order
to take advantage of this scaling, the generated code must use this characteristic to its
advantage. However OpenAPI descriptions don't naturally represent that hierarchy and
so it must be constructed.

URI space tree


Walking the list of PathItems and building a resource hierarchy is a simple process. This
approach presents an opportunity to apply a filter to limit the PathItems that have code
generated. Many application developers are sensitive to the size of their client
applications. By selectively including only resources that are used by a client application,
libraries can be kept small. It's essential that when more functionality is adopted that
existing generated code doesn't change.

Code model
Most SDK generator efforts use a combination of API description of DOM and templates
to create source code. Templates have several disadvantages:

Syntax differences between languages cause semantic duplication between


languages. This causes there to be lots of redundancies in templates.
Small amounts of logic required when conditionally generating source can
introduce complex syntax inside templates that is hard to test, debug, and
maintain.
It's easy for the behavior and capabilities of the different languages to diverge as
language templates are independent. This divergence can be problematic if you're
trying to provide consistent feature support across languages.

Kiota takes a different approach to code generation. The OpenAPI PathItems are
analyzed and a corresponding language agnostic code model is created. This code
model relies on standard object-oriented features that are available in all recent
mainstream languages.

The code model built for Kiota is designed to support the features needed to create the
thin "typing" veneer over a core HTTP library. It isn't intended to provide a
comprehensive code model for any arbitrary code. This approach of using a common
code model is feasible because we're targeting modern object oriented languages and
limiting the scenarios to making HTTP requests.

Refine code model by language


Despite the narrow scenario, there are still scenarios where, in order to create idiomatic
source code, adjustments are required to the code model before emitting the source
code.

The changes to the model made in this section should be as minimal as possible as
they'll likely cause more maintenance in the future.
This section can be used to import language framework dependencies required for the
generated source code. It can also be used for updating the casing of identifiers the
casing appropriate for the language.

All the different code constructs that are modeled are derived from a base CodeElement
class. Some CodeElements can contain other CodeElements . This approach allows
traversing the CodeElement hierarchy uniformly and enables emitting source code in the
desired order. This section can reorder peer elements based on language conventions.

Generate source files


The last step of the process is to take the code model and translate it to language
specific text. Traversing the CodeElement hierarchy and applying a concrete
LanguageWriter implementation outputs the desired source code.

Implementing a language support for a new language requires, at minimum,


implementing a class that derives from LanguageWriter .

Kiota abstractions
The generated source code doesn't contain the logic to make HTTP requests directly. It
requires being connected to a core library that makes the HTTP requests. A Kiota.Core
library provides basic HTTP functionality, but API owners can choose to provide their
own core libraries that are optimized for their API.

Core libraries take a dependency on the Kiota abstractions library for a language and
provide the services of making the HTTP call to the API.
This abstraction prevents Kiota from taking a dependency on a particular HTTP client
library for a platform. Kiota remains focused on providing a consistent experience for
discovering resources, creating requests, and deserializing responses.
Managing dependencies of Kiota API
clients
Article • 10/01/2024

Kiota clients require multiple dependencies to function properly. In this documentation


page, you find details about each dependency, which package to use in each language
and guidance on how to properly manage these dependencies for your application.

Guidance

Generated client and dependencies versions alignment


For the best experience, after generating or updating a client, always ensure the kiota
dependencies are aligned with the versions recommended by the info command.

More information about the info command

Dependencies selection
In most cases, the bundle package and any additionally required package for the
language you're using brings most dependencies your application needs.

If your application requires a specific HTTP client, serialization library or format, you
need to at least add the abstractions and additionally required dependencies for the
language you're using. Additionally, you can select default implementations for HTTP
and serialization packages, or swap them for third party or your own implementations.

Additionally, your application might need to reference an authentication package


depending on the target API.

Abstractions
Any Kiota generated API client relies on a set of abstractions as a build and runtime
dependency, the application will require this dependency after a new client is generated.

More information about the abstractions package

The following table provides the list of abstractions package per language.
ノ Expand table

Language Package Name

C# Microsoft.Kiota.Abstractions

CLI Microsoft.Kiota.Abstractions

Go github.com/microsoft/kiota-abstractions-go

Java com.microsoft.kiota:microsoft-kiota-abstractions

PHP microsoft/kiota-abstractions

Python microsoft-kiota-abstractions

Ruby microsoft_kiota_abstractions

Swift Not released

TypeScript @microsoft/kiota-abstractions

Serialization
Kiota provides default implementation for diverse serialization formats. These
dependencies are required at runtime. Depending the application requirements those
implementations can be used as is, swapped or augmented with implementations from
the application, or swapped with third party implementations.

More information about the serialization packages

JSON
Media type: application/json

The following table provides the list of serialization package per language.

ノ Expand table

Language Package Name Relies on

C# Microsoft.Kiota.Serialization.Json System.Text.Json

CLI Microsoft.Kiota.Serialization.Json System.Text.Json

Go github.com/microsoft/kiota-serialization-json-go None
Language Package Name Relies on

Java com.microsoft.kiota:microsoft-kiota-serialization-json Gson

PHP microsoft/kiota-serialization-json None

Python microsoft-kiota-serialization-json None

Ruby microsoft_kiota_serialization_json None

Swift Not released None

TypeScript @microsoft/kiota-serialization-json None

Multipart
Media type: multipart/form-data

The following table provides the list of serialization package per language.

ノ Expand table

Language Package Name Relies on

C# Microsoft.Kiota.Serialization.Multipart None

CLI Microsoft.Kiota.Serialization.Multipart None

Go github.com/microsoft/kiota-serialization-multipart-go None

Java com.microsoft.kiota:microsoft-kiota-serialization-multipart None

PHP microsoft/kiota-serialization-multipart None

Python microsoft-kiota-serialization-multipart None

Ruby Not released None

Swift Not released None

TypeScript @microsoft/kiota-serialization-multipart None

Form
Media type: application/x-www-form-urlencoded

The following table provides the list of serialization package per language.
ノ Expand table

Language Package Name Relies on

C# Microsoft.Kiota.Serialization.Form None

CLI Microsoft.Kiota.Serialization.Form None

Go github.com/microsoft/kiota-serialization-form-go None

Java com.microsoft.kiota:microsoft-kiota-serialization-form None

PHP microsoft/kiota-serialization-form None

Python microsoft-kiota-serialization-form None

Ruby Not Released None

Swift Not released None

TypeScript @microsoft/kiota-serialization-form None

Text
Media type: text/plain

The following table provides the list of serialization package per language.

ノ Expand table

Language Package Name Relies on

C# Microsoft.Kiota.Serialization.Text None

CLI Microsoft.Kiota.Serialization.Text None

Go github.com/microsoft/kiota-serialization-text-go None

Java com.microsoft.kiota:microsoft-kiota-serialization-text None

PHP microsoft/kiota-serialization-text None

Python microsoft-kiota-serialization-text None

Ruby Not Released None

Swift Not released None

TypeScript @microsoft/kiota-serialization-text None


Http
Kiota provides a default request adapter implementation to convert abstract request
information objects created by the generated fluent API to HTTP requests. This
dependency is required at runtime. Depending the application requirements this
implementation can be used as is, swapped with another implementation from the
application, or swapped with a third party implementation.

More information about the HTTP package.

The following table provides the list of HTTP package per language.

ノ Expand table

Language Package Name Relies on

C# Microsoft.Kiota.Http.HttpClientLibrary System.Net.Http

CLI Microsoft.Kiota.Http.HttpClientLibrary System.Net.Http

Go github.com/microsoft/kiota-http-go net/http

Java com.microsoft.kiota:microsoft-kiota-http-okHttp None

PHP microsoft/kiota-http-guzzle None

Python microsoft-kiota-http None

Ruby microsoft_kiota_faraday None

Swift Not released None

TypeScript @microsoft/kiota-http-fetchlibrary None

Authentication
Depending on authentication requirements from the target REST APIs, your application
might additionally need an authentication dependency. Kiota provides default
implementation providers for specific scenarios. Depending the application
requirements those implementations can be used as is, swapped or augmented with
implementations from the application, or swapped with third party implementations.

More information about the authentication package

Azure Identity
These providers might be used for any API secured with Bearer token authorization for
which the identity platform is Entra Identity/Microsoft Identity Platform/Azure
Identity/Azure Active Directory.

The following table provides the list of authentication package per language.

ノ Expand table

Language Package Name Relies on

C# Microsoft.Kiota.Authentication.Azure Azure.Identity

CLI Microsoft.Kiota.Authentication.Azure Azure.Identity

Go github.com/microsoft/kiota-authentication- github.com/Azure/azure-sdk-for-
azure-go go/sdk/azidentity

Java com.microsoft.kiota:microsoft-kiota- com.azure:azure-identity


authentication-azure

PHP microsoft/kiota-authentication-phpleague phpleague

Python microsoft-kiota-authentication-azure azure-identity

Ruby microsoft_kiota_authentication_oauth oauth

Swift Not released None

TypeScript @microsoft/kiota-authentication-azure @azure/identity

Additional
Additional dependencies are required at build time and/or runtime.

The following table provides the list of additional package per language.

ノ Expand table

Language Package Name Type

C# None

CLI Microsoft.Kiota.CLI.Commons, System.CommandLine Build and runtime

Go None

Java jakarta.annotation:jakarta.annotation-api:2.0.0 Build

PHP None
Language Package Name Type

Python None

Ruby None

Swift None

TypeScript None

Bundle
To simplify dependencies management, kiota now offers bundle packages. These
packages contain the abstractions, the default serialization implementations, and the
default http implementation. Bundle packages can be used as an alternative to adding
references to those packages.

The following table provides the list of bundle package per language.

ノ Expand table

Language Package Name

C# Microsoft.Kiota.Bundle

CLI Microsoft.Kiota.Bundle

Go github.com/microsoft/kiota-bundle-go

Java com.microsoft.kiota:microsoft-kiota-bundle

PHP Not available

Python Not available

Ruby Not available

Swift Not available

TypeScript @microsoft/kiota-bundle
Kiota API client experience
Article • 06/20/2024

Create a resource
Here's an example of the basic read and write syntax for a resource.

C#

// An authentication provider from the supported language table


// https://github.com/microsoft/kiota#supported-languages, or your own
implementation
var authProvider = ;
var requestAdapter = new HttpClientRequestAdapter(authProvider);
var client = new ApiClient(requestAdapter);
var user = await client.Users["[email protected]"].GetAsync();

var newUser = new User


{
FirstName = "Bill",
LastName = "Brown"
};

await client.Users.PostAsync(newUser);

Access related resources


Resources are accessed via relation properties starting from the client object. Collections
of resources are accessible by an indexer and a parameter. Once the desired resource is
referenced, the supported HTTP methods are exposed by corresponding methods.
Deeply nested resource hierarchies are accessible by continuing to traverse
relationships.

C#

// An authentication provider from the supported language table


// https://github.com/microsoft/kiota#supported-languages, or your own
implementation
var authProvider = ;
var requestAdapter = new HttpClientRequestAdapter(authProvider);
var client = new ApiClient(requestAdapter);
var message = await client.Users["[email protected]"]
.MailFolders["Inbox"]
.Messages[23242]
.GetAsync();

The client object is a request builder object, and forms the root of a hierarchy of request
builder objects. These request builders can access any number of APIs that are merged
into a common URI space.

Requests can be further refined by providing query parameters. Each HTTP operation
method that supports query parameters accepts a lambda that can configure an object
with the desired query parameters.

C#

// An authentication provider from the supported language table


// https://github.com/microsoft/kiota#supported-languages, or your own
implementation
var authProvider = ;
var requestAdapter = new HttpClientRequestAdapter(authProvider);
var client = new ApiClient(requestAdapter);
var message = await client.Users["[email protected]"]
.Events
.GetAsync(q =>
{ q.StartDateTime = DateTime.Now;
q.EndDateTime = DateTime.Now.AddDays(7);
});

Using a configured query parameter object prevents tight coupling on the order of
query parameters and makes optional parameters easy to implement across languages.

Response with no schema


YAML

openapi: 3.0.3
info:
title: The simplest thing that works
version: 1.0.0
servers:
- url: https://example.org/
paths:
/speakers:
get:
responses:
200:
description: Ok
If the OpenAPI description doesn't describe the response payload, then it should be
assumed to be of content type application/octet-stream .

Client library implementations should return the response payload in the language-
native way of providing an untyped set of bytes. This response format could be a byte
array or some kind of stream response.

C#

Stream speaker = await apiClient.Speakers.GetAsync();

2 Warning

Support for stream responses identified by application/octet-stream are not


supported yet

Response with simple schema


YAML

openapi: 3.0.3
info:
title: Response with simple schema
version: 1.0.0
servers:
- url: https://example.org/
paths:
/speakers/{speakerId}:
get:
parameters:
- name: speakerId
in: path
required: true
schema:
type: string
responses:
200:
description: Ok
content:
application/json:
schema:
type: object
properties:
displayName:
type: string
C#

Speaker speaker = await apiClient.Speakers["23"].GetAsync();


string displayName = speaker.DisplayName;

Response with primitive payload


Responses with a content type of text/plain should be serialized into a primitive data
type. Unless a Schema object indicates a more precise data type, the payload should be
serialized to a string.

YAML

openapi: 3.0.3
info:
title: Response with primitive payload
version: 1.0.0
servers:
- url: https://example.org/
paths:
/speakers/count:
get:
responses:
200:
description: Ok
content:
text/plain:
schema:
type: number

C#

int speakerCount = await apiClient.Speakers.Count.GetAsync();

2 Warning

Support for text/plain responses are not supported yet

Filtered collection
YAML

openapi: 3.0.3
info:
title: Collection filtered by query parameter
version: 1.0.0
servers:
- url: https://example.org/
paths:
/speakers:
get:
parameters:
- name: location
in: query
required: false
schema:
type: string
responses:
200:
description: Ok
content:
application/json:
schema:
type: array
item:
$ref: "#/components/schemas/speaker"
components:
schemas:
speaker:
type: object
properties:
displayName:
type: string
location:
type: string

C#

IEnumerable<Speaker> speakers = await apiClient.Speakers.GetAsync(x => {


x.Location="Montreal"; });

Heterogeneous collection
Kiota client libraries automatically downcast heterogeneous collection items (or single
properties) to the target type if the following criteria are met. This way client library
users can easily access the other properties available on the specialized type.

A discriminator is present in the description


The response payload contains a matching mapping entry.

YAML
openapi: 3.0.3
info:
title: Heterogeneous collection
version: 1.0.0
servers:
- url: https://example.org/
paths:
/sessions:
get:
parameters:
- name: location
in: query
required: false
schema:
type: string
responses:
200:
description: Ok
content:
application/json:
schema:
type: array
item:
$ref: "#/components/schemas/session"
components:
schemas:
entity:
type: object
properties:
id:
type: string
session:
allof:
- $ref: "#/components/schemas/entity"
type: object
properties:
'@OData.Type':
type: string
enum:
- session
displayName:
type: string
location:
type: string
workshop:
allof:
- $ref: "#/components/schemas/session"
type: object
properties:
'@OData.Type':
type: string
enum:
- workshop
requiredEquipment:
type: string
presentation:
allof:
- $ref: "#/components/schemas/session"
type: object
properties:
'@OData.Type':
type: string
enum:
- presentation
recorded:
type: boolean

C#

IEnumerable<Session> sessions = await apiClient.Sessions.GetAsync();


List<Presentation> presentations = sessions.OfType<Presentation>().ToList();
// OfType is a native method that filters a collection based on the item
type returning a subset

Explicit Error Response


YAML

openapi: 3.0.3
info:
title: The simplest thing that works
version: 1.0.0
servers:
- url: https://example.org/
paths:
/speakers:
get:
responses:
"2XX":
description: Success
"4XX":
$ref: "#/components/responses/errorResponse"
"5XX":
$ref: "#/components/responses/errorResponse"
components:
responses:
errorResponse:
description: error
content:
application/json:
schema:
type: object
properties:
code:
type: string
message:
type: string

C#

try
{
var speakersStream = await apiClient.Speakers.GetAsync();
}
catch ( ServerException exception )
{
Console.WriteLine(exception.Error.Message)
}

2 Warning

Support for ServerException is not supported yet

Readability of the API client


Kiota is designed as a lightweight and fast API client generator that focuses on the
discovery, exploration, and calling of any HTTP API with minimal effort. The primary goal
of Kiota is to provide developers with a tool that simplifies the process of working with
APIs, rather than producing human-readable code. This approach allows Kiota to
support a wide range of languages and to handle the complexities of all APIs efficiently.
By keeping code readability as a non-goal, Kiota can prioritize performance, scalability,
and ease of use, ensuring that developers can focus on the functionality of their
applications rather than the underlying auto-generated code.

Developers are encouraged to treat Kiota-generated code as an opaque box that


reliably handles API interactions. Peeking into the auto-generated code is discouraged
because it is optimized for machines, not human interpretation, which could lead to
confusion and misinterpretation. Instead, developers should utilize the well-documented
interfaces provided by Kiota to interact with their APIs. This abstraction allows for a
cleaner development experience and ensures that any updates or changes to the Kiota
generator do not impact the developer's workflow. Trust in the robustness of Kiota's
output allows developers to dedicate their time to crafting the best possible
applications with the assurance that the API communication is handled efficiently in the
background.
Kiota abstractions
Article • 05/22/2024

On most platforms, there are a range of different HTTP client library implementations.
Developers often have preferences on which is the best implementation to meet their
needs. Kiota's objective is to make it easier to create an HTTP request object but
attempt to be agnostic of the library that makes the HTTP call. In order to decouple
Kiota from specific HTTP libraries, we defined a set of abstractions.

Kiota attempts to minimize the amount of generated code to decrease processing time
and reduce the binary footprint of the client libraries. In order to achieve this goal, we
attempt to put as much code as a possible into the core libraries. Kiota ships with a
default set of core libraries that include default implementations for HTTP transport,
authentication, and serialization. Replacing these core libraries with ones optimized for
your scenarios is a supported scenario.

The core libraries take care of all generic processing of HTTP requests. The service library
that Kiota generates is designed to create a strongly typed layer over the core libraries
to simplify the process of creating requests and consuming responses.

Requests
This section provides information about the types offered in the abstractions library the
generated result depends on which are related to executing requests.

Request adapter
The request adapter interface is the primary point where Kiota service libraries trigger
the creation of an HTTP request. The following code snippet is the C#
implementation .

C#

public interface IRequestAdapter


{
void EnableBackingStore(IBackingStoreFactory backingStoreFactory);

ISerializationWriterFactory SerializationWriterFactory { get; }

Task<ModelType> SendAsync<ModelType>(
RequestInformation requestInfo,
ParsableFactory<ModelType> factory,
IResponseHandler responseHandler = default,
Dictionary<string, ParsableFactory<IParsable>> errorMappings =
default) where ModelType : IParsable;

Task<IEnumerable<ModelType>> SendCollectionAsync<ModelType>(
RequestInformation requestInfo,
ParsableFactory<ModelType> factory,
IResponseHandler responseHandler = default,
Dictionary<string, ParsableFactory<IParsable>> errorMappings =
default) where ModelType : IParsable;

Task<ModelType> SendPrimitiveAsync<ModelType>(
RequestInformation requestInfo,
IResponseHandler responseHandler = default,
Dictionary<string, ParsableFactory<IParsable>> errorMappings =
default);

Task SendNoContentAsync(
RequestInformation requestInfo,
IResponseHandler responseHandler = default,
Dictionary<string, ParsableFactory<IParsable>> errorMappings =
default);
}

Kiota service libraries return the model type that is associated with an HTTP resource.
This behavior can be overridden by changing the responseHandler to do something
different than default behavior. One use of this approach is to change the response type
to be either a native HTTP response class, or return a generic API response class that
provides access to more underlying metadata.

7 Note

This interface is meant to support the generated code and not to be used by
application developers. Should you need to make arbitrary requests because they
are not part of the generated client, please use a native HTTP client instead as it will
be better suited for that purpose. Additionally you should obtain that native client
from the provided factory, or use the middleware factory to augment an existing
client. For more information about middleware, see Implementing middleware.

Request information
In order to enable Kiota service libraries to make requests, they need to be able to
accumulate information about the request and pass it to the core library. The request
information object is designed to do that. It only contains properties that are provided
by the request builders. As request builders get more sophisticated, so can the request
information class.
C#

public class RequestInformation


{
public string UrlTemplate { get; set; }
public Uri URI { get; set; }
public HttpMethod HttpMethod { get; set; }
public IDictionary<string, object> QueryParameters { get; set; } =
new Dictionary<string, object>(StringComparer.OrdinalIgnoreCase);
public IDictionary<string, string> Headers { get; set; } =
new Dictionary<string, string>(StringComparer.OrdinalIgnoreCase);
public IDictionary<string, object> PathParameters { get; set; } =
new Dictionary<string, object>(StringComparer.OrdinalIgnoreCase);
public Stream Content { get; set; }
public IEnumerable<IRequestOption> RequestOptions { get }
}

Response handler
When the request information is passed to the execution method from the fluent style
API, the core library does all of the default hard work. A custom response handler can
change the behavior of and access the native response object.

C#

public interface IResponseHandler


{
Task<ModelType> HandleResponseAsync<NativeResponseType, ModelType>(
NativeResponseType response,
Dictionary<string, ParsableFactory<IParsable>> errorMappings);
}

Failed responses handling


Kiota implements default error handling. If a response handler is passed, the error
detection logic is bypassed to allow the caller to implement whichever custom handling
they desire.

Backing store
This interface defines the members a backing store needs to implement for a model to
be able to store its field values in a custom data store instead of using fields.

C#
public interface IBackingStore
{
T Get<T>(string key);
void Set<T>(string key, T value);
IEnumerable<KeyValuePair<string, object>> Enumerate();
IEnumerable<string> EnumerateKeysForValuesChangedToNull();
string Subscribe(Action<string, object, object> callback);
void Subscribe(Action<string, object, object> callback, string
subscriptionId);
void Unsubscribe(string subscriptionId);
void Clear();
bool InitializationCompleted { get; set; }
bool ReturnOnlyChangedValues { get; set; }
}

In-memory backing store


Default implementation that stores information in a map/dictionary in memory that
enables for dirty tracking of changes on a model and reuse of models.

Authentication
See the authentication documentation page for information on interfaces that allow for
implementing authentication libraries.

Serialization
See the serialization documentation page for information on interfaces that allow for
implementing serialization libraries.
Authentication with Kiota API clients
Article • 05/24/2024

Most REST APIs are protected through some kind of authentication and authorization
scheme. The default HTTP core services provided by Kiota require an authentication
provider to be passed to handle authentication concerns.

Authentication provider interface


Authentication providers are required to implement the following contract/interface
defined in the abstraction library.

.NET

public interface IAuthenticationProvider


{
Task AuthenticateRequestAsync(
RequestInformation request,
Dictionary<string, object>? additionalAuthenticationContext =
null,
CancellationToken cancellationToken = default);
}

The request parameter is the abstract request to be executed. The return value
must be a Task that completes whenever the authentication sequence completes
and the request object is updated with the authentication/authorization
information.

Access token provider interface


Implementations of this interface can be used in combination with the
BaseBearerTokenAuthentication provider class to provide the access token to the

request before it executes. They can also be used to retrieve an access token to build
and execute arbitrary requests with a native HTTP client.

.NET

public interface IAccessTokenProvider


{
AllowedHostsValidator AllowedHostsValidator { get; }

Task<string> GetAuthorizationTokenAsync(
Uri uri,
Dictionary<string, object>? additionalAuthenticationContext =
null,
CancellationToken cancellationToken = default));
}

In GetAuthorizationTokenAsync , the uri parameter is the URI of the abstract


request to be executed. The return value is a Task that holds the access token, or
null if the request could/should not be authenticated.

Allowed hosts validator


This utility class is in charge of validating the host of any request is present on an
allowlist. The validator is used by the base access token provider to check whether it
should return a token to the request.

Base bearer token authentication provider


A common practice in the industry for APIs is to implement authentication and
authorization via the Authorization request header with a bearer token value.

If you want to add support for more authentication providers for that scheme, Kiota
abstractions offer a class to use in combination with your own implementation of an
access token provider. You only need to implement the access token acquisition
sequence and not the header composition and addition.

.NET

public class BaseBearerTokenAuthenticationProvider


{
public BaseBearerTokenAuthenticationProvider(IAccessTokenProvider
tokenProvider) {

}
}

7 Note
Please leverage the same approach if you want to add support for new
authentication schemes where the authentication scheme composition logic is
implemented in a base class so it can be reused across multiple providers.

Microsoft Entra Identity authentication


provider
The Azure authentication package contains an authentication provider that relies on
Microsoft Entra Identity to get access tokens and implements bearer authentication. It
can effectively be used for any client making requests to APIs secured by the Microsoft
Entra Identity Platform.

Anonymous authentication provider


Some APIs don't require any authentication and can be queried anonymously. For this
scenario, the abstractions packages provide an AnonymousAuthenticationProvider , which
serves as a placeholder and performs no operation.

API key authentication provider


Some APIs simply rely on an API key for authentication in the request query parameters
or in the request headers. For this scenario, the abstractions packages provide an
ApiKeyAuthenticationProvider .

This provider allows you to:

Set the name of the request header/query parameter. (for example Authorization )
Set the value of the request header/query parameter. (for example Basic
base64encodedValue )

Choose whether the provided name and value are used for a request header or for
a query parameter.

7 Note

This authentication provider does not perform any encoding of the key or the
value, if the authentication scheme requires any encoding, it needs to be
performed before the values are passed to the provider. For example with basic
authentication, you'll need to base64 encode the "userId:password" pair before
passing it to the provider.

Choose your authentication provider


Does the target API require no authentication? Use the anonymous authentication
provider.
Is the API protected by Microsoft Identity Platform? Use the Azure Identity
authentication provider.
Is the authentication implemented via an API key in the query parameters or
headers? Use the API key authentication provider.
Is the authentication implemented via a bearer token in the Authorization header?
Use a custom access token provider with the Base bearer token authentication
provider.
Anything else, use a custom authentication provider.

Design considerations
The default request adapters used by generated clients to make an HTTP request
require an authentication provider as a constructor parameter, and call the authenticate
request method themselves. An alternative could be to use HTTP client middleware
handlers instead. This approach was a deliberate design decision to:

Lead application developer to make a conscious choice about authenticating with


the API.
Enable reusability through interfaces defined to work with Request Information,
limiting interdependencies.
Enable dependency injection scenarios.
Kiota request builders
Article • 05/24/2024

The primary goal of a request builder class is to enable a developer to easily construct
an HTTP request. By using a set of related request builder classes, we can enable a
developer to construct an HTTP request for any resource exposed by an HTTP API.

There are three phases of constructing the HTTP request. Building the URL, specifying
query parameters, and selecting the HTTP method.

Building the URL


By creating properties on request builder classes, the developer can effectively construct
a URL by navigating the hierarchy of request builders, aided by the editor's
autocomplete.

The URL for the request is built using an RFC6570 URL Template and providing its
parameters.

C#

var todo = await todoClient.ToDos["<todoId>"].GetAsync();


var responsiblePerson = await todoClient.ToDos["
<todoId>"].AssignedTo.GetAsync();

Each request builder class exposes the set of HTTP methods that are supported on that
resource. Each operation method allows setting and configuring query parameters,
setting HTTP headers, and providing a custom response handler.

Request builders are generated into a subnamespace following the API path they refer
to.

Default members
Each request builder contains a default set of members to help build the URL and
ultimately the requests.

Path parameters
The path parameters dictionary/map contains a list of the parameters for the URL
template. The fluent API builds the URL using those parameters, and the parameters are
passed along from request builder to request builder.

Considering the following sample:

C#

var requestBuilder =
todoClient.TaskLists["taskListId"].ToDos["todoId"].AssignedTo;

Path parameters for the requestBuilder variable contain two entries:

task_list_id of value taskListId .

todo_id of value todoId .

When the request adapter executes the request, it resolves all parameters (path and
query) against the URL template. The base URL parameter value is also provided at that
time.

UrlTemplate
The request builder has a Url Template property. This template is resolved using the
path and query parameters to get the definitive URL to use for the request.

Consider the following sample:

C#

var requestBuilder =
todoClient.TaskLists["taskListId"].ToDos["todoId"].AssignedTo;

The URL template for the requestBuilder looks something like


{+baseurl}/taskLists/{task_list_id}/toDos/{todo_id}/assignedTo{?select,expand} .

7 Note

The query parameters will only be present if included in the OpenAPI description.

The request adapter provides the path and query parameters, and the base URL before
the request is executed.

RequestAdapter
In order to execute any request, the request builder needs to have access to a request
adapter.

This request adapter is passed from request builder to request builder when using the
fluent style API. This object holds most of the client configuration, serialization, and
deserialization capabilities and more.

Constructors
Request builders offer two different constructors (one if the target language supports
types unions).

C#

public UsersRequestBuilder(Dictionary<string, object> pathParameters,


IRequestAdapter requestAdapter);
public UsersRequestBuilder(string rawUrl, IRequestAdapter requestAdapter)

The first constructor (dictionary) is meant to be used by the fluent API infrastructure to
pass in the path parameters from previous request builders.

The second constructor is meant to be used by developers when they need to use the
request builder with a raw URL they already have. Multiple scenarios require such use:
delta links, paging through collections, resuming from going offline...

7 Note

Once the raw URL is set for a given request builder, and subsequently for a given
request, the path and query parameters on the request information will be reset,
and the request adapter will not attempt to resolve the template anymore, it will
read the provided raw URL as is.

Navigation members
Besides executing requests and getting the deserialized result, request builders also act
as the foundation for the fluent style API.

Properties
Properties are used for navigation path segments that declare no parameters.
In the following example:

C#

var requestBuilder =
todoClient.TaskLists["taskListId"].ToDos["todoId"].AssignedTo;

Two navigation properties are in use in this fluent style API call: .TaskLists and .ToDos

The underlying URL template looks like


{+baseurl}/taskLists/{task_list_id}/toDos/{todo_id}/assignedTo{?select,expand} ,

where both the taskLists and toDos path segments don't require any parameter.

7 Note

If the target language doesn't support auto-property getters ( get keyword in C# or


TypeScript) a method with no parameter will be used instead.

This property always returns a value (non-null) and never throws an exception.

Indexers
Indexers are used for navigation path segments that declare a single unnamed
parameter. This design choice was made as APIs often use that pattern for indexable
collections endpoints.

In the following example:

C#

var requestBuilder =
todoClient.TaskLists["taskListId"].ToDos["todoId"].AssignedTo;

Two indexers are used where brackets are present.

The underlying URL template looks like


{+baseurl}/taskLists/{task_list_id}/toDos/{todo_id}/assignedTo{?select,expand} ,

where both the {task_list_id} and {todo_id} path segments are single unnamed path
parameters.

It's important to note that even if an endpoint to index in the collection


{+baseurl}/taskLists/{task_list_id} doesn't exist, it doesn't affect the generation of
the fluent style API for the endpoint. If that indexing endpoint does exist, the only effect
is to the parent request builder that exposes a Get method.

7 Note

For languages that do not support indexers, a method with a suffix and a single
parameters is used instead.

Java

var requestBuilder =
todoClient.taskLists().byTaskListId("taskListId").toDos().byToDoId("todoId")
.assignedTo;

This indexer always returns a value (non-null) and never throws an exception.

Method with parameters


Methods with parameters are used when path segments contain named parameters or
multiple parameters.

In the following example:

C#

var requestBuilder =
todoClient.TaskLists["taskListId"].GetReminders("startDate", "endDate");

One method with two parameters is present.

The underlying URL template looks like


{+baseurl}/taskLists/{task_list_id}/getReminders(startDate='{startDate}',endDate='{

endDate}')/{?select,expand} , when the getReminders path segment contains two

named parameters startDate and endDate .

This method with parameters always returns a value (non-null) and never throw an
exception.

WithUrl
Request builders offer a WithUrl method to facilitate the interoperability between the
fluent API surface and raw URLs coming from other sources.
Let's assume the following call returns a URL to the next page, a common practice for
REST APIs.

CSharp

var page1 = await client.Customers["Jane"].Orders.GetAsync();


page1.NextPageUrl;

You can still use the fluent API and get the benefits of autocompletion, compile-time
validation and more by using the WithUrl method.

CSharp

var page1 = await


client.Customers["Jane"].Orders.WithUrl(page1.NextPageUrl).GetAsync();

7 Note

In this example, any path parameter (any value passed before the WithUrl method)
as well as any query parameter (passed to the executor/GetAsync method) will be
ignored.

[!INFO] Always use the WithUrl method in the right-most position before the
executor method (GetAsync), this way the data types for the request and response
bodies will match what you expect.

Request building and execution


Once the request path is built using the fluent style API, request builders provide
methods to generate and execute requests.

Request generators
Request generator methods follow this Create{HTTPMethodName}RequestInformation
naming convention. And accept the following parameters:

body: the request body if supported.


query parameters: an object or callback to set the request query parameters.
headers: an object or callback to set the request headers.
options: a list of request options to set for the request. The middleware pipeline is
the primary consumer of these options.
These methods return an abstract request information object that can be passed to the
request adapter for execution, or used with other tasks (for example, batching of
requests).

Request executors
Request executor methods follow this {HTTPMethodName}{Suffix} naming convention,
where a suffix is applied when it makes sense for the target language (for example,
GetAsync in C#). These methods accept the same parameter set as the request
generators as they call into these methods to generate the request and then pass the
request information to the request adapter for execution. They provide an extra
parameter:

responseHandler: this parameter might be used to bypass the standard response


handling for the current request and access the native HTTP response object.
Query parameters and request headers
Article • 05/24/2024

Kiota API clients provide a fluent API you can use to add query parameters or headers to
requests before sending them out to the service.

Query parameters
Kiota generates a type for each operation to reflect the query parameters in the API
description. The application code can then use that type to customize the request and
benefit from compile time validations.

Consider the following sample:

C#

var result = await todoClient


.TaskLists["taskListId"]
.ToDos["todoId"]
.AssignedTo
.GetAsync(x => x.QueryParameters.Select = new string[] { "id", "title"
});

The URL template for the request builder looks something like
{+baseurl}/taskLists/{task_list_id}/toDos/{todo_id}/assignedTo{?select,expand} .

And the resulting URI is


https://contoso.com/taskLists/taskListId/toDos/todoId/assignedTo?select=id,title

7 Note

Enumerations in query parameters are treated as strings.

Request headers
Kiota doesn't generate a type specific to the operation for request headers. The HTTP
specification defines a large number of standard headers, and vendors can come up
with custom headers. Projecting a type for request headers would be redundant and
inflate the amount of code being generated.
The application code can use the fluent API to customize headers sent to the service via
a generic Headers type.

C#

var result = await todoClient


.TaskLists["taskListId"]
.ToDos["todoId"]
.AssignedTo
.GetAsync(x => x.Headers.Add("Contoso-Custom", "foo", "bar"));

The code above results in the following request.

HTTP

GET ...
Contoso-Custom: foo, bar

The request adapter folds headers with multiple values automatically.

7 Note

Header values are limited to strings and the application must serialize other
types.
Serialization with Kiota API clients
Article • 10/11/2024

APIs rely on some serialization format (JSON, YAML, XML...) to be able to receive and respond to requests from their
clients. Kiota generated models and request builders aren't tied to any specific serialization format or implementation
library. To achieve this, Kiota generated clients rely on two key concepts:

Models rely on a set of abstractions available in the abstractions package and implemented in a separate package
for each format.
Models self-describe their serialization/deserialization logic. For more information about models, see Kiota API
models.

Additional data holder


The additional data holder interface defines members implemented by models that might include properties in API
responses that aren't described in the OpenAPI description of the API. As the type information for these types is unknown
at generation time, default serializers will make a best effort attempt during deserialization using UntypedNode types.

C#

public interface IAdditionalDataHolder


{
IDictionary<string, object> AdditionalData { get; set; }
}

Parsable
The parsable interface defines members that are required in models in order to be able to self serialize/deserialize itself.
You can find a detailed description of those members in the models documentation page.

C#

public interface IParsable


{
IDictionary<string, Action<T, IParseNode>> GetFieldDeserializers<T>();
void Serialize(ISerializationWriter writer);
IDictionary<string, object> AdditionalData { get; set; }
}

Parsable factory
Parsable factory defines the structure for models factories creating parsable objects according to their derived types or
the discriminator value present in the payload.

CSharp

public delegate T ParsableFactory<T>(IParseNode node) where T : IParsable;

Parse node
The parse node interface defines members that are required in a deserialization library. It mostly acts as an abstractions
and mapping layer between the methods that models' deserializers call, and the library in use to deserialize the payload.
It heavily relies on recurrence programming design, and the corresponding factory instantiates the implementing class.

On top of the mapping methods, parse node offers two events that must be called during the deserialization process by
implementers:

OnBeforeAssignFieldValues : when the target object is created and before fields of the object are assigned.

OnAfterAssignFieldValues : when the target object field values are assigned.

Parse node factory


The parse node factory interface defines members that are required in a deserialization library to instantiate a new parse
node implementer from a raw payload. It also describes which MIME type this factory/parse node applies to.

Whenever the request adapter needs to deserialize a response body, it looks for a factory that applies to that result based
on the HTTP response Content-Type header, instantiate a new parse node for the corresponding type using the factory,
and call in the parse node to get the deserialized result.

Parse node factory registry


This class is a registry for multiple parse node factories that are available to the request adapter. Implementers for new
deserialization libraries or formats don't need to do anything with this type other than requesting users to register their
new factory at runtime with the provided singleton to make it available for the Kiota client.

Parse node proxy factory


Parse node offers multiple events that are called during the deserialization sequence. This proxy facilitates the registration
of such events with existing parse nodes. Implementers for new deserialization libraries or formats don't need to do
anything with this type other than requesting users to wrap their factories with it as well should they be subscribing to
deserialization events.

Serialization writer
The serialization writer interface defines members that are required in a serialization library. It mostly acts as an
abstractions and mapping layer between the methods that models' serializers call, and the library in use to serialize the
payload. The corresponding factory instantiates the implementing class.

On top of the mapping methods, serialization writer offers three events that must be called during the serialization
process by implementers:

OnBeforeObjectSerialization : called before the serialization process starts.


OnStartObjectSerialization : called right after the serialization process starts.

OnAfterObjectSerialization : called after the serialization process ends.

Serialization writer factory


The serialization writer factory interface defines members that are required in a serialization library to instantiate a new
serialization writer implementer. It also describes which MIME type this factory/serialization writer applies to.

Whenever the request adapter needs to serialize a request body, it looks for a factory that applies to that result based on
the HTTP request Content-Type header, instantiate a serialization writer for the corresponding type using the factory, and
call in the serialization writer to get the serialized result.
Serialization writer factory registry
This class is a registry for multiple serialization writer factories that are available to the request adapter. Implementers for
new serialization libraries or formats don't need to do anything with this type other than requesting users to register their
new factory at runtime with the provided singleton to make is available for the Kiota client.

Serialization writer proxy factory


Serialization writer offers multiple events that are called during the serialization sequence. This proxy facilitates the
registration of such events with existing serialization writers. Implementers for new serialization libraries or formats don't
need to do anything with this type other than requesting users to wrap their factories with it as well should they be
subscribing to serialization events.

Serialization helpers
Automatic serialization and the decoupling between the serialization information and the serialization format can make
some serialization scenarios more complex. For that reason, Kiota abstractions libraries offer serialization helpers to
unblock such scenarios.

It's important to use the Kiota serialization infrastructure and not the native serialization capabilities from a library as:

it supports down-casting to a derived type from discriminator. (for example, getting a student with extra fields and
not just a user)
it supports complex property types. (duration, dates, etc.)
it doesn't rely on any runtime reflection of the code.

Let's assume the API contains a User model.

C#

cs

using Microsoft.Kiota.Abstractions.Serialization;

var myUser = new User {


FirstName = "Jane",
LastName = "Smith"
};

var result = await KiotaJsonSerializer.SerializeAsStringAsync(myUser);


// gives us {"firstName":"Jane","lastName":"Smith"}
// alternatively if you need to serialize to a different content type you can use this helper instead
// var result = await KiotaSerializer.SerializeAsStringAsync("application/json", myUser);

var deserializedUser = await KiotaJsonSerializer.DeserializeAsync(result,


User.CreateFromDiscriminatorValue);
// returns the deserialized value

Types mapping
The table below describes the mapping between OpenAPI type-format pairs and language types. Any format which
does not have an entry in the table will use the default type for the corresponding OpenAPI type.

ノ Expand table
OpenAPI OpenAPI C# Type Go Type Java Type TypeScript PHP Type Python Default
type format Type Type Mapping
for
OpenAPI
Type

number uint8 sbyte int8 Short number int int

number int8 byte int8 Byte number int int

number int32 int32/int int32 Integer number int int

number int64 int64/long int64 Long number int int

number float float/single float32 Float number float float

number double double float64 Double number float float Yes

number decimal decimal float64 BigDecimal number float float

string N/A string string String string string string Yes

string uuid Guid UUID UUID Guid string UUID

string date-time DateTimeOffset time OffsetDateTime Date DateTime datetime

string date Kiota Date Kiota Date LocalDate Kiota Date Kiota Date date
Only Only

string time Kiota Time Kiota Time LocalTime Kiota Time Kiota Time time
Only Only

string duration TimeSpan Kiota ISO Kiota Kiota DateInterval timedelta


Duration PeriodAndDuration Duration

string binary Stream byte[] byte[] ArrayBuffer StreamInterface bytes

string base64url byte[] byte[] byte[] ArrayBuffer StreamInterface bytes

bool N/A bool bool Boolean Boolean bool bool

7 Note

The C# Date and Time types also provide operators so they are fully convertible from or to DateOnly and TimeOnly.

Untyped Node
In scenarios where the type information for a property/parameter in the input OpenAPI description is not present, Kiota
will generate with the generic UntypedNode type which represent that the property/parameter could be a primitive,object
or a collection. As the type information is unknown at compile/generation time, the UntypedNode object can be parsed at
runtime by calling the GetValue() methods of the derived types to get the native representation of the node.

The example below shows a sample generic function that parses an UntypedNode object parse out the various elements
inside it.

C#

cs

using Microsoft.Kiota.Abstractions.Serialization;

private static void ParseUntypedNode(UntypedNode untypedNode)


{
switch (untypedNode)
{
case UntypedObject untypedObject:
Console.WriteLine("Found object value: ");
foreach (var (name, node) in untypedObject.GetValue())
{
Console.WriteLine("Property Name: " + name);
ParseUntypedNode(node);// handle the nested nodes
}
break;

case UntypedArray untypedArray:


Console.WriteLine("Found array value: ");
foreach (var item in untypedArray.GetValue())
{
Console.WriteLine("Array Item: ");
ParseUntypedNode(item);// handle the nested nodes
}
break;

case UntypedString:
case UntypedBoolean:
case UntypedDouble:
case UntypedFloat:
case UntypedInteger:
case UntypedLong:
case UntypedNull:
string scalarAsString = KiotaJsonSerializer.SerializeAsString(untypedNode);
Console.WriteLine("Found scalar value : " + scalarAsString);
break;
}
}

7 Note

As objects of UntypedNode implement the IParsable interface it is possible to use the serialization helpers from Kiota
to serialize them to a string/stream and parse it with a preferable parser based on scenario.

The next example below shows how one can use the UntypedNode objects to build a payload that sends a multi-
dimensional array(tabular data).

C#

cs

using Microsoft.Kiota.Abstractions.Serialization;

var table = new UntypedArray(new List<UntypedNode>


{
new UntypedArray(new List<UntypedNode>{ new UntypedString("1"),new UntypedString("2"), new
UntypedString("3"),}),// row 1
new UntypedArray(new List<UntypedNode>{ new UntypedString("4"),new UntypedString("5"), new
UntypedString("6"),}),// row 2
});

var jsonString = KiotaJsonSerializer.SerializeAsString(table);


Implementing middleware
Article • 05/24/2024

By registering custom middleware handlers, you can perform operations before a


request is made. For example, auditing and filtering the request before the client sends
it.

Middleware
Create your middleware class and add your business requirements. For example, you
might wish to add custom headers to the request or filter headers and content.

C#

public class SaveRequestHandler : DelegatingHandler


{
protected override async Task<HttpResponseMessage> SendAsync(
HttpRequestMessage request, CancellationToken cancellationToken)
{
var jsonContent = await
request.Content.ReadAsStringAsync(cancellationToken);
Console.WriteLine($"Request: {jsonContent}");

return await base.SendAsync(request, cancellationToken);


}
}

Register middleware
Create a middleware handlers array and use the existing middleware already
implemented within Microsoft.Kiota.HttpClientLibrary that includes existing handlers
like retry, redirect, and more.

C#

var handlers = KiotaClientFactory.CreateDefaultHandlers();


handlers.Add(new SaveRequestHandler());

Next you need to create a delegate chain so the middleware handlers are registered in
the right order.

C#
var httpMessageHandler =
KiotaClientFactory.ChainHandlersCollectionAndGetFirstLink(
KiotaClientFactory.GetDefaultHttpMessageHandler(),
handlers.ToArray());

Finally, create a request adapter using an HttpClient with the message handler. This
adapter can then be used when submitting requests from the generated client. This
design means different adapters/middleware can be used when calling APIs and
therefore gives flexibility to how and when a middleware handler is used.

C#

var httpClient = new HttpClient(httpMessageHandler!);


var adapter = new HttpClientRequestAdapter(authProvider,
httpClient:httpClient);
var client = new PostsClient(adapter); // the name of the client will vary
based on your generation parameters
Kiota API models
Article • 06/13/2024

The primary goal of Kiota's generated models is to enable a developer to easily craft
request payloads and get results as high levels objects. These models eliminate the need
for developers to define their own types and/or implement serialization/deserialization.

Components versus inline models


All models declared as components are generated under a models subnamespace. If
models/components are namespaced components/modelA , components/ns1/modelB , the
namespaces are included as subnamespaces of the models namespace.

All models declared inline with an operation are generated under the namespace of the
operation, next to the request builder that uses it. As a reminder, all request builders are
put in namespaces according to the path segment they refer to.

Inheritance
Models in an allOf schema declaration inherit from each other. The uppermost type in
the collection is the greatest ancestor of the chain.

allOf interpretation rules


The following table describes how kiota will project any schema with allOf entries when
processing an API description:

ノ Expand table

Number of Number Number Total Result


peer of inline referenced number
properties schemas schemas of
schemas

0 0 0 0 Ignored/Invalid

0 0 or 1 0 or 1 1 Ignored, will process the only allOf


entry instead and use the original
schema's description and name.

1 or more 0 0 0 Class/interface without a parent type.


Number of Number Number Total Result
peer of inline referenced number
properties schemas schemas of
schemas

0 1 or more 1 * Class/interface with merged


properties from the inline schemas
and a parent type from the referenced
schema.

1 or more 0 1 1 Class/interface with properties from


the current schema and a parent type
from the referenced schema.

1 or more 1 0 1 Class/interface with properties from


the current schema and a parent type
from the inline schema.

0 0 1 1 Class/interface with properties from


the referenced schema and without a
parent type.

0 1 0 1 Class/interface with properties from


the inline schema and without a
parent type.

1 or more 1 1 2 If the referenced schema has


properties and the inline schema does
not, class/interface with properties
from the current schema and a parent
type from referenced schema.

1 or more 1 1 2 If the inline schema has properties


and the referenced schema does not.
class/interface with properties from
the current schema and a parent type
from the inline schema.

1 or more 1 1 2 If both the inline schema and the


referenced schema have properties:
class/interface with properties from
the current schema merged with the
inline schema and a parent type from
the referenced schema.

1 or more 1 1 2 If none of the inline and the


referenced schema have properties.
Class/interface without a parent type.

* 1 or more 0 or 1 * Class/interface with properties from


the main schema, and allOf entries
Number of Number Number Total Result
peer of inline referenced number
properties schemas schemas of
schemas

merged.

* 0 or 1 1 or more * Class/interface with properties from


the main schema, and allOf entries
merged.

7 Note

These rules are applied to allOf entries recursively enabling multi-level inheritance.

Faceted implementation of oneOf


oneOf specifies a type union (exclusive) where the response can be of one of the

specified child schemas. Kiota implements that specification by generating types for all
the child schemas and using a union type for languages that support it or a wrapper
type with one property per type in the union.

The deserialized result is either one of the types of the union or the wrapper type with
only one of the properties being non-null.

When a oneOf keyword has at least one child schema that is of type object then the
OpenAPI discriminator keyword MUST be provided to identify the applicable schema.

Child schemas that are arrays or primitives use the equivalent type language parser to
attempt to interpret the input value. The first primitive schema that doesn't fail to parse
is used to deserialize the input.

Nested oneOf keywords are only supported when the child schema uses a $ref to
enable naming the nested type.

Faceted implementation of anyOf


anyOf specifies a type intersection (inclusive union) where the response can be of any of

the specified child schemas. Kiota implements that specification by generating types for
all the child schemas and using an intersection type for languages that support it or a
wrapper type with one property per type in the union.
The deserialized result is either an intersection type or the wrapper type with one or
more of the properties being non-null.

Where there are common properties in the child schemas, the corresponding value in
the input is deserialized into the first child schema with the common properties.

Heterogeneous collections
For any collection of items that rely on allOf , anyOf , or oneOf , it's possible the result
contains multiple types of objects.

For example, think of an endpoint returning a collection of directory objects (abstract).


Directory object is derived by User and Group, and each type has its own set of
properties. In this case, the endpoint is documented as returning a collection of
directory objects and return in reality a mix of users and groups.

Kiota supports discriminators by down-casting the returned object during


deserialization. The down-casting is supported by using allOf and a discriminator
property. Kiota supports both implicit and explicit discriminator mappings. Using oneOf
to constrain derived types is not supported as Kiota interprets that as an intersection
type.

For inline schemas, the type name follows these conventions.

Last segment name + operation + requestBody


Last segment name + operation + response
Parent type name + member + ID (sequential)

Example 1 - using allOf and discriminator


JSON

{
"microsoft.graph.directoryObject": {
"allOf": [
{ "$ref": "#/components/schemas/microsoft.graph.entity" },
{
"title": "directoryObject",
"required": ["@odata.type"],
"type": "object",
"properties": {
"@odata.type": {
"type": "string",
"default": "#microsoft.graph.directoryObject"
}
}
}
],
"discriminator": {
"propertyName": "@odata.type",
"mapping": {
"#microsoft.graph.user":
"#/components/schemas/microsoft.graph.user",
"#microsoft.graph.group":
"#/components/schemas/microsoft.graph.group"
}
}
},
"microsoft.graph.user": {
"allOf": [
{ "$ref": "#/components/schemas/microsoft.graph.directoryObject" },
{
"title": "user",
"type": "object"
}
]
},
"microsoft.graph.group": {
"allOf": [
{ "$ref": "#/components/schemas/microsoft.graph.directoryObject" },
{
"title": "group",
"type": "object"
}
]
}
}

Example 2 - using oneOf to constrain the derived types -


not supported
JSON

{
"type": "object",
"title": "directoryObject",
"oneOf": [
{
"type": "object",
"title": "user"
},
{
"type": "object",
"title": "group"
}
]
}
Default members
In addition to all the described properties, a model contains a set of default members.

Factory method
The factory method (static) is used by the parse node implementation to get the base or
derived instance according to the discriminator value. Consider an operation that
describes returning a Person model, and the Person model has discriminator
information (mapping + property name). If the response payload contains one of the
mapped values (for example, Employee ), the deserializer generates the derived Employee
type instead of the base Person type. This way API client users can take advantage of
the properties that are defined on this specialized model.

C#

public static new Person CreateFromDiscriminatorValue(IParseNode parseNode)


{
_ = parseNode ?? throw new ArgumentNullException(nameof(parseNode));
var mappingValueNode = parseNode.GetChildNode("@odata.type");
var mappingValue = mappingValueNode?.GetStringValue();
return mappingValue switch {
"#api.Employee" => new Employee(),
_ => new Person(),
};
}

Field deserializers
The field deserializers method or property contains a list of callbacks to be used by the
parse node implementation when deserializing the objects. Kiota relies on automatic
serialization, where each type knows how to serialize/deserialize itself thanks to the
OpenAPI description. A significant advantage of this approach it to avoid tying the
generated models to any specific serialization format (JSON, YAML, XML,...) or any
specific library (because of attributes/annotations these libraries often require).

7 Note

Any property found in the response payload and which does not match an entry in
the field deserializers (casing included), will be stored in the additional data
collection.
Serialize method
Like the field deserializers, the model's serialize method uses the passed serialization
writer to serialize itself.

Additional data
Dictionary/Map that stores all the additional properties that aren't described in the
schema.

7 Note

The additional data property is only present when the OpenAPI description for the
type allows it and if the current model doesn't inherit a model which already has
this property.

Backing store
When present, the property values are stored in this backing store instead of using fields
for the object. The backing store allows multiple things like dirty tracking of changes,
making it possible to get an object from the API, update a property, and send that
object back with only the changed property and not the full object. Additionally it's used
for integration with custom data sources.

7 Note

The backing store is only added if the target language supports it and when the -b
parameter is passed to the CLI when generating the models.

Properties and accessors name mangling


To produce a more idiomatic output for specific languages, mangling is applied to the
properties names and/or accessors. The following table describes the mangling rules
being applied for each language:

ノ Expand table

Language Property name Property accessors

CSharp PascalCase -
Language Property name Property accessors

CLI PascalCase -

Go - PascalCase

Java camelCase camelCase

PHP - camelCase

Python snake_case snake_case

Ruby snake_case snake_case

Swift - -

TypeScript - camelCase

Enumerations
Kiota only projects enum models when the schema type is string, as projecting enums
for boolean or number types doesn't add much value.

Additionally, you can:

Control the enum symbol name using the x-ms-enum extension. more information
Control whether the projected enum should be flaggable through the x-ms-enum-
flags extension. more information

During deserialization, if an unknown enum member value is encountered, the client


throws an exception. This design decision was made to ensure client applications fail as
early as possible when the client might need to be refreshed or when the API
description is inaccurate.
HTTP status code handling with Kiota
API clients
Article • 05/24/2024

Kiota uses the specified HTTP status codes in OpenAPI descriptions to determine return
types. It also attempts to handle cases where APIs return a status code other than the
one specified in the OpenAPI description.

Generation
During API client generation, Kiota follows these rules to map status codes described by
the OpenAPI description. The following table is ordered, which means the first rule that
matches is used during generation.

ノ Expand table

Code Schema is present Result type

200-203 yes model class

2XX yes model class

204, 205 N/A void

201, 202 no void

200, 203, 206 no stream

2XX no stream

7 Note

For a schema to be considered present, it must be part of a structured content


response ( application/json , application/xml , text/plain , text/xml , text/yaml ).

Runtime status code handling


At runtime, the client can encounter response status codes that differ from what was
originally documented due to how HTTP works. Default request adapter
implementations follow these rules:
ノ Expand table

Expected return type Response status code Response body is present Returned value

model class 200-203 yes deserialized value

model class 200-202, 204, 205 no null

void 200-205 N/A void

stream 200-203, 206 yes stream

stream 200-205 no null


Error handling with Kiota API clients
Article • 05/24/2024

Kiota API clients include error types for errors defined in OpenAPI descriptions.

Error types mapping


The abstractions library for each language defines an API exception type (or error) which
inherits or implements the default error/exception type for the language. Kiota
generates types for schemas mapped to HTTP specific error status codes (400-600) or to
ranges (4XX, 5XX).

7 Note

If the error schema is an allOf , Kiota will flatten all the allOf entries recursively
into the generated type as most languages do not support multiple parents
inheritance.

This mapping of codes to types is passed to the request adapter as a dictionary/map so


it can be used at runtime and is specific to each endpoint. An error mapping is only
considered valid if the response has a schema of type object and at least one field. All
generated error/exception types inherit from the base API exception/error defined in the
abstractions library.

Runtime behavior
At runtime, if the API returns an error status code, the request adapter follows this
sequence:

1. If a mapping is present for the specific status code and if the response body can be
deserialized to that type, deserialize then throw.
2. If a mapping is present for the corresponding range (4XX, 5XX) and if the response
body can be deserialized to that type, deserialize then throw.
3. If a mapping is present for "default" responses and if the response body can be
deserialized to that type, deserialize then throw.
4. If none of the previous criteria are met, throw a new instance of the API exception
defined in the abstractions library.
The generated clients throw exceptions/errors for failed response codes to allow the
consumer to tell the difference between a successful response that didn't return a body
(204, etc.) and a failed response. The consumer can implement try/catch behavior that
either catches the generic API exception type, or is more specific to an exception type
mapped to a range or even a status code, depending on the scenario.

Transient errors
Most request adapters handle transient errors (for example 429 because of throttling,
network interruption, etc.) through two main mechanisms. In this scenario, the request
adapter and the generated client aren't aware that an error happened and don't throw
an exception.

The native clients of most platforms provide support for some transient errors
handling (for example, reconnecting when the network was interrupted).
Request adapters provide a middleware infrastructure to implement cross-cutting
concerns like transient error handling (for example, exponential back-off when
throttled) which is enabled by default.

Error message
Kiota generates code to extract the value of a property from the generated error type as
the main exception/error message/reason if a string property is identified with the x-ms-
primary-error-message extension.

In this example, the value for the errorMessage property returned from the API is used
as the error message for the exception if any 404 response is returned.

YAML

openapi: 3.0.3
info:
title: OData Service for namespace microsoft.graph
description: This OData service is located at
https://graph.microsoft.com/v1.0
version: 1.0.1
paths:
/foo:
get:
responses:
'404':
content:
application/json:
schema:
type: object
properties:
bar:
type: string
errorMessage:
type: string
x-ms-primary-error-message: true
servers:
- url: https://graph.microsoft.com/v1.0

API Exception properties


The base API exception/error type from which all generated error types derive defines
the following properties. The request adapter for the language automatically populates
these properties.

ノ Expand table

Name Type Description

ResponseStatusCode int32 The status code from the HTTP response.

ResponseHeaders map(string, string[]) The response headers.

Additionally these types also derive from the native exception/error type of the
platform, and can be expected to provide the same properties.

Solutions to missing error mappings


When a description doesn't document a mapping for an error status code encountered
at runtime, the client application receives an exception/error with the following error
message: "The server returned an unexpected status code and no error factory is
registered for this code." There are many ways to deal with this situation:

You can reach out to the API producer to ask them to improve their description
and add the missing code to the API description. The API client can then be
refreshed to include the error mapping.
You can maintain a local copy of the description and add the missing code to the
API description. The API client can then be refreshed to include the error mapping.
The client application can rely on the status code and header fields to drive its
recovery.
Kiota backing store
Article • 05/24/2024

By default Kiota models are generated to store the data directly within their memory
space. While this option is simpler, it limits many scenarios.

The backing store option ( -b | --backing-store ) allows you to generate different


models that rely on a backing store implementation to store their data.

Backing store features

Dirty tracking
A common limitation of simple models is round trip update of data send the entire
representation of the object, which is wasteful and can have side effects. Imagine a
scenario where your application gets a user, updates their title to send it back to the
service. In that scenario, you want your client to automatically track which fields the
application updates.

C#

var user = await client.Users["john"].GetAsync();


user.Title = "Dr";
await client.Users["john"].PatchAsync(user);

Without the backing store enabled, the client sends the entire representation:

JSON

{
"firstName": "John",
"lastName": "Doe",
"title": "Dr",
"email": "[email protected]"
}

Not only it leads to more data being transferred, but it can potentially result in errors if
the service prevents updating the email address field without a specific permission.

With the backing store enabled, the client sends only the changed fields:

JSON
{
"title": "Dr"
}

Which leads to less data transfer and reduces the chances to result in an error.

The backing store also allows tracking properties being reset and sending null to the
service to do so.

C#

var user = await client.Users["john"].GetAsync();


user.Title = null; // we want to reset the title to the default value from
the service
await client.Users["john"].PatchAsync(user);

Without the backing store would result in:

JSON

{
"firstName": "John",
"lastName": "Doe",
"email": "[email protected]"
}

With the backing store would result in:

JSON

{
"title": null
}

Event subscription
In certain scenarios, you need your application to be notified when data changes
happen. For instance, to refresh the user interface or to synchronize the data with
another data store.

The backing store also enables these scenarios through a subscription mechanism.

C#
// in the section that displays the user profile on screen
var user = await client.Users["john"].GetAsync();
user.BackingStore.Subscribe((key, previousValue, newValue) => {
if ("title".Equals(key)) {
// refresh the UI component displaying the title of the user
}
})

// in the profile form as the user updates their title


// the UI component will automatically refresh
dropDown.OnSelectedItemChange += (selectedItem) => {
user.Title = selectedItem.Value;
};
await client.Users["john"].PatchAsync(user);

Implementations
Kiota abstractions libraries provide a default implementation of the backing store
InMemoryBackingStore. The generated client automatically registers it when the client
is instantiated. The registration mechanism relies on a singleton defined in the
abstractions library and the implementation in use is common for all clients in the
application domain.

You can register your own implementation by calling the EnableBackingStore on the
RequestAdapter in use, or by passing it as an argument to the client constructor.
Unit testing Kiota API clients
Article • 07/06/2023

Unit testing API clients against the actual API can often be impractical. Issues like
network failures, authentication requirements, or changing data can make testing
difficult or impossible. We recommend that unit tests use mock implementations of the
HTTP transport layer to control API responses.

For Kiota API clients, the HTTP layer is contained in a request adapter. Mocking the
request adapter allows you to control API responses.

Prerequisite
In this sample, the following frameworks/tools are used.

xUnit - unit testing framework for .NET


NSubstitute - mocking library to mock interfaces

Kiota client unit testing


The following unit tests are for an API client generated for the /posts endpoint in the
JSONPlaceholder REST API . The full project can be downloaded from GitHub .

C#

using System.Text.Json;
using KiotaPosts.Client;
using KiotaPosts.Client.Models;
using Microsoft.Kiota.Abstractions;
using Microsoft.Kiota.Abstractions.Serialization;
using Microsoft.Kiota.Serialization.Json;
using NSubstitute;

namespace KiotaPostsTests;

public class PostsRequestsTests


{
private static readonly List<Post> postsMock = new()
{
new Post
{
Id = 1,
UserId = 1,
Title = "Post Title #1",
Body = "Posts Body #1",
},
new Post
{
Id = 2,
UserId = 2,
Title = "Post Title #2",
Body = "Post Body #2",
},
};

// Basic test for GET /posts


[Fact]
public async Task All_Posts()
{
// Arrange
var adapter = Substitute.For<IRequestAdapter>();
var postsClient = new PostsClient(adapter);

// Return the mocked list of posts


adapter.SendCollectionAsync(
Arg.Any<RequestInformation>(),
Arg.Any<ParsableFactory<Post>>(),
Arg.Any<Dictionary<string, ParsableFactory<IParsable>>>(),
Arg.Any<CancellationToken>())
.ReturnsForAnyArgs(postsMock);

// Act
var posts = await postsClient.Posts.GetAsync();

// Assert
Assert.NotNull(posts);
Assert.Equal(postsMock.Count, posts.Count);
}

// Basic test for GET /posts/{id}


[Fact]
public async Task Post_By_Id()
{
// Arrange
var adapter = Substitute.For<IRequestAdapter>();
var postsClient = new PostsClient(adapter);

// Return the mocked post #1 object if the path


// contains the ID of post #1
adapter.SendAsync(
Arg.Is<RequestInformation>(req =>
req.PathParameters.Values.Contains(1)),
Arg.Any<ParsableFactory<Post>>(),
Arg.Any<Dictionary<string, ParsableFactory<IParsable>>>(),
Arg.Any<CancellationToken>())
.Returns(postsMock[0]);

// Return the mocked post #2 object if the path


// contains the ID of post #2
adapter.SendAsync(
Arg.Is<RequestInformation>(req =>
req.PathParameters.Values.Contains(2)),
Arg.Any<ParsableFactory<Post>>(),
Arg.Any<Dictionary<string, ParsableFactory<IParsable>>>(),
Arg.Any<CancellationToken>())
.Returns(postsMock[1]);

// Act
var post1 = await postsClient.Posts[1].GetAsync();
var post2 = await postsClient.Posts[2].GetAsync();

// Assert
Assert.NotNull(post1);
Assert.Equal(postsMock[0].Title, post1.Title);
Assert.NotNull(post2);
Assert.Equal(postsMock[1].Title, post2.Title);
}

// Basic test for POST /posts


[Fact]
public async Task Post_Create_New()
{
// Arrange
var adapter = Substitute.For<IRequestAdapter>();
var postsClient = new PostsClient(adapter);

// Add JsonSerializationWriter to serialize Post objects

adapter.SerializationWriterFactory.GetSerializationWriter("application/json"
)
.Returns(sw => new JsonSerializationWriter());

// When the request is sent through the adapter


// save it so we can validate the content of the request
RequestInformation? postRequest = null;
await adapter.SendAsync(
Arg.Do<RequestInformation>(req => postRequest = req),
Arg.Any<ParsableFactory<Post>>(),
Arg.Any<Dictionary<string, ParsableFactory<IParsable>>?>(),
Arg.Any<CancellationToken>());

var newPost = new Post


{
UserId = 3,
Title = "Created new post",
Body = "For testing purposes",
};

// Act
await postsClient.Posts.PostAsync(newPost);

// Assert
Assert.NotNull(postRequest);
// Deserialize the request body
var postFromBody = JsonSerializer.Deserialize<Post>(
postRequest.Content,
new JsonSerializerOptions
{
PropertyNamingPolicy = JsonNamingPolicy.CamelCase,
});

Assert.NotNull(postFromBody);
Assert.Equal(newPost.UserId, postFromBody.UserId);
Assert.Equal(newPost.Title, postFromBody.Title);
Assert.Equal(newPost.Body, postFromBody.Body);
}
}
Adding an API to search
Article • 08/26/2024

The search command relies on multiple indices to find OpenAPI descriptions that can be
used to generate clients. If you maintain APIs, you can add your own description to the
results by updating one of the following indices:

GitHub
APIs.guru

GitHub
You can add your API descriptions to the search result by following these steps:

1. Add the kiota-index topic to your GitHub repository.


2. Add an apis.json or apis.yaml file at the root of your repository on your main
branch.
3. Make sure the repository has a description and:
a. The repository is public
b. Or the kiota GitHub application is installed on the repository, users are
allowed to read the repository, and they are signed into kiota.

Example apis.yaml
YAML

name: Microsoft Graph OpenAPI registry


description: This repository contains the OpenAPI definitions for Microsoft
Graph APIs.
tags:
- microsoft
apis:
- name: Microsoft Graph v1.0
description: The Microsoft Graph API offers a single endpoint, to provide
access to rich, people-centric data and insights in the Microsoft cloud.
baseUrl: https://graph.microsoft.com/v1.0
properties:
- type: x-openapi
url: openapi/v1.0/openapi.yaml # can be the relative path on the
repository or a publicly accessible URL

7 Note
For more information about apis.yaml, see What is APIs.yaml? .

Example apis.json
jsonc

{
"name": "Microsoft Graph OpenAPI registry",
"description": "This repository contains the OpenAPI definitions for
Microsoft Graph APIs.",
"tags": [
"microsoft"
],
"apis": [
{
"name": "Microsoft Graph v1.0",
"description": "The Microsoft Graph API offers a single
endpoint, to provide access to rich, people-centric data and insights in the
Microsoft cloud.",
"baseUrl": "https://graph.microsoft.com/v1.0",
"properties": [
{
"type": "x-openapi",
"url": "openapi/v1.0/openapi.yaml" // can be the
relative path on the repository or a publicly accessible URL
}
]
}
]
}

7 Note

For more information about apis.json, see What is APIs.json? .

APIs guru
You can add your description to the APIs guru index by filling the following form .
Register a Kiota API client in .NET with
dependency injection
Article • 10/01/2024

In this tutorial, you learn how to register a Kiota API client with dependency injection.

Required tools
.NET SDK 8.0
Kiota CLI

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

.NET CLI

dotnet new webapi -o kiota-with-di


cd kiota-with-di
dotnet new gitignore

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

Run the following commands to get the required dependencies.

.NET CLI

dotnet add package Microsoft.Extensions.Http


dotnet add package Microsoft.Kiota.Bundle

Generate the API client


Kiota generates API clients from OpenAPI documents. Let's download the GitHub API
specs and generate the API client.
You can then use the Kiota command line tool to generate the API client classes.

Bash

# Download the specs to ./github-api.json


kiota download apisguru::github.com -o ./github-api.json
# Generate the client, path filter for just releases
kiota generate -l csharp -d github-api.json -c GitHubClient -n
GitHub.ApiClient -o ./GitHub --include-path
"/repos/{owner}/{repo}/releases/*" --clean-output

Create extension methods


Create a new file named KiotaServiceCollectionExtensions.cs in the root of your project
and add the following code.

C#

using Microsoft.Kiota.Http.HttpClientLibrary;

/// <summary>
/// Service collection extensions for Kiota handlers.
/// </summary>
public static class KiotaServiceCollectionExtensions
{
/// <summary>
/// Adds the Kiota handlers to the service collection.
/// </summary>
/// <param name="services"><see cref="IServiceCollection"/> to add the
services to</param>
/// <returns><see cref="IServiceCollection"/> as per
convention</returns>
/// <remarks>The handlers are added to the http client by the <see
cref="AttachKiotaHandlers(IHttpClientBuilder)"/> call, which requires them
to be pre-registered in DI</remarks>
public static IServiceCollection AddKiotaHandlers(this
IServiceCollection services)
{
// Dynamically load the Kiota handlers from the Client Factory
var kiotaHandlers = KiotaClientFactory.GetDefaultHandlerTypes();
// And register them in the DI container
foreach(var handler in kiotaHandlers)
{
services.AddTransient(handler);
}

return services;
}

/// <summary>
/// Adds the Kiota handlers to the http client builder.
/// </summary>
/// <param name="builder"></param>
/// <returns></returns>
/// <remarks>
/// Requires the handlers to be registered in DI by <see
cref="AddKiotaHandlers(IServiceCollection)"/>.
/// The order in which the handlers are added is important, as it
defines the order in which they will be executed.
/// </remarks>
public static IHttpClientBuilder AttachKiotaHandlers(this
IHttpClientBuilder builder)
{
// Dynamically load the Kiota handlers from the Client Factory
var kiotaHandlers = KiotaClientFactory.GetDefaultHandlerTypes();
// And attach them to the http client builder
foreach(var handler in kiotaHandlers)
{
builder.AddHttpMessageHandler((sp) =>
(DelegatingHandler)sp.GetRequiredService(handler));
}

return builder;
}
}

Create a client factory


Create a new file named GitHubClientFactory.cs in the GitHub folder and add the
following code.

The code in these files implement a factory pattern, where you create a factory class that
is responsible for creating an instance of the client. This way you have a single place that
is responsible for creating the client, and you can easily change the way the client is
created. In this sample we are registering the factory in the dependency injection
container as well, because it gets the HttpClient injected in the constructor.

C#

using GitHub.ApiClient;
using Microsoft.Kiota.Abstractions.Authentication;
using Microsoft.Kiota.Http.HttpClientLibrary;

namespace GitHub;

public class GitHubClientFactory


{
private readonly IAuthenticationProvider _authenticationProvider;
private readonly HttpClient _httpClient;
public GitHubClientFactory(HttpClient httpClient)
{
_authenticationProvider = new AnonymousAuthenticationProvider();
_httpClient = httpClient;
}

public GitHubClient GetClient() {


return new GitHubClient(new
HttpClientRequestAdapter(_authenticationProvider, httpClient: _httpClient));
}
}

Register the API client


Open the Program.cs file and add the following code above the var app =
builder.Build(); line. Sample Program.cs .

C#

using GitHub;
var builder = WebApplication.CreateBuilder(args);

// Add services to the container.


// Learn more about configuring Swagger/OpenAPI at
https://aka.ms/aspnetcore/swashbuckle
builder.Services.AddEndpointsApiExplorer();
builder.Services.AddSwaggerGen();

// ----------- Add this part to register the generated client -----------


// Add Kiota handlers to the dependency injection container
builder.Services.AddKiotaHandlers();

// Register the factory for the GitHub client


builder.Services.AddHttpClient<GitHubClientFactory>((sp, client) => {
// Set the base address and accept header
// or other settings on the http client
client.BaseAddress = new Uri("https://api.github.com");
client.DefaultRequestHeaders.Add("Accept",
"application/vnd.github.v3+json");
}).AttachKiotaHandlers(); // Attach the Kiota handlers to the http client,
this is to enable all the Kiota features.

// Register the GitHub client


builder.Services.AddTransient(sp =>
sp.GetRequiredService<GitHubClientFactory>().GetClient());
// ----------- Add this part to register the generated client end -------

var app = builder.Build();

// Configure the HTTP request pipeline.


if (app.Environment.IsDevelopment())
{
app.UseSwagger();
app.UseSwaggerUI();
}

app.UseHttpsRedirection();

var summaries = new[]


{
"Freezing", "Bracing", "Chilly", "Cool", "Mild", "Warm", "Balmy", "Hot",
"Sweltering", "Scorching"
};

app.MapGet("/weatherforecast", () =>
{
var forecast = Enumerable.Range(1, 5).Select(index =>
new WeatherForecast
(
DateOnly.FromDateTime(DateTime.Now.AddDays(index)),
Random.Shared.Next(-20, 55),
summaries[Random.Shared.Next(summaries.Length)]
))
.ToArray();
return forecast;
})
.WithName("GetWeatherForecast")
.WithOpenApi();

// ----------- Add this part to create a new endpoint that uses the
generated client -----------

app.MapGet("/dotnet/releases", async (GitHub.ApiClient.GitHubClient client,


CancellationToken cancellationToken) =>
{
var releases = await client.Repos["dotnet"]
["runtime"].Releases["latest"].GetAsync(cancellationToken:
cancellationToken);
return releases;
})
.WithName("GetDotnetReleases")
.WithOpenApi();

// ----------- Add this part to create a new endpoint that uses the
generated client end -----------

app.Run();

record WeatherForecast(DateOnly Date, int TemperatureC, string? Summary)


{
public int TemperatureF => 32 + (int)(TemperatureC / 0.5556);
}
Create an endpoint
We will now create an endpoint that uses the GitHub client from dependency injection
to get the latest release of dotnet/runtime .

Open the Program.cs file and add the following code above the app.Run(); line. Sample
Program.cs .

C#

using GitHub;
var builder = WebApplication.CreateBuilder(args);

// Add services to the container.


// Learn more about configuring Swagger/OpenAPI at
https://aka.ms/aspnetcore/swashbuckle
builder.Services.AddEndpointsApiExplorer();
builder.Services.AddSwaggerGen();

// ----------- Add this part to register the generated client -----------


// Add Kiota handlers to the dependency injection container
builder.Services.AddKiotaHandlers();

// Register the factory for the GitHub client


builder.Services.AddHttpClient<GitHubClientFactory>((sp, client) => {
// Set the base address and accept header
// or other settings on the http client
client.BaseAddress = new Uri("https://api.github.com");
client.DefaultRequestHeaders.Add("Accept",
"application/vnd.github.v3+json");
}).AttachKiotaHandlers(); // Attach the Kiota handlers to the http client,
this is to enable all the Kiota features.

// Register the GitHub client


builder.Services.AddTransient(sp =>
sp.GetRequiredService<GitHubClientFactory>().GetClient());
// ----------- Add this part to register the generated client end -------

var app = builder.Build();

// Configure the HTTP request pipeline.


if (app.Environment.IsDevelopment())
{
app.UseSwagger();
app.UseSwaggerUI();
}

app.UseHttpsRedirection();

var summaries = new[]


{
"Freezing", "Bracing", "Chilly", "Cool", "Mild", "Warm", "Balmy", "Hot",
"Sweltering", "Scorching"
};

app.MapGet("/weatherforecast", () =>
{
var forecast = Enumerable.Range(1, 5).Select(index =>
new WeatherForecast
(
DateOnly.FromDateTime(DateTime.Now.AddDays(index)),
Random.Shared.Next(-20, 55),
summaries[Random.Shared.Next(summaries.Length)]
))
.ToArray();
return forecast;
})
.WithName("GetWeatherForecast")
.WithOpenApi();

// ----------- Add this part to create a new endpoint that uses the
generated client -----------

app.MapGet("/dotnet/releases", async (GitHub.ApiClient.GitHubClient client,


CancellationToken cancellationToken) =>
{
var releases = await client.Repos["dotnet"]
["runtime"].Releases["latest"].GetAsync(cancellationToken:
cancellationToken);
return releases;
})
.WithName("GetDotnetReleases")
.WithOpenApi();

// ----------- Add this part to create a new endpoint that uses the
generated client end -----------

app.Run();

record WeatherForecast(DateOnly Date, int TemperatureC, string? Summary)


{
public int TemperatureF => 32 + (int)(TemperatureC / 0.5556);
}

Run the application


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

.NET CLI

dotnet run
You can now open a browser and navigate to http://localhost:{port}/dotnet/releases
to see the latest release of dotnet/runtime . Alternatively, you can also go to
http://localhost:{port}/swagger to see the Swagger UI with this new endpoint.

Authentication
The GitHubClientFactory class is responsible for creating the client, and it is also
responsible for creating the IAuthenticationProvider . In this sample, we are using the
AnonymousAuthenticationProvider , which is a simple provider that does not add any

authentication headers. More details on authentication with Kiota can be found in the
Kiota authentication documentation.

The GitHubClientFactory is used through dependency injection, which means you can
have other types injected by the constructor that are needed for the authentication
provider.

You might want to create a BaseBearerTokenAuthenticationProvider that is available in


Kiota and expects an IAccessTokenProvider , which is just an interface with one method
to provide an access token. Access tokens usually have a lifetime of 1 hour, which is why
you need to get them at runtime and not set them at registration time.

See also
Sample project used in this guide
Build API clients for .NET with Microsoft Identity authentication shows how to use
Kiota with Microsoft Identity authentication.
ToDoItem Sample API implements a sample OpenAPI in ASP.NET Core and
sample clients in multiple languages.
Releases and support for Kiota
Article • 05/24/2024

Microsoft ships major releases, minor releases, and patches for Kiota. This article
explains release types and support options for Kiota.

Release types
Kiota follows Semantic Versioning 2.0.0 . Information about the type of each release is
encoded in the version number in the form major.minor.patch .

Major releases
Major releases include new features, new public API surface area, and bug fixes. Due to
the nature of the changes, these releases are expected to have breaking changes. Major
releases can install side by side with previous major releases. We only maintain the latest
major release, except for security and privacy related issues where we might release
patches to prior major versions. Major releases are published as needed.

Minor releases
Minor releases also include new features, public API surface area, and bug fixes. The
difference between these and major releases is that minor releases don't contain
breaking changes to the tooling experience or the generated API surface area of Stable
maturity languages. Minor releases can install side by side with previous minor releases.
Minor releases are targeted to publish on the first Tuesday of every month.

Patches
Patches ship as needed, and they include security and nonsecurity bug fixes.

Language support
Language support in Kiota is either stable, preview or experimental for each language.

The following criteria are used to determine the maturity levels.

Stable: Kiota provides full functionality for the language and is used to generate
production API clients.
Preview: Kiota is at or near the level of stable but isn't being used to generate
production API clients.
Experimental: Kiota provides some functionality for the language but is still in
early stages. Some features might not work correctly or at all.

Breaking changes to languages that are stable result in major version change for Kiota
tooling. Code generation changes to a stable language aren't considered breaking when
they rely on additions in the corresponding abstractions library. These changes only
require updating the abstractions library to the latest minor/patch version under the
same major version.

The current status of language support can be queried by using the following
command.

Bash

kiota info

Kiota roll-forward and compatibility


Major and minor updates can be installed side by side with previous versions. Installing
new versions of the Kiota tooling doesn't affect existing Kiota generated code. To
update applications to the latest Kiota generate code, the code must be regenerated
with the new Kiota tooling. The app doesn't automatically roll forward to use a newer
version of Kiota Tooling.

We recommend rebuilding the app and testing against a newer major or minor version
before deploying to production.

Support
The primary support channel for Kiota is GitHub. You can open GitHub issues in the
Kiota repository to track bugs and feature requests.

You might also like