What is the DeepSeek API?

The DeepSeek API is a web service that sends your text to a DeepSeek model and returns the model's reply. Instead of typing into the chat app, your code sends a request and gets the answer back as data, so you can build it into a website, a support bot, a data pipeline, an internal tool or a script.

Its main features:

Compatible

OpenAI-style

Uses the same request format as OpenAI's API. Existing SDKs work once you change the base URL.

Flexible

Every model

Use V4.1 Flash, R1 and more by changing a single field.

Affordable

Pay per token

Prepaid, with no subscription. See API pricing.

Not a developer? You may not need the API at all. The free chat app covers most personal use, and Harness Desktop can work with your files without any code. It handles coding, documents and spreadsheets. Back to the DeepSeek AI home page.

Step 1 - Create an API key

  1. 1
    Open the API platform

    Go to platform.deepseek.com and sign in. The API account is separate from the chat app, so a chat login won't take you to the developer console. Having trouble? See the login guide.

  2. 2
    Add credit

    The API is prepaid. Top up a small balance under Billing; without credit, requests fail with a 402 error.

  3. 3
    Create and copy a key

    Open API keys → Create new key, name it after your project, and copy it straight away. It's only shown once.

  4. 4
    Store it safely

    Save it as an environment variable called DEEPSEEK_API_KEY. Never put it in your source code, a public repo or a browser app.

# Add to ~/.zshrc or ~/.bashrc to keep it across sessions
export DEEPSEEK_API_KEY="sk-your-key-here"

Step 2 - Send your first request

Every request goes to the chat completions endpoint and includes a model name and a list of messages. Pick your language:

# pip install openai
from openai import OpenAI
import os

client = OpenAI(
    api_key=os.environ["DEEPSEEK_API_KEY"],
    base_url="https://api.deepseek.com",
)

resp = client.chat.completions.create(
    model="deepseek-chat",   # confirm current model names in the API docs
    messages=[
        {"role": "system", "content": "You are a concise assistant."},
        {"role": "user",   "content": "Give me three names for a tea shop."},
    ],
)
print(resp.choices[0].message.content)
Already using OpenAI's SDK? Change only the base_url, the API key and the model name. Everything else stays the same.

Step 3 - Understand the response

{
  "id": "chatcmpl-7f3a…",
  "object": "chat.completion",
  "model": "deepseek-chat",
  "choices": [{
    "index": 0,
    "message": {
      "role": "assistant",
      "content": "1. Steep - Co.\n2. The Kettle Room\n3. Leaf Lane"
    },
    "finish_reason": "stop"
  }],
  "usage": {
    "prompt_tokens": 27,
    "completion_tokens": 19,
    "total_tokens": 46
  }
}
FieldWhat it means
choices[0].message.contentThe model's reply - usually the only part you need.
finish_reasonstop means it finished normally; length means it hit max_tokens and was cut off.
usageTokens used. This is what you're billed for.
modelWhich model answered.
idA unique ID for the request. Log it for debugging.

Choose a model

Change the model field to switch models. Start with Flash and move up only when a task needs it.

ModelUse it forSpeedCostGuide
V4.1 FlashDefault for chat, summaries, extraction, assistants and project developmentFastestLowestV4.1 Flash
R1 (reasoner)Maths, logic, planning, hard bugs. Returns its reasoning in a separate fieldSlowModerateR1
V4 ProLong, nuanced, high-stakes writing and analysisModerateHighestV4 Pro vs Flash
CoderCode completion, fill-in-the-middle and code generationFastLowCoder

Request parameters you'll actually use

ParameterWhat it doesTypical value
modelWhich model answers.The Flash model name for most tasks
messagesThe conversation so far: system sets behaviour, user is the person, assistant is the model's earlier replies.A system message plus the user's message
temperatureRandomness. Lower values are more predictable; higher values are more creative.0 for code and data, about 1 for writing
max_tokensThe longest the reply can be. Caps cost and length.Just above the length you expect
streamSends the reply in pieces as it's written.true for chat interfaces
response_formatAsks for valid JSON output.{"type": "json_object"}
toolsFunctions the model may call, including web search and fetch where supported.See tools
stopText that makes the model stop writing.["\n\n"] for one-paragraph answers

Multi-turn conversations

The API doesn't remember anything between requests. To hold a conversation, send the earlier messages again each time, adding the model's last reply and the user's new message:

history = [{"role": "system", "content": "You are a friendly travel guide."}]

def ask(text):
    history.append({"role": "user", "content": text})
    r = client.chat.completions.create(model="deepseek-chat", messages=history)
    reply = r.choices[0].message.content
    history.append({"role": "assistant", "content": reply})
    return reply

ask("Plan a day in Kandy.")
ask("Make it cheaper.")   # the model sees the first plan
Keep history short. You pay for every token you resend. For long chats, summarise older turns into a single message. With R1, don't send its reasoning back; include only the final content.

Streaming responses

Without streaming, your app waits for the whole reply. With stream=True, text arrives as it's written, so users see the answer appear right away. This matters most for longer replies and for R1, which thinks before it answers.

stream = client.chat.completions.create(
    model="deepseek-chat",
    messages=[{"role": "user", "content": "Write a short welcome note for new staff."}],
    stream=True,
)
for chunk in stream:
    piece = chunk.choices[0].delta.content
    if piece:
        print(piece, end="", flush=True)

Getting reliable JSON output

To get data your code can use directly, turn on JSON mode and describe the fields you want in the prompt:

r = client.chat.completions.create(
    model="deepseek-chat",
    response_format={"type": "json_object"},
    messages=[
        {"role": "system", "content": 'Return JSON: {"customer": str, "order_id": str, "urgent": bool}'},
        {"role": "user", "content": "Order #48213 arrived broken, need it by Friday - Nimali"},
    ],
)
import json; data = json.loads(r.choices[0].message.content)

Use the word "JSON" in your prompt, include an example of the shape you want, and check the result in your code before you rely on it.

Tools, web search and fetch

Tool calling (also called function calling) lets the model ask your code to do something, such as look up an order, check the weather or query a database. You describe each tool, the model replies with the tool it wants and the arguments to use, your code runs it, and you send the result back so the model can finish its answer.

Web search and fetch are built-in tools added in the V4.1-Flash-1017 update. They let the model search the web and read a page itself, so you don't have to build that part. They're ideal for questions about news, prices, documentation and anything else after the model's training cut-off. Setup, request format and examples are in our search - fetch guide.

Errors and how to fix them

CodeWhat it meansHow to fix it
400 Bad requestThe request body isn't in the right format.Check your JSON is valid and messages is a list of {role, content} objects.
401 UnauthorizedThe key is wrong, revoked or missing.Check the Authorization: Bearer header for typos or extra spaces, and make sure you're calling api.deepseek.com.
402 Insufficient balanceYour prepaid credit has run out.Top up under Billing on the API platform.
422 Invalid parametersA field has a value the API doesn't accept.Check the model name, the temperature range and the max_tokens limit.
429 Rate limitToo many requests in a short time.Retry after a short wait, waiting longer each time, and spread requests out.
500 Server errorSomething went wrong on DeepSeek's side.Retry after a short wait. If it continues, check updates for known issues.
503 OverloadedServers are busy, usually right after a release.Retry with longer waits, or try again later.
finish_reason: lengthThe reply was cut off.Raise max_tokens, or ask for a shorter answer.
# Simple retry that waits longer each time
import time
for attempt in range(5):
    try:
        r = client.chat.completions.create(model="deepseek-chat", messages=msgs)
        break
    except Exception as e:
        if attempt == 4: raise
        time.sleep(2 ** attempt)   # 1s, 2s, 4s, 8s

Pricing and cost control

You pay per million tokens, with separate prices for input (what you send) and output (what the model writes). Output costs more, and repeated input can be billed at a lower cached rate. As a rough guide, 1,000 tokens is about 750 English words.

TipWhy it saves moneyHow
Default to FlashIt's the cheapest model, and good enough for most tasks.Send hard cases to R1 or V4 Pro only when Flash isn't enough.
Keep the start of the prompt identicalRepeated input can be billed at the cached rate.Put the fixed system prompt and instructions first, in exactly the same words every time.
Cap the outputOutput tokens cost the most.Set max_tokens, and ask for short or JSON-only replies.
Trim historyYou pay to resend old messages.Summarise older turns into one message.
Watch usageCatches expensive prompts early.Log token counts per request and set up alerts.

Security best practices

DoWhy
Keep keys on the serverAnyone can read a key placed in browser JavaScript or a mobile app. Send requests through your own backend instead.
Use one key per projectIf a key leaks, you can revoke it without breaking everything else.
Never commit keysAdd .env to .gitignore. Tools that scan code for secrets can catch mistakes before they're pushed.
Rotate keys regularlyLimits the damage if a key was exposed without you knowing.
Treat user input with careUsers can try to override your system prompt. Don't let the model's output trigger sensitive actions without checking it first.
Don't send secrets in promptsPrompts are processed on DeepSeek's servers. For sensitive data, consider self-hosting open-weight models.

DeepSeek API - frequently asked questions

Is the DeepSeek API free?

No. It's prepaid and charged per token. The chat app is free, and you can get it from the download page.

Is the API compatible with OpenAI's SDK?

Yes. Point the official OpenAI SDK, or any compatible library, at https://api.deepseek.com with your DeepSeek key and a DeepSeek model name.

Which model should I start with?

V4.1 Flash. It's the fastest and cheapest. Move to R1 for reasoning, or V4 Pro for top quality, only when you need to.

Does the API remember previous messages?

No. Each request stands alone. Send the conversation history in messages each time. See multi-turn conversations.

Can the API search the web?

Yes, with the web search and fetch tools. See the search - fetch guide.

How do I get R1's reasoning?

Call the reasoner model. The response has the reasoning in reasoning_content and the answer in content. Details on the R1 page.

What are the rate limits?

Limits depend on your account and on demand. If you get a 429 error, wait and retry, waiting longer each time. The current limits are shown in the console on the API platform.

Is this the official DeepSeek documentation?

No. DeepSeekR1.com is an independent guide site. For the official reference, use the docs on the API platform. See about us, our disclaimer, privacy policy and terms.

Stuck on something? Contact us with the error message.