Tool overview
Что такое Kiota?
Генератор SDK Microsoft из OpenAPI — полный справочник workflow.
Зачем этот справочник Kiota
Проверка OpenAPI, предпросмотр SDK, сравнение генераторов — на клиенте.
Возможности DevUtilities
7 шагов Build My SDK, readiness score, API explorer.
Как использовать
Следуйте этим шагам, чтобы получить точные результаты с инструментом выше.
- Paste or upload your OpenAPI 3 JSON/YAML spec—or start from a sample like Petstore, GitHub, or Microsoft Graph metadata.
- Review the OpenAPI Readiness score and fix blocking errors (duplicate operationIds, circular refs, missing response schemas) using the diagnostics panel.
- Walk through the Build My SDK workflow: Understand → Validate → Configure language and client name → Preview SDK structure.
- In Preview, use API Explorer, SDK Tree, and Multi-Language tabs to inspect how operations and models will generate.
- Select only the endpoints your application needs to reduce output size; confirm trimmed paths in the exported CLI command.
- Configure authentication by mapping securitySchemes to Bearer, API key, or OAuth patterns in the Auth step.
- Compare Kiota with OpenAPI Generator and NSwag using per-spec file and time estimates on the Compare Generators tab.
- Copy the generated kiota generate command or sample TypeScript/C# usage code from the Generate step.
- Run Kiota CLI locally (dotnet tool install Microsoft.OpenApi.Kiota) to emit files into your project directory.
- Integrate the client with your auth provider, add tests against mock or staging APIs, and pin Kiota version in CI for reproducible regeneration.
Справочник Kiota и библиотека проблем/решений
Руководства Kiota и исправления OpenAPI. Обновлено July 2026.
Указатель руководств Kiota — начните здесь
This page is a single canonical reference for the full Microsoft Kiota SDK workflow. Use the interactive Build My SDK workflow above while you read, or jump to a topic below.
Что такое Kiota и когда использовать
Microsoft Kiota is an OpenAPI-driven SDK generator that produces strongly typed API clients. Unlike hand-written HTTP wrappers, Kiota emits a consistent request builder model: navigate from a root client to path segments, attach query parameters, and call fluent methods that return typed responses.
Supported languages (Kiota 1.x)
- C#, Go, Java, JavaScript/TypeScript, PHP, Python, Ruby, and Swift
- Same OpenAPI input with language-specific idioms (e.g. snake_case modules in Python)
Use Kiota when
- Building clients for Microsoft Graph, Azure APIs, or any OpenAPI 3.x document
- You want consistent request builders, pagination helpers, and typed models across languages
- You need a unified authentication abstraction via Kiota Abstractions and auth provider packages
Skip Kiota when
- Your API is not described by OpenAPI
- You need server-side code generation only
- Your team standardizes on NSwag (.NET) or OpenAPI Generator (broad template ecosystem)
This DevUtilities workspace validates spec readiness, previews SDK structure, compares generators, configures auth, and exports ready-to-run kiota generate commands—all without uploading your spec to a server.
Kiota vs OpenAPI Generator vs NSwag vs AutoRest
Compare OpenAPI client generators before you commit to a toolchain. The Compare Generators tab on this page estimates file count and generation time for your uploaded spec.
Kiota vs OpenAPI Generator vs NSwag vs AutoRest
| Generator | Strengths | Best for |
|---|---|---|
| Kiota | Consistent request builders, PageIterator, BackingStore; small language set with shared patterns | Microsoft Graph, multi-language consistency, modern typed clients |
| OpenAPI Generator | Dozens of languages and templates; large ecosystem | Uncommon languages, legacy templates, server stubs |
| NSwag | Deep ASP.NET integration; C# clients and controllers; flexible JSON serializers | .NET-only consumers with Newtonsoft or System.Text.Json control |
| AutoRest | Azure SDK conventions (legacy) | Maintaining existing Azure SDK pipelines only—Kiota for new Microsoft projects |
Матрица поддержки языков
Kiota 1.x supports C#, Go, Java, JavaScript/TypeScript, PHP, Python, Ruby, and Swift from the same OpenAPI document.
- TypeScript/JavaScript: ES modules with a Kiota request adapter
- C#: integrates with Microsoft.Kiota.Abstractions
- Python: snake_case module layout
- Reserved keywords: Kiota applies language-specific escaping when model names collide
Not every OpenAPI feature maps identically to every language—discriminated unions may flatten differently in Go versus TypeScript. Use the Multi-Language preview tab before generating.
Чеклист готовности OpenAPI для Kiota
Kiota requires OpenAPI 3.0 or 3.1 with at least one path and operation. Aim for four or five stars in the readiness score before running kiota generate in CI.
High-quality spec checklist
- Unique operationId on every operation
- Explicit schema titles for reusable components
- servers entry or a --base-url for the CLI
- securitySchemes under components, referenced on operations
- Response content schemas (not empty {}) for typed deserialization
What this tool checks
- Duplicate or missing operationIds
- Missing response schemas and circular $ref chains
- Polymorphism without discriminator
- Nullable style mismatches between OpenAPI 3.0 and 3.1
Fix syntax errors with the OpenAPI Validator tool first, then return here for Kiota-specific compatibility.
Исправление: дублирующийся operationId
Why it happens
OpenAPI allows omitting operationId, but Kiota uses it to name request builder methods. Duplicate or colliding IDs cause generation failures or silent method overwrites.
Diagnose
Search your spec for duplicate operationId strings, or identical path/method combinations after normalization.
Fixes
- Assign globally unique operationId values (e.g. users_list_v1 following resource_action_version).
- Fix the source spec if you control the API; otherwise post-process with a rename script.
- Use --include-path trimming flags to generate a subset while fixing upstream.
Best practice: enforce unique operationIds in Spectral or your API design linter before publishing.
Исправление: циклическая ссылка
Why it happens
JSON Schema $ref cycles (A → B → A) confuse serializers and may cause Kiota to abort model generation.
Diagnose
The diagnostics panel flags circular component chains. Swagger UI also reveals self-referential types (e.g. TreeNode with TreeNode[] children).
Fixes
- Break the cycle by inlining one side or introducing a shallow DTO for generation.
- Replace unbounded recursive models with depth-limited variants for client use.
- For polymorphic graphs, use discriminator-based oneOf instead of unchecked object loops.
Kiota supports some recursive types in newer versions, but shallow specs remain more portable across languages.
Исправление: проблемы nullable-схем
Why it happens
OpenAPI 3.0 uses nullable: true while 3.1 uses type unions like [string, null]. Mixing styles produces inconsistent nullability in C# and TypeScript.
Diagnose
Inspect components.schemas for inconsistent nullable markers. Verify required arrays—required means the key must appear, not that the value is non-null.
Fixes
- Standardize on OpenAPI 3.1 type unions or consistent nullable: true across schemas.
- Mark optional fields correctly in required arrays.
- Regenerate after normalizing so each language adapter maps nullability correctly.
The OpenAPI Readiness panel highlights nullable mismatches that break strict TypeScript builds.
Паттерны аутентификации с Kiota
Kiota clients do not embed secrets—they accept an authentication provider on the request adapter. Match the scheme name in OpenAPI (BearerAuth, oauth2) to your provider template.
Common patterns
- Bearer / OAuth 2.0: IAccessTokenProvider or Azure Identity with Microsoft Graph
- API key: custom provider setting x-api-key header or query params per security scheme
- OAuth authorization code: acquire tokens out-of-band; provider returns cached tokens
- Microsoft Graph multi-tenant: ClientSecretCredential, DeviceCodeCredential, or InteractiveBrowserCredential
The Auth step in this workflow maps your spec's securitySchemes to starter TypeScript and C# snippets. Never commit client secrets—load from environment variables or a vault at runtime.
Генерировать только выбранные endpoints
Large APIs like Microsoft Graph contain thousands of operations; most apps need a slice. Trimming reduces compile time, package size, and review noise.
CLI flags
- --include-path and --exclude-path accept glob patterns (e.g. /users/**, !/admin/**)
- Exported kiota generate commands include --include-path when you select endpoints here
Workflow
- Load the full spec
- Select only tags or paths your app calls
- Preview SDK tree size in the Preview step
- Copy the CLI command and run locally
- Document trim patterns in your repo for consistent CI regeneration
Регенерировать SDK без потери изменений
Treat generated clients as build artifacts—avoid hand-editing generated files. Regeneration overwrites manual patches.
- Generate into a dedicated folder (./generated/sdk) and wrap with your own facade for business logic
- Use partial classes (C#) or module augmentation (TypeScript) outside generated paths
- Store kiota-lock.json and pin Kiota CLI version in git; regenerate in CI so drift is visible in diffs
- If you must fork, namespace the output directory and merge via git subtrees only when upgrading Kiota
The Generate step shows sample usage code and output layout you can commit as a baseline.
Пример: Microsoft Graph
- Download spec: fetch Microsoft Graph OpenAPI metadata or use trimmed Graph beta JSON in your repo
- Trim paths: include only /me, /users, /groups your app needs
- Generate: kiota generate -l typescript -d graph.json -o ./src/graph-sdk -c GraphClient --base-url https://graph.microsoft.com/v1.0
- Authenticate: TokenCredentialRequestAdapter with @azure/identity DefaultAzureCredential or on-behalf-of for web apps
- Call API: const user = await client.me.get(); handle OData errors via Graph error model
- Handle errors: 401 → refresh tokens; 429 → respect Retry-After; add Kiota retry middleware as needed
This tool's workflow mirrors these steps with readiness analysis for Graph-scale specs.
Примеры: GitHub REST и Stripe
GitHub REST
- Download OpenAPI from GitHub's published description
- Generate with --base-url https://api.github.com
- Authenticate with Bearer PAT via custom access token provider
- Trim to repos and pulls paths—the full spec is large
Stripe
- Stripe publishes OpenAPI—generate TypeScript for customers and payment intents
- Use Bearer sk_test_... from environment variables; never embed keys
- Verify discriminated schemas for polymorphic objects (payment_method types) in readiness panel
Petstore (smoke test)
Use openapi.json from learn.openapis.org to preview the full SDK tree and compare generator timings without trimming.
Интеграция CI/CD
Pin Kiota CLI version in CI for reproducible builds: dotnet tool install Microsoft.OpenApi.Kiota --version x.y.z
Typical pipeline
- Lint OpenAPI with Spectral
- Run kiota validate or this readiness check
- kiota generate into src/generated
- Commit kiota-lock.json when used
- Run language tests against mock server or recorded fixtures
- Fail PR if git diff is non-empty after generation
For monorepos, generate per API package in parallel jobs. Store the spec as source of truth—client drift means the spec changed without regeneration.
Производительность для больших OpenAPI spec
Generation time and output size scale with operation count and schema depth.
- Graph-scale specs (10k+ operations): minutes and thousands of files—trim aggressively
- Memory: Kiota loads the full document; split multi-megabyte specs if CLI runs out of memory
- Compile time: smaller SDKs mean faster tsc and smaller npm packages
Rule of thumb (public specs)
- Petstore: ~1s, under 50 files
- Medium internal APIs: ~5–30s
- Graph-scale: path filtering required for acceptable developer experience
DevUtilities estimates generation seconds and file counts from your spec so you can benchmark before local runs.
Лучшие практики для больших spec
- Split specs by bounded context—separate packages for billing vs identity
- Use tags consistently so Kiota grouping matches team ownership
- Prefer components.schemas over inline anonymous objects
- Add operationId early in API design
- Version paths (/v1, /v2) and generate separate clients per major version
- Run readiness checks on every PR that touches the spec
- Centralize security schemes
- Strip x-internal endpoints in a build step before generate when generators cannot filter extensions
Обновление существующего SDK после изменений API
- Refresh OpenAPI spec from source when the API changes
- Diff the spec (openapi-diff or oasdiff)
- Regenerate the client and review git diff for breaking renames
- Treat operationId as a public contract—Kiota renames methods when operationId changes
- Additive changes (new optional properties) are usually safe; removed operations fail compile early
- Version spec in semver; tag generated releases to match
- Update kiota-lock.json after intentional Kiota CLI upgrades
- Communicate SDK updates via changelog entries derived from spec diff
Ограничения и обходные пути
- Clients only—Kiota does not generate server stubs
- Partial support: complex oneOf/allOf may simplify; callbacks and webhooks often skipped
- Binary formats may map to streams differently per language
- Weak typings when schemas are mostly untyped JSON blobs—improve at source
- Kiota cannot invent operationIds—you must supply or accept derived names
- WebSocket APIs are out of scope
When Kiota cannot model an edge case, fall back to raw fetch for that endpoint or post-process with wrapper methods. Watch Kiota release notes when upgrading.
Часто задаваемые вопросы
Развёрнутые ответы на типичные проблемы отладки и вопросы конфиденциальности данных.
Связанные инструменты
Ознакомьтесь с другими связанными утилитами, дополняющими этот инструмент.
Официальная документация и ссылки
Авторитетные спецификации и документация платформы для этой утилиты.