DEV Community

Vanessa Massey
Vanessa Massey

Posted on

How to Get a Kimi API Key and Start Building in 5 Minutes (2026)


Quick Answer

Getting a Kimi K3 API key takes under 5 minutes: (1) sign up at platform.moonshot.ai, (2) create an API key from the console, (3) install the OpenAI SDK, (4) point the base URL to https://api.moonshot.ai/v1 with model ID kimi-k3. Your first API call costs about $0.007. For production use, route through TeamoRouter to get automatic failover and multi-provider stability without changing your code.

Step 1: Get Your API Key (2 Minutes)

1.1 Sign Up for a Moonshot Account

Go to the Moonshot developer platform:

Click Sign Up and create an account. You can use email or phone number registration. If you already have a Kimi (kimi.com) account, you can use the same credentials — the developer platform uses the same identity system.

1.2 Navigate to API Keys

Once logged in, you will see the developer console dashboard. In the left sidebar, click API Keys (or the key icon). This page shows all your existing keys and lets you create new ones.

1.3 Create a New Key

Click the Create or New API Key button. Give your key a descriptive name (e.g., "my-dev-machine" or "production-backend") so you can identify it later. Click confirm.

Important: Your API key will be displayed exactly once. It starts with sk- followed by a long string of characters. Copy it immediately and store it somewhere secure — a password manager, an environment variable file, or your secrets manager. Once you navigate away from the page, the full key will not be shown again. If you lose it, you will need to create a new one.

1.4 Add Funds to Your Account

Before you can make API calls, you need a balance. Go to the Billing or Balance section of the console and add funds. A few dollars is enough to start — at $0.007 per typical call, $5 gives you roughly 700 API calls. Moonshot supports credit card and Alipay/WeChat Pay (for China-based accounts).

Step 2: Install the SDK (30 Seconds)

Kimi K3 uses the standard OpenAI SDK. No special library or wrapper is needed.

Python

python -m pip install --upgrade "openai>=1.0"
Enter fullscreen mode Exit fullscreen mode

Requires Python 3.9 or later.

Node.js

npm install openai
Enter fullscreen mode Exit fullscreen mode

Or with your package manager of choice:

yarn add openai
pnpm add openai
bun add openai
Enter fullscreen mode Exit fullscreen mode

Step 3: Set Your Environment Variable (30 Seconds)

Store your API key as an environment variable. This keeps it out of your source code.

macOS / Linux

Add this to your ~/.zshrc or ~/.bashrc:

export MOONSHOT_API_KEY="sk-xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx"
Enter fullscreen mode Exit fullscreen mode

Then reload:

source ~/.zshrc
Enter fullscreen mode Exit fullscreen mode

Windows (PowerShell)

[System.Environment]::SetEnvironmentVariable('MOONSHOT_API_KEY', 'sk-xxx', 'User')
Enter fullscreen mode Exit fullscreen mode

Temporary (Current Terminal Only)

export MOONSHOT_API_KEY="sk-xxx"
Enter fullscreen mode Exit fullscreen mode

Using a .env File (Recommended for Projects)

Create a .env file in your project root:

MOONSHOT_API_KEY=sk-xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx
Enter fullscreen mode Exit fullscreen mode

Then load it in Python:

from dotenv import load_dotenv
load_dotenv()
Enter fullscreen mode Exit fullscreen mode

Or in Node.js with the dotenv package:

npm install dotenv
Enter fullscreen mode Exit fullscreen mode
import "dotenv/config";
Enter fullscreen mode Exit fullscreen mode

Never commit your .env file to git. Add .env to your .gitignore.

Step 4: Make Your First API Call (2 Minutes)

Python Example

Create a file called first_call.py:

import os
from openai import OpenAI

# Initialize the client with Kimi's endpoint
client = OpenAI(
    api_key=os.environ["MOONSHOT_API_KEY"],
    base_url="https://api.moonshot.ai/v1",
)

# Make your first API call
completion = client.chat.completions.create(
    model="kimi-k3",
    messages=[
        {"role": "system", "content": "You are a helpful assistant."},
        {"role": "user", "content": "Explain what Moonshot AI's Kimi K3 model is in two sentences."},
    ],
    max_completion_tokens=200,
)

print(completion.choices[0].message.content)
Enter fullscreen mode Exit fullscreen mode

Run it:

python first_call.py
Enter fullscreen mode Exit fullscreen mode

You should see a response from K3 in under 10 seconds.

Node.js Example

Create first_call.mjs:

import OpenAI from "openai";

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

const completion = await client.chat.completions.create({
  model: "kimi-k3",
  messages: [
    { role: "system", content: "You are a helpful assistant." },
    { role: "user", content: "Explain what Moonshot AI's Kimi K3 model is in two sentences." },
  ],
  max_completion_tokens: 200,
});

console.log(completion.choices[0].message.content);
Enter fullscreen mode Exit fullscreen mode

Run it:

node first_call.mjs
Enter fullscreen mode Exit fullscreen mode

Streaming Example (Real-Time Output)

For a typewriter-style experience, add streaming:

Python:

stream = client.chat.completions.create(
    model="kimi-k3",
    messages=[{"role": "user", "content": "Write a short poem about programming."}],
    stream=True,
)

for chunk in stream:
    if chunk.choices[0].delta.content:
        print(chunk.choices[0].delta.content, end="")
Enter fullscreen mode Exit fullscreen mode

Node.js:

const stream = await client.chat.completions.create({
  model: "kimi-k3",
  messages: [{ role: "user", content: "Write a short poem about programming." }],
  stream: true,
});

for await (const chunk of stream) {
  process.stdout.write(chunk.choices[0]?.delta?.content || "");
}
Enter fullscreen mode Exit fullscreen mode

Step 5: Migrate Existing OpenAI Code (Bonus — 30 Seconds)

Already have code that uses the OpenAI SDK? Switching to Kimi K3 requires exactly three changes:

# === Before (OpenAI) ===
from openai import OpenAI
client = OpenAI(api_key="sk-openai-xxx")
model = "gpt-4o"

# === After (Kimi K3) ===
from openai import OpenAI
client = OpenAI(
    api_key="sk-moonshot-xxx",                     # Change 1: Moonshot key
    base_url="https://api.moonshot.ai/v1",          # Change 2: Moonshot endpoint
)
model = "kimi-k3"                                   # Change 3: Model ID
Enter fullscreen mode Exit fullscreen mode

That is literally it. The request and response formats are identical to OpenAI's — K3 is a drop-in replacement at the SDK level. All your existing prompt engineering, message formatting, and response parsing code works without modification.

What to Remove

K3 has several parameters locked at launch. Remove these from your API calls:

  • temperature — K3 ignores or rejects this.
  • top_p — Same.
  • frequency_penalty and presence_penalty — Remove them.
  • reasoning_effort — Only "max" is available; remove the parameter unless you are explicitly setting it to "max".

If your existing code sets any of these, either comment them out or wrap them in a conditional based on the model being used.

Common Issues and How to Fix Them

"The api_key client option must be set"

You forgot to set the MOONSHOT_API_KEY environment variable, or you are not loading it correctly. Check with:

echo $MOONSHOT_API_KEY
Enter fullscreen mode Exit fullscreen mode

If nothing prints, the variable is not set. Re-run your export command or check your .env file.

"Invalid API key" or 401 Unauthorized

Possible causes:

  • Your API key is misspelled or truncated. Keys are long — copy-paste carefully.
  • You created the key but did not add funds. Go to the billing page and add a balance.
  • You are using the wrong endpoint. International users should use https://api.moonshot.ai/v1, China-based users should use https://api.moonshot.cn/v1.

"Model not found" or 404

Check your model ID. It must be exactly kimi-k3 — lowercase, with a hyphen, no spaces. Common mistakes: kimi_k3 (underscore), kimik3 (no hyphen), Kimi-K3 (mixed case).

429 Too Many Requests

You are being rate limited. Options:

  • Add exponential backoff to your retry logic.
  • Reduce the number of concurrent requests.
  • For production workloads, route through an API gateway like TeamoRouter that distributes traffic across multiple provider endpoints, effectively multiplying your rate limit capacity.

Slow Responses

K3's standard tier generates ~33-35 tokens per second. A 500-token response takes about 15 seconds. This is normal. To improve the experience:

  • Always use streaming so output appears incrementally rather than all at once after the full generation.
  • Consider the Kimi K3 Fast tier (~117 t/s) if latency is critical.

Vision/Image Uploads Failing

At launch, K3's API does not support public image URLs. You must pass images as base64-encoded strings or use file uploads. Do not use image_url with a remote URL — it will fail.

Beyond the Quickstart: Production Best Practices

1. Do Not Hardcode API Keys

Environment variables are the minimum. For production, use a secrets manager:

# AWS Secrets Manager
import boto3, json
secret = json.loads(boto3.client("secretsmanager").get_secret_value(SecretId="moonshot-api-key")["SecretString"])
api_key = secret["MOONSHOT_API_KEY"]
Enter fullscreen mode Exit fullscreen mode
// Google Cloud Secret Manager
const { SecretManagerServiceClient } = require("@google-cloud/secret-manager");
const client = new SecretManagerServiceClient();
const [version] = await client.accessSecretVersion({ name: "projects/my-project/secrets/moonshot-api-key/versions/latest" });
const apiKey = version.payload.data.toString();
Enter fullscreen mode Exit fullscreen mode

2. Use a Stable API Gateway for Production

Calling Moonshot's API directly works for development. For production applications that need reliability, a single-provider dependency is risky. Moonshot paused new subscriptions within 48 hours of K3's launch because demand exceeded GPU capacity — a direct API dependency would have meant downtime for your application.

TeamoRouter provides a stable API gateway layer:

Your App → TeamoRouter (single endpoint) → Kimi K3 (primary)
                                          → Kimi K3 (backup provider #1)
                                          → Kimi K3 (backup provider #2)
                                          → Fallback model (if all K3 providers down)
Enter fullscreen mode Exit fullscreen mode

Your code never changes — you swap base_url from api.moonshot.ai to TeamoRouter's endpoint, and TeamoRouter handles provider selection, health monitoring, and automatic failover. For teams building on K3, this is the difference between hoping the API stays up and knowing your application will keep running.

3. Implement Retry Logic

Even with a gateway, transient failures happen. Add robust retry logic:

import time
from openai import OpenAI, APIError

def call_with_retry(client, max_retries=3, **kwargs):
    for attempt in range(max_retries):
        try:
            return client.chat.completions.create(**kwargs)
        except APIError as e:
            if attempt == max_retries - 1:
                raise
            wait = 2 ** attempt  # Exponential backoff: 1s, 2s, 4s
            print(f"API error, retrying in {wait}s... ({e})")
            time.sleep(wait)
Enter fullscreen mode Exit fullscreen mode

4. Monitor Your Usage

Moonshot's console shows basic usage stats. For production monitoring, track:

  • Tokens per request (input and output separately).
  • Cache hit rate (higher is cheaper — aim for >80%).
  • Error rate and latency per endpoint.
  • Cost per task (total cost divided by number of completed user tasks).

5. Design for Caching

K3's context caching gives a 90% discount on cached input tokens. Structure your prompts so the cache works for you:

  • Put static content (system prompts, tool definitions, project rules) at the beginning of the message sequence.
  • Keep system prompts identical across requests. Avoid dynamic elements like timestamps or request IDs in the prefix.
  • Send related requests close together in time. The cache has a limited TTL.

Quick Reference: Endpoints and Model IDs

International API:  https://api.moonshot.ai/v1
China API:          https://api.moonshot.cn/v1
Model ID (API):     kimi-k3
Model ID (Kimi Code): k3
API Key Page:       platform.moonshot.ai → API Keys
Billing Page:       platform.moonshot.ai → Billing
SDK:                openai (Python pip install openai)
                    openai (Node.js npm install openai)
Enter fullscreen mode Exit fullscreen mode

Next Steps

Now that you have your API key and your first call working:

  1. Explore K3's capabilities. Try different prompt styles, system messages, and task types to understand where K3 excels and where it struggles. If you work with Go or frontend development, you are in K3's sweet spot.
  2. Set up for production. Route your API traffic through TeamoRouter for automatic failover, load balancing, and multi-provider resilience. Your base_url changes once — everything else stays the same, and you get production-grade reliability without building it yourself.
  3. Read the full pricing and setup guide. For a deeper dive into rate limits, caching strategies, and cost optimization, see our Kimi K3 API guide.
  4. Compare plans. If you are considering a Kimi subscription instead of (or in addition to) API access, read our Kimi K3 coding plan comparison.

Kimi K3 is the most exciting open-source model for developers in 2026. Five minutes to your first API call is all it takes to start building with it.

Top comments (0)