Kimi API Guide: Setup and First Request

The Kimi API is Moonshot AI’s programmatic route to Kimi models. It uses an OpenAI-compatible Chat Completions format, so you can call it with plain HTTP or the OpenAI Python and Node.js SDKs after changing the base URL.

This guide shows the shortest safe setup for a text request. The code is based on Kimi’s official documentation checked on August 4, 2026.

Test status: We checked these examples line by line against the current official quickstart, but did not create, reveal or use a paid API key for this draft. Do not describe the samples as independently executed until a controlled test is recorded under our testing methodology.

What you need

  • A Kimi API Platform account
  • An API key created at platform.kimi.ai
  • At least the minimum usable balance required by your account
  • cURL, or Python/Node.js with a current OpenAI SDK
  • A server-side environment where the key will not be exposed to visitors

Kimi’s current rate-limit page says at least a $1 recharge is required to start API use. Promotions, vouchers and payment methods can vary, so check the live console.

Kimi API endpoint and authentication

SettingValue
Service addresshttps://api.moonshot.ai
SDK base URLhttps://api.moonshot.ai/v1
Chat Completions endpointhttps://api.moonshot.ai/v1/chat/completions
Authorization headerAuthorization: Bearer $MOONSHOT_API_KEY
Request content typeapplication/json

Never put an API key in client-side JavaScript, a public repository, a screenshot or an error log. Create different keys for development and production so either can be revoked without taking down every integration.

Step 1: create an API key

  1. Sign in at the Kimi API Platform.
  2. Open API Keys in the console.
  3. Create a new key for this project.
  4. Copy it once and store it in a password manager or secret manager.
  5. Do not paste the key into this website or send it by email.

If a key is ever exposed, revoke it in the platform console and replace it immediately.

Step 2: store the key as an environment variable

Kimi’s documentation uses the variable name MOONSHOT_API_KEY.

macOS or Linux

export MOONSHOT_API_KEY="YOUR_KIMI_API_KEY"

PowerShell

$env:MOONSHOT_API_KEY="YOUR_KIMI_API_KEY"

These examples set the variable for the current shell session. For production, use the secret-management system provided by your hosting platform rather than committing a .env file.

Step 3: choose a model

Model IDBest starting useContextImportant note
kimi-k3Strongest current general capability, long-context coding and knowledge work1MAlways reasons; supports top-level reasoning_effort
kimi-k2.7-codeCoding-focused evaluations and agents256KThinking-mode coding model
kimi-k2.7-code-highspeedCoding where lower response latency matters256KHigher-speed variant; verify its current price
kimi-k2.6Lower-cost general chat, multimodal and agent baseline256KSupports thinking and non-thinking modes

Kimi recommends K3 as the general quickstart. A model with a larger context or higher price is not automatically better for every task; compare outputs and cost using your own evaluation set.

Step 4: make a request with cURL

curl https://api.moonshot.ai/v1/chat/completions \
  -H "Content-Type: application/json" \
  -H "Authorization: Bearer $MOONSHOT_API_KEY" \
  -d '{
    "model": "kimi-k3",
    "messages": [
      {
        "role": "user",
        "content": "Return only the result of 17 multiplied by 24."
      }
    ],
    "reasoning_effort": "low",
    "max_completion_tokens": 64
  }'

The response should be JSON with a choices array and a usage object. Because model output is nondeterministic, this guide does not promise exact wording. Your application should parse the response structure and handle missing or error responses safely.

Python example

Install the SDK:

pip install --upgrade "openai>=1.0"

Then create a client with Kimi’s base URL:

import os
from openai import OpenAI

client = OpenAI(
    api_key=os.environ["MOONSHOT_API_KEY"],
    base_url="https://api.moonshot.ai/v1",
)

response = client.chat.completions.create(
    model="kimi-k3",
    messages=[
        {
            "role": "user",
            "content": "Return only the result of 17 multiplied by 24.",
        }
    ],
    reasoning_effort="low",
    max_completion_tokens=64,
)

print(response.choices[0].message.content)
print(response.usage)

The official API overview requires OpenAI SDK 1.0.0 or later. Its general overview lists Python 3.7.1 or later, while the newer quickstart recommends Python 3.8 or later; use Python 3.8 or newer to satisfy both pages.

Node.js example

Install the SDK:

npm install openai@latest

Create the client and call K3:

const OpenAI = require("openai");

const client = new OpenAI({
  apiKey: process.env.MOONSHOT_API_KEY,
  baseURL: "https://api.moonshot.ai/v1",
});

async function main() {
  const response = await client.chat.completions.create({
    model: "kimi-k3",
    messages: [
      {
        role: "user",
        content: "Return only the result of 17 multiplied by 24.",
      },
    ],
    reasoning_effort: "low",
    max_completion_tokens: 64,
  });

  console.log(response.choices[0].message.content);
  console.log(response.usage);
}

main().catch((error) => {
  console.error(error.status, error.message);
  process.exitCode = 1;
});

The official documentation specifies Node.js 18 or later.

Read the usage data

A successful Chat Completions response can report:

  • prompt_tokens — input processed for the request;
  • completion_tokens — generated output;
  • total_tokens — combined token count; and
  • cached_tokens — input served through caching, when reported.

Store these values with the model name and timestamp for cost monitoring. Do not log the API key, private prompts or full responses containing sensitive data.

Use our Kimi API pricing calculator method to translate token counts into approximate cost.

Streaming responses

Set stream: true when you want tokens delivered incrementally rather than waiting for the complete response. Streaming can improve perceived latency for chat interfaces, but your code must handle server-sent events, partial content, disconnects and retries.

Do not automatically retry a partially completed request without considering duplicate cost and duplicate side effects.

Multimodal input

The current Kimi quickstart says K3, K2.7 Code and K2.6 accept text, image and video input. It recommends file uploads for larger video or media reused across requests, with images no larger than 4K and videos no larger than 1080p.

Multimodal support does not mean every file format or URL is accepted. Start with the official payload examples and test one small, non-sensitive asset before designing a production pipeline.

Common Kimi API errors

StatusMeaningFirst checks
400Invalid requestModel name, JSON shape, parameter compatibility and context size
401Authentication failedMissing, invalid or revoked key; malformed Bearer header
429Rate limit exceededAccount limits, concurrency, RPM/TPM/TPD and retry timing
500 / 5xxServer-side failureCapture request ID if available; retry with bounded backoff
504Request timeoutReduce workload, use streaming where appropriate, or split the task

Kimi’s Help Center says a single request can have a two-hour timeout. That is not a recommended client timeout. Production applications need their own cancellation, retry and idempotency strategy.

A safer retry pattern

  • Retry only transient 429 and 5xx failures.
  • Use exponential backoff with random jitter.
  • Cap the retry count and total elapsed time.
  • Respect any server-provided retry instruction.
  • Do not retry 401 until the key problem is fixed.
  • Log metadata, not secrets.
  • Review whether a repeated tool call could create duplicate external actions.

Pre-production checklist

  • [ ] API key stored in a server-side secret manager
  • [ ] Development and production keys separated
  • [ ] Current model ID confirmed through /v1/models
  • [ ] Maximum output and application timeouts set
  • [ ] 400, 401, 429 and 5xx responses handled
  • [ ] Usage and cost monitored without logging sensitive content
  • [ ] User input and model output treated as untrusted data
  • [ ] Tool permissions restricted to the minimum required
  • [ ] Privacy, retention and vendor terms reviewed
  • [ ] A small reproducible evaluation run before launch

Frequently asked questions

Is the Kimi API compatible with the OpenAI API?

Kimi documents compatibility with the OpenAI Chat Completions request and response format. Point the SDK to https://api.moonshot.ai/v1. Kimi-specific parameters and unsupported OpenAI features still need separate review.

Can I use my Kimi membership as API credit?

No. Kimi Membership, Kimi Code and the Kimi API Open Platform are separate billing routes.

Which model should I start with?

Kimi’s current quickstart recommends kimi-k3. For a cost baseline, compare it with kimi-k2.6; for a coding-specific task, include kimi-k2.7-code in your evaluation.

Can I put the API key in a WordPress page?

No. Anything delivered to a visitor’s browser can be copied. Keep the key on the server and expose only a controlled application endpoint with authentication, validation and spend protection.

Verification and limitations

This draft was checked against Kimi’s official API documentation on August 4, 2026. No paid API call was made and no secret was accessed. Before publication, KI AI Team should run the minimal request with a restricted test key, record the response status, model ID, SDK version, usage and actual cost, then update this section without publishing the key or private account data.

Corrections are welcome through Sources & Corrections.

Official sources