Tool overview
什么是 Kiota?
Microsoft OpenAPI SDK 產生器 — 完整工作流参考。
為什么使用此 Kiota 参考
驗證 OpenAPI 就绪度、预覽 SDK、比较產生器 — 客戶端处理。
DevUtilities 核心功能
七步 Build My SDK、就绪度评分、API 瀏覽器、认证向導。
使用方法
按照以下步骤使用上方工具并获得准确結果。
- 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 指南、產生器對比、认证、CI/CD。最后更新 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.
Kiota 的 OpenAPI 就绪清單
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.
仅產生選定端点
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 规范的性能
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.
大型规范最佳实践
- 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
API 变更后更新现有 SDK
- 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.
常见問題
關于常见调试問題和数據私隱的可展開解答。
相關工具
探索可与此工具配合使用的其他相關实用工具。
官方文件与参考
本工具的权威规范与平台文件。