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:
OpenAI-style
Uses the same request format as OpenAI's API. Existing SDKs work once you change the base URL.
Step 1 - Create an API key
- 1Open 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.
- 2Add credit
The API is prepaid. Top up a small balance under Billing; without credit, requests fail with a 402 error.
- 3Create 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.
- 4Store 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"
# Current session
$env:DEEPSEEK_API_KEY = "sk-your-key-here"
# Permanently, for your user
setx 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)
curl https://api.deepseek.com/chat/completions \
-H "Content-Type: application/json" \
-H "Authorization: Bearer $DEEPSEEK_API_KEY" \
-d '{
"model": "deepseek-chat",
"messages": [
{"role": "system", "content": "You are a concise assistant."},
{"role": "user", "content": "Give me three names for a tea shop."}
]
}'
// npm install openai
import OpenAI from "openai";
const client = new OpenAI({
apiKey: process.env.DEEPSEEK_API_KEY,
baseURL: "https://api.deepseek.com",
});
const resp = await client.chat.completions.create({
model: "deepseek-chat",
messages: [
{ role: "system", content: "You are a concise assistant." },
{ role: "user", content: "Give me three names for a tea shop." },
],
});
console.log(resp.choices[0].message.content);
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
}
}
| Field | What it means |
|---|---|
choices[0].message.content | The model's reply - usually the only part you need. |
finish_reason | stop means it finished normally; length means it hit max_tokens and was cut off. |
usage | Tokens used. This is what you're billed for. |
model | Which model answered. |
id | A 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.
| Model | Use it for | Speed | Cost | Guide |
|---|---|---|---|---|
| V4.1 Flash | Default for chat, summaries, extraction, assistants and project development | Fastest | Lowest | V4.1 Flash |
| R1 (reasoner) | Maths, logic, planning, hard bugs. Returns its reasoning in a separate field | Slow | Moderate | R1 |
| V4 Pro | Long, nuanced, high-stakes writing and analysis | Moderate | Highest | V4 Pro vs Flash |
| Coder | Code completion, fill-in-the-middle and code generation | Fast | Low | Coder |
Request parameters you'll actually use
| Parameter | What it does | Typical value |
|---|---|---|
model | Which model answers. | The Flash model name for most tasks |
messages | The 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 |
temperature | Randomness. Lower values are more predictable; higher values are more creative. | 0 for code and data, about 1 for writing |
max_tokens | The longest the reply can be. Caps cost and length. | Just above the length you expect |
stream | Sends the reply in pieces as it's written. | true for chat interfaces |
response_format | Asks for valid JSON output. | {"type": "json_object"} |
tools | Functions the model may call, including web search and fetch where supported. | See tools |
stop | Text 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
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
| Code | What it means | How to fix it |
|---|---|---|
| 400 Bad request | The request body isn't in the right format. | Check your JSON is valid and messages is a list of {role, content} objects. |
| 401 Unauthorized | The 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 balance | Your prepaid credit has run out. | Top up under Billing on the API platform. |
| 422 Invalid parameters | A field has a value the API doesn't accept. | Check the model name, the temperature range and the max_tokens limit. |
| 429 Rate limit | Too many requests in a short time. | Retry after a short wait, waiting longer each time, and spread requests out. |
| 500 Server error | Something went wrong on DeepSeek's side. | Retry after a short wait. If it continues, check updates for known issues. |
| 503 Overloaded | Servers are busy, usually right after a release. | Retry with longer waits, or try again later. |
finish_reason: length | The 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.
| Tip | Why it saves money | How |
|---|---|---|
| Default to Flash | It'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 identical | Repeated 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 output | Output tokens cost the most. | Set max_tokens, and ask for short or JSON-only replies. |
| Trim history | You pay to resend old messages. | Summarise older turns into one message. |
Watch usage | Catches expensive prompts early. | Log token counts per request and set up alerts. |
Security best practices
| Do | Why |
|---|---|
| Keep keys on the server | Anyone can read a key placed in browser JavaScript or a mobile app. Send requests through your own backend instead. |
| Use one key per project | If a key leaks, you can revoke it without breaking everything else. |
| Never commit keys | Add .env to .gitignore. Tools that scan code for secrets can catch mistakes before they're pushed. |
| Rotate keys regularly | Limits the damage if a key was exposed without you knowing. |
| Treat user input with care | Users 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 prompts | Prompts 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.