Openapi Kiota
Openapi Kiota
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
Authentication
Middleware handlers
Get started
b GET STARTED
Install Kiota
f QUICKSTART
g TUTORIAL
.NET tutorial
CLI tutorial
Go tutorial
Java tutorial
PHP tutorial
Python tutorial
Ruby tutorial
TypeScript tutorial
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.
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
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
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
Bash
3. Open the solution with Visual Studio and right select publish or execute the
following command:
Bash
ノ Expand table
7 Note
Refer to .NET runtime identifier catalog so select the appropriate runtime for
your platform.
Bash
7 Note
The Kiota Visual Studio Code extension is currently in public preview and is subject
to change.
YAML
steps:
- uses: actions/checkout@v3
- uses: microsoft/[email protected]
7 Note
The setup Kiota GitHub Action in public preview and is subject to change.
) 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
) 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
) 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
2. Select on the Download button. To complete the installation, restart Visual Studio.
Next steps
For details on running Kiota, see Using the Kiota tool.
Using the Kiota tool
Article • 10/01/2024
7 Note
ノ Expand table
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
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.
Bash
Bash
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
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
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
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
Example
The following command with the provided options displays the following result.
Bash
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
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)
Bash
--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
--additional-data (--ad)
Bash
--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
--deserializer (--ds)
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.
ノ Expand table
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
text.TextParseNodeFactory
Accepted values
Bash
--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:
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
Accepted values
A valid URI to an OpenAPI description in the local filesystem or hosted on an HTTPS server.
Bash
--serializer (-s)
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.
ノ Expand table
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
Accepted values
Bash
--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
Accepted values
Any valid MIME type that matches a request body type or a response type in the OpenAPI
description.
Examples
Bash
--type-access-modifier (--tam)
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
Internal
Protected
Examples
Bash
Language information
Kiota info accepts the following parameters when displaying language information like
their maturity level or dependencies needed at runtime.
Bash
Example - global
The following command with the provided options displays the following result.
Bash
kiota info
Bash
Bash
Bash
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
Accepted values:
ノ Expand table
HTTP Implement the request adapter with a specific HTTP client. Runtime
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
--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
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
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.
Bash
--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
--exclude-path (-e)
Bash
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
--include-path (-i)
A glob pattern to include paths from generation. Accepts multiple values. If this parameter
is absent, everything is included.
Bash
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
The location of the OpenAPI description in JSON or YAML format to use to generate the
SDK. Accepts a URL or a local path.
Bash
--language (-l)
The target language for the generated code files or for the information.
Accepted values
csharp
go
java
php
python
ruby
shell
swift
typescript
Bash
--log-level (--ll)
The log level to use when logging events to the main output. Defaults to warning .
Accepted values
critical
debug
error
information
none
trace
warning
Bash
--output (-o)
The output directory or file path for the generated code files. Defaults to ./output for
generate and ./output/result.json for download.
Accepted values
A valid path to a directory (generate) or a file (download).
Bash
--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.
Bash
--version (-v)
Select a specific version of the API description. No default value.
Bash
--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.
Bash
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
ノ Expand table
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
Project configuration
In case you're adding a Kiota client to an existing project, the following configuration is
required:
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.
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
Tip
C#
using KiotaPosts.Client;
using KiotaPosts.Client.Models;
using Microsoft.Kiota.Abstractions.Authentication;
using Microsoft.Kiota.Http.HttpClientLibrary;
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!"
};
// PATCH /posts/{id}
var update = new Post
{
// Only update title
Title = "Updated title"
};
// 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.
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:
Create a project
Run the following command in the directory you want to create a new project.
Bash
Project configuration
In case you're adding a Kiota client to an existing project, the following configuration is
required:
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.
Bash
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
Tip
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;
ApiClientBuilder.RegisterDefaultSerializer<JsonSerializationWriterFactory>
();
ApiClientBuilder.RegisterDefaultSerializer<TextSerializationWriterFactory>
();
ApiClientBuilder.RegisterDefaultSerializer<FormSerializationWriterFactory>
();
return adapter;
}).RegisterCommonServices();
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.
GET /posts
Bash
GET /posts/{id}
Bash
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
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
Project configuration
In case you're adding a Kiota client to an existing project, the following configuration is
required:
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.
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
Tip
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{}
// 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)
// 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
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
Project configuration
In case you're adding a Kiota client to an existing project, the following configuration is
required:
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.
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'
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
Tip
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;
// 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!");
// PATCH /posts/{id}
final Post update = new Post();
// Only update title
update.setTitle("Updated title");
// DELETE /posts/{id}
client.posts().byPostId(specificPostId).delete();
}
}
7 Note
Bash
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.
) 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:
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.
Bash
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
Tip
JSON
"autoload": {
"psr-4": {
"KiotaPosts\\Client\\": "client/"
}
}
To ensure the newly generated classes can be imported, update the autoload paths
using:
Bash
composer dumpautoload
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
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:
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:
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
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
Tip
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
# 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!"
# 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
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:
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
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
Tip
TypeScript
// 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!',
};
// PATCH /posts/{id}
const update: Post = {
// Only update title
title: 'Updated title',
};
// 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.
Bash
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
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.
.NET CLI
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
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.
4. Select Register. On the Overview page, copy the value of the Application
(client) ID and save it.
6. Locate the Advanced settings section. Set the Allow public client flows toggle
to Yes, then select Save.
C#
using Azure.Identity;
using GetUserClient.ApiClient;
using Microsoft.Kiota.Authentication.Azure;
using Microsoft.Kiota.Bundle;
7 Note
This example uses the DeviceCodeCredential class. You can use any of the
credential classes from the Azure.Identity library.
.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:
Create a project
Run the following command in the directory you want to create a new project.
Bash
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.
Bash
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
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.
4. Select Register. On the Overview page, copy the value of the Application
(client) ID and save it.
6. Locate the Advanced settings section. Set the Allow public client flows toggle
to Yes, then select Save.
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;
// 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);
7 Note
This example uses the DeviceCodeCredential class. You can use any of the
credential classes from the Azure.Identity library.
Bash
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
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.
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
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
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.
4. Select Register. On the Overview page, copy the value of the Application
(client) ID and save it.
6. Locate the Advanced settings section. Set the Allow public client flows toggle
to Yes, then select Save.
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)
}
if err != nil {
fmt.Printf("Error creating request adapter: %v\n", err)
}
client := client.NewGraphApiClient(adapter)
if err != nil {
fmt.Printf("Error getting user: %v\n", err)
}
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
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.
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'
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
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.
4. Select Register. On the Overview page, copy the value of the Application
(client) ID and save it.
6. Locate the Advanced settings section. Set the Allow public client flows toggle
to Yes, then select Save.
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;
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
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.
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
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
"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.
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.
) 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.
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';
$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()}";
7 Note
This example uses the AuthorizationCodeContext class. You can use any of the
credential classes from the kiota-authentication-phpleague library.
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.
Bash
Tip
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
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.
4. Select Register. On the Overview page, copy the value of the Application
(client) ID and save it.
6. Locate the Advanced settings section. Set the Allow public client flows toggle
to Yes, then select Save.
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
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)
# 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.
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.
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
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
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.
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.
) 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.
5. Copy everything in the URL between code= and & . This value is the 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'
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
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.
Bash
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
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.
4. Select Register. On the Overview page, copy the value of the Application
(client) ID and save it.
6. Locate the Advanced settings section. Set the Allow public client flows toggle
to Yes, then select Save.
TypeScript
const authProvider =
new AzureIdentityAuthenticationProvider(credential, graphScopes,
undefined, allowedHosts);
const adapter = new FetchRequestAdapter(authProvider);
GetUser();
7 Note
This example uses the DeviceCodeCredential class. You can use any of the
credential classes from the @azure/identity library.
Bash
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
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.
Code model
Most SDK generator efforts use a combination of API description of DOM and templates
to create source code. Templates have several disadvantages:
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.
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.
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
Guidance
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.
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.
The following table provides the list of abstractions package per language.
ノ Expand table
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
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.
JSON
Media type: application/json
The following table provides the list of serialization package per language.
ノ Expand table
C# Microsoft.Kiota.Serialization.Json System.Text.Json
Go github.com/microsoft/kiota-serialization-json-go None
Language Package Name Relies on
Multipart
Media type: multipart/form-data
The following table provides the list of serialization package per language.
ノ Expand table
C# Microsoft.Kiota.Serialization.Multipart None
Go github.com/microsoft/kiota-serialization-multipart-go None
Form
Media type: application/x-www-form-urlencoded
The following table provides the list of serialization package per language.
ノ Expand table
C# Microsoft.Kiota.Serialization.Form None
Go github.com/microsoft/kiota-serialization-form-go None
Text
Media type: text/plain
The following table provides the list of serialization package per language.
ノ Expand table
C# Microsoft.Kiota.Serialization.Text None
Go github.com/microsoft/kiota-serialization-text-go None
The following table provides the list of HTTP package per language.
ノ Expand table
C# Microsoft.Kiota.Http.HttpClientLibrary System.Net.Http
Go github.com/microsoft/kiota-http-go net/http
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.
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
C# Microsoft.Kiota.Authentication.Azure Azure.Identity
Go github.com/microsoft/kiota-authentication- github.com/Azure/azure-sdk-for-
azure-go go/sdk/azidentity
Additional
Additional dependencies are required at build time and/or runtime.
The following table provides the list of additional package per language.
ノ Expand table
C# None
Go None
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
C# Microsoft.Kiota.Bundle
CLI Microsoft.Kiota.Bundle
Go github.com/microsoft/kiota-bundle-go
Java com.microsoft.kiota:microsoft-kiota-bundle
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#
await client.Users.PostAsync(newUser);
C#
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#
Using a configured query parameter object prevents tight coupling on the order of
query parameters and makes optional parameters easy to implement across languages.
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#
2 Warning
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#
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#
2 Warning
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#
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.
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#
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
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#
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#
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#
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; }
}
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.
.NET
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.
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
Task<string> GetAuthorizationTokenAsync(
Uri uri,
Dictionary<string, object>? additionalAuthenticationContext =
null,
CancellationToken cancellationToken = default));
}
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
}
}
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.
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.
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:
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.
The URL for the request is built using an RFC6570 URL Template and providing its
parameters.
C#
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.
C#
var requestBuilder =
todoClient.TaskLists["taskListId"].ToDos["todoId"].AssignedTo;
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.
C#
var requestBuilder =
todoClient.TaskLists["taskListId"].ToDos["todoId"].AssignedTo;
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#
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
where both the taskLists and toDos path segments don't require any parameter.
7 Note
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.
C#
var requestBuilder =
todoClient.TaskLists["taskListId"].ToDos["todoId"].AssignedTo;
where both the {task_list_id} and {todo_id} path segments are single unnamed path
parameters.
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.
C#
var requestBuilder =
todoClient.TaskLists["taskListId"].GetReminders("startDate", "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
You can still use the fluent API and get the benefits of autocompletion, compile-time
validation and more by using the WithUrl method.
CSharp
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 generators
Request generator methods follow this Create{HTTPMethodName}RequestInformation
naming convention. And accept the following parameters:
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:
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.
C#
The URL template for the request builder looks something like
{+baseurl}/taskLists/{task_list_id}/toDos/{todo_id}/assignedTo{?select,expand} .
7 Note
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#
HTTP
GET ...
Contoso-Custom: foo, bar
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.
C#
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#
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
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.
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.
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:
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 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.
C#
cs
using Microsoft.Kiota.Abstractions.Serialization;
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
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
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;
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;
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#
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#
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#
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.
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.
ノ Expand table
0 0 0 0 Ignored/Invalid
merged.
7 Note
These rules are applied to allOf entries recursively enabling multi-level inheritance.
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.
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.
{
"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"
}
]
}
}
{
"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#
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.
ノ Expand table
CSharp PascalCase -
Language Property name Property accessors
CLI PascalCase -
Go - PascalCase
PHP - camelCase
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.
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
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
2XX no stream
7 Note
Expected return type Response status code Response body is present Returned value
Kiota API clients include error types for errors defined in OpenAPI descriptions.
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.
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
ノ Expand table
Additionally these types also derive from the native exception/error type of the
platform, and can be expected to provide the same properties.
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.
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#
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#
JSON
{
"firstName": "John",
"lastName": "Doe",
"email": "[email protected]"
}
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
}
})
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.
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;
// Act
var posts = await postsClient.Posts.GetAsync();
// Assert
Assert.NotNull(posts);
Assert.Equal(postsMock.Count, posts.Count);
}
// 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);
}
adapter.SerializationWriterFactory.GetSerializationWriter("application/json"
)
.Returns(sw => new JsonSerializationWriter());
// 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:
Example apis.yaml
YAML
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
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
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.
.NET CLI
Bash
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;
}
}
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;
C#
using GitHub;
var builder = WebApplication.CreateBuilder(args);
app.UseHttpsRedirection();
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 -----------
// ----------- Add this part to create a new endpoint that uses the
generated client end -----------
app.Run();
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);
app.UseHttpsRedirection();
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 -----------
// ----------- Add this part to create a new endpoint that uses the
generated client end -----------
app.Run();
.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.
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.
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
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.