Tool overview
O que é Kiota?
Kiota é o gerador de SDK da Microsoft para clientes tipados em C#, TypeScript, Python, Go, Java e mais. Esta página é a referência canónica do fluxo completo.
Porquê usar esta referência Kiota?
Valide a prontidão OpenAPI, pré-visualize SDKs, compare geradores e exporte comandos CLI — tudo no seu navegador.
Funcionalidades principais no DevUtilities
Fluxo Build My SDK de sete passos, pontuação de prontidão, explorador API e guias de problemas/soluções.
Como usar
Siga estes passos para obter resultados precisos com a ferramenta acima.
- Cole ou carregue a sua spec OpenAPI 3 JSON/YAML — ou comece com Petstore, GitHub ou metadados do Microsoft Graph.
- Revise a pontuação de prontidão OpenAPI e corrija erros bloqueantes com o painel de diagnóstico.
- Percorra o fluxo Build My SDK: Compreender → Validar → Configurar idioma e nome do cliente → Pré-visualizar estrutura SDK.
- Na Pré-visualização, use o Explorador API e as separadores multilíngue para inspecionar operações e modelos.
- Selecione apenas os endpoints que a sua aplicação precisa para reduzir o tamanho da saída.
- Configure autenticação mapeando securitySchemes para Bearer, chave API ou OAuth no passo Auth.
- Compare Kiota com OpenAPI Generator e NSwag usando estimativas de ficheiros e tempo por spec.
- Copie o comando kiota generate ou código de exemplo TypeScript/C# do passo Gerar.
- Execute a CLI Kiota localmente para emitir ficheiros no seu projeto.
- Integre o cliente com o seu fornecedor de auth, adicione testes e fixe a versão Kiota em CI.
Referência Kiota e biblioteca de problemas/soluções
Guias Kiota, comparações de geradores, autenticação, CI/CD e correcções OpenAPI. Última revisão July 2026.
Índice de guias Kiota — comece aqui
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.
O que é Kiota e quando usar
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 |
Matriz de suporte de idiomas
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.
Lista de prontidão OpenAPI para 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.
Correção: operationId duplicado
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.
Correção: erro de referência circular
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.
Correção: problemas de schema 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.
Padrões de autenticação com 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.
Gerar apenas endpoints selecionados
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
Regenerar SDK sem perder alterações personalizadas
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.
Exemplo completo: 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.
Exemplos reais: GitHub REST e 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.
Integração 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.
Desempenho com specs OpenAPI grandes
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.
Boas práticas para specs grandes
- 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
Atualizar SDK existente após mudanças na 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
Limitações e alternativas
- 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.
Perguntas frequentes
Respostas para problemas comuns e questões de privacidade de dados.
Ferramentas relacionadas
Explore outros utilitários relacionados que complementam esta ferramenta.
Documentação oficial e referências
Especificações e documentação da plataforma para esta utilidade.