The DeepSeek API lets your software send requests to DeepSeek’s hosted models and receive generated responses over HTTPS. You can use it for chat features, document workflows, coding assistance, and other application features without running the model on your own hardware.
To get started, create a DeepSeek API key, check your available API balance, and send a small request to https://api.deepseek.com/chat/completions. This guide provides curl, Python, and JavaScript examples, explains how to inspect the response, and compares the current models and prices.
Documentation and pricing reviewed November 21, 2026.
Quick reference
| Setting | Value |
|---|---|
| Official documentation | DeepSeek API Docs |
| API key management | DeepSeek Open Platform |
| Base URL for Chat Completions and Responses | https://api.deepseek.com |
| Model used in this tutorial | deepseek-flash |
| Chat Completions authentication | Authorization: Bearer YOUR_DEEPSEEK_API_KEY |
Jump to: API key setup · Code examples · Response fields · Models · Pricing · Features · Troubleshooting
Get a DeepSeek API Key and Prepare Your Account
DeepSeek Chat and the Open Platform share the same account, but API calls require an API key. The Open Platform terms also instruct developers to keep that key out of browser and other distributed client-side code.
- Open the official API key page and sign in to your DeepSeek account.
- Create an API key for your integration and keep it in a secure place.
- Check your available API balance. If you need funds, use the platform’s top-up page.
- Choose a terminal or backend environment for your first request.
The balance API distinguishes available grants from topped-up funds and provides is_available to indicate whether the balance is sufficient. Creating a credential and having usable API credit are separate requirements.
Store the Key in an Environment Variable
The examples read DEEPSEEK_API_KEY from the current process environment. These interactive commands let you enter the key without writing it into the script. Run your example from the same terminal afterward.
Bash on macOS, Linux, or Git Bash: Open a Bash terminal or run bash first, then enter the following commands.
read -rsp "DeepSeek API key: " DEEPSEEK_API_KEY
export DEEPSEEK_API_KEY
printf '\n'
Windows PowerShell 5.1 or later:
$deepseekSecret = Read-Host "DeepSeek API key" -AsSecureString
$env:DEEPSEEK_API_KEY = [System.Net.NetworkCredential]::new("", $deepseekSecret).Password
Remove-Variable deepseekSecret
PowerShell’s Read-Host command masks the entered secret. These settings apply to the current session and its child processes. For deployment, configure the key through your hosting environment’s secret-management settings.
For a website, send requests through your backend. Your browser interface should call that backend, which adds the DeepSeek credential. Shipping the credential in public JavaScript exposes it to anyone who can inspect the application.
DeepSeek API Examples: curl, Python, and JavaScript
Choose one example for your preferred environment. Each sends the same short prompt with thinking disabled, streaming disabled, and a 128-token output limit. Running an example makes a billable model request. The examples make one attempt and contain no automatic retry loop.
Option 1: Send a Request with curl
This command uses Bash syntax and a curl version that supports --fail-with-body. The double quotes around the authorization header allow the environment variable to expand. It follows the request structure in DeepSeek’s official quickstart.
curl --silent --show-error --fail-with-body \
https://api.deepseek.com/chat/completions \
-H "Authorization: Bearer ${DEEPSEEK_API_KEY:?Set DEEPSEEK_API_KEY first}" \
-H "Content-Type: application/json" \
-d '{
"model": "deepseek-flash",
"messages": [
{"role": "system", "content": "You are a concise technical assistant."},
{"role": "user", "content": "Explain an API in one sentence."}
],
"thinking": {"type": "disabled"},
"max_tokens": 128,
"stream": false
}'
curl prints the JSON response. Find the generated answer inside choices[0].message.content. If the server returns an HTTP error, --fail-with-body keeps its response body visible while making curl report failure.

Option 2: Use the DeepSeek API in Python
Save this as deepseek_example.py, then run python deepseek_example.py. It uses Python 3’s standard HTTP library, so no third-party package is required. Use python3 if that is the Python 3 command on your computer.
import json
import os
import urllib.error
import urllib.request
api_key = os.environ.get("DEEPSEEK_API_KEY")
if not api_key:
raise SystemExit("Set DEEPSEEK_API_KEY in this terminal first.")
payload = {
"model": "deepseek-flash",
"messages": [
{"role": "system", "content": "You are a concise technical assistant."},
{"role": "user", "content": "Explain an API in one sentence."},
],
"thinking": {"type": "disabled"},
"max_tokens": 128,
"stream": False,
}
request = urllib.request.Request(
"https://api.deepseek.com/chat/completions",
data=json.dumps(payload).encode("utf-8"),
headers={
"Authorization": "Bearer " + api_key,
"Content-Type": "application/json",
},
method="POST",
)
try:
with urllib.request.urlopen(request, timeout=120) as response:
data = json.load(response)
except urllib.error.HTTPError as error:
detail = error.read().decode("utf-8", errors="replace")
detail = detail.replace(api_key, "[REDACTED]")
raise SystemExit(f"DeepSeek HTTP {error.code}: {detail[:1000]}")
if data.get("error"):
detail = json.dumps(data["error"]).replace(api_key, "[REDACTED]")
raise RuntimeError("DeepSeek API error: " + detail[:1000])
choice = data["choices"][0]
answer = choice["message"].get("content")
if not isinstance(answer, str) or not answer.strip():
raise RuntimeError("No text answer was returned.")
print(answer)
print("Finish reason:", choice.get("finish_reason"))
print("Usage:", json.dumps(data.get("usage"), indent=2))
The script prints the answer, finish reason, and usage. Its timeout is a client-side networking setting, not a promise about service response time. An HTTP or network failure raises an exception instead of silently submitting another request.
Python Alternative: Use the OpenAI SDK
If your project already uses the OpenAI Python client, DeepSeek’s SDK example provides a familiar integration path. Install the package with python -m pip install openai, then save this as deepseek_sdk_example.py and run python deepseek_sdk_example.py.
import os
from openai import OpenAI
client = OpenAI(
api_key=os.environ["DEEPSEEK_API_KEY"],
base_url="https://api.deepseek.com",
max_retries=0,
)
response = client.chat.completions.create(
model="deepseek-flash",
messages=[
{"role": "system", "content": "You are a concise technical assistant."},
{"role": "user", "content": "Explain an API in one sentence."},
],
extra_body={"thinking": {"type": "disabled"}},
max_tokens=128,
stream=False,
)
choice = response.choices[0]
print(choice.message.content)
print("Finish reason:", choice.finish_reason)
print("Usage:", response.usage)
The extra_body argument carries DeepSeek’s thinking setting. This example sets max_retries=0 to disable automatic SDK retries, as documented in the Python SDK reference.
Option 3: Use the DeepSeek API with JavaScript and Node.js
Use Node.js 22 or newer, which includes fetch. Save this as deepseek_example.mjs and run node deepseek_example.mjs. This example runs in Node.js on your computer or server.
const apiKey = process.env.DEEPSEEK_API_KEY;
if (!apiKey) {
throw new Error("Set DEEPSEEK_API_KEY in this terminal first.");
}
const response = await fetch("https://api.deepseek.com/chat/completions", {
method: "POST",
headers: {
Authorization: "Bearer " + apiKey,
"Content-Type": "application/json"
},
body: JSON.stringify({
model: "deepseek-flash",
messages: [
{ role: "system", content: "You are a concise technical assistant." },
{ role: "user", content: "Explain an API in one sentence." }
],
thinking: { type: "disabled" },
max_tokens: 128,
stream: false
}),
signal: AbortSignal.timeout(120000)
});
const body = await response.text();
if (!response.ok) {
const detail = body.replaceAll(apiKey, "[REDACTED]").slice(0, 1000);
throw new Error("DeepSeek HTTP " + response.status + ": " + detail);
}
const data = JSON.parse(body);
if (data.error) {
const detail = JSON.stringify(data.error)
.replaceAll(apiKey, "[REDACTED]").slice(0, 1000);
throw new Error("DeepSeek API error: " + detail);
}
const choice = data.choices?.[0];
const answer = choice?.message?.content;
if (typeof answer !== "string" || !answer.trim()) {
throw new Error("No text answer was returned.");
}
console.log(answer);
console.log("Finish reason:", choice.finish_reason);
console.log("Usage:", JSON.stringify(data.usage ?? null, null, 2));
The response.ok check matters because an HTTP error still produces a fetch response. The abort signal supplies an example client timeout policy. Adjust application timeouts to your workload after the first request works.
Read the Response Before Calling the Integration Complete
The Chat Completions reference documents the following response fields:
| Field | What to inspect |
|---|---|
choices[0].message.content | The answer text for this simple request. |
choices[0].finish_reason | How generation ended. stop is a normal ending; length signals truncation. |
usage.prompt_tokens | Total input tokens. |
usage.completion_tokens | Generated output tokens. |
usage.prompt_cache_hit_tokens and usage.prompt_cache_miss_tokens | The cached and uncached portions of input. |
The exact wording of the answer and the token counts will vary. Check that the response answers your question, that generation finished appropriately, and that usage is available. A successful HTTP status establishes transport success; it does not establish factual accuracy or task completion.

When an answer ends with length, decide whether to shorten the requested response or provide a larger output allowance. Avoid automatically accepting truncated JSON, unfinished code, or a partial instruction as a complete result. Preserve missing usage as unavailable rather than converting it to zero.
Choose a Current DeepSeek API Model
Use the model IDs in the current model table. At the review date, the two documented choices are:
| API model ID | Serving version | Input |
|---|---|---|
deepseek-flash | DeepSeek-V4.1-Flash-1017 | Text and images |
deepseek-v4-pro | DeepSeek-V4-Pro-0813 | Text |
Flash is a practical starting point for this tutorial because its listed token prices are lower and it supports image input. Evaluate both models against your own examples before choosing one for a larger workload; a model name or higher price alone does not establish better results for your task.
For discovery, GET https://api.deepseek.com/models returns model identifiers and capability metadata. The documented model entries show a 1,048,576-token context capacity and a maximum output allowance of 393,216 tokens. Context capacity includes input and output; these ceilings are different from the default output allowance.
Keep the output limit modest for a small task. Large available limits are useful when the application needs them, but they are not a reason to request a long answer to a short question.
DeepSeek API Pricing and a Simple Cost Example
The following official prices are in USD per 1 million tokens and were checked on November 21, 2026.
| Model | Period | Input: cache hit | Input: cache miss | Output |
|---|---|---|---|---|
deepseek-flash | Off-peak | $0.003 | $0.15 | $0.60 |
deepseek-flash | Peak | $0.006 | $0.30 | $1.20 |
deepseek-v4-pro | Off-peak | $0.022 | $0.66 | $1.98 |
deepseek-v4-pro | Peak | $0.044 | $1.32 | $3.96 |
Peak periods are 01:00–04:00 and 06:00–10:00 UTC on weekdays, excluding Chinese public holidays. All other periods are off-peak. For U.S. scheduling, convert UTC using your location and the applicable date.

Estimate model-token cost using the actual usage counts:
Cost in USD =
(cached input tokens × cache-hit price
+ uncached input tokens × cache-miss price
+ output tokens × output price)
÷ 1,000,000
For an illustrative Flash off-peak request with 1,000 uncached input tokens and 500 output tokens, the calculation is:
Input: 1,000 × $0.15 ÷ 1,000,000 = $0.00015
Output: 500 × $0.60 ÷ 1,000,000 = $0.00030
Total: $0.00045
At those assumed token counts and rates, 1,000 requests would cost $0.45 in model tokens. This is an arithmetic example, not the observed cost of the short prompt above. Include billed retries, follow-up requests, and any separately priced services in an application budget.
Context caching automatically discounts eligible reused input. A hit requires matching a persisted prefix unit, so repeated wording does not guarantee a hit on the next call. Budget from observed usage and keep an all-miss estimate for comparison.
As of November 18, 2026, model-triggered server-side search and fetch have no separate per-call fee; returned context still contributes to token usage. Standalone Search and Fetch APIs remain separately priced. Check the service pricing sections when adding tools, file processing, or audio.
Add Thinking, Streaming, and Conversation History
Control Thinking Deliberately
Thinking is enabled by default, with high effort. For raw Chat Completions requests, thinking.type selects enabled or disabled, and reasoning_effort controls effort. The tutorial disables thinking to keep the first request simple. See the Thinking Mode guide.
In thinking mode, reasoning is returned in message.reasoning_content, while the final answer is in message.content. The temperature setting has no effect in that mode. If using the OpenAI Python SDK, pass DeepSeek’s thinking extension inside extra_body.
Evaluate a reasoning setting on representative tasks. Compare whether answers improve, how much output is generated, and how long the task takes. Keep the setting that meets your application’s requirements instead of assuming maximum effort is necessary for every request.
Stream Output When Your Interface Needs It
Set stream to true for incremental delivery. Chat Completions uses server-sent events ending in [DONE]; its final content chunk carries full usage. Read the streaming contract before replacing the nonstreaming parser.
The examples above expect one JSON response. Streaming requires an event parser or a compatible SDK streaming interface; simply changing the flag while retaining a single JSON-document parser is insufficient. Keep partial text separate from a completed answer if the connection drops.
Send the History Your Next Turn Needs
Chat Completions is stateless at the conversation level. Add the previous assistant reply and the new user message to the relevant history, then send that history in the next request. DeepSeek’s multi-round conversation guide shows this sequence.
For plain conversations, preserve the context needed to understand corrections and follow-up questions. Tool-enabled conversations have additional history requirements; use the documented tool flow when adding them. Context caching does not replace the messages your application must send.
What Else Can You Build with the DeepSeek API?
The API extends beyond text completions. DeepSeek’s chatbot feature guide describes built-in conversation features, while separate guides cover standalone services. Add the capability that directly supports your task after basic requests are working.
| Capability | Practical use | Implementation guide |
|---|---|---|
| JSON output | Request JSON with response_format: {"type":"json_object"} and explicitly instruct the model to return JSON. | JSON Output |
| Function calling | Receive proposed function calls, validate arguments, execute approved application functions, and return their results. | Tool Calls |
| Vision | Send images with text to deepseek-flash for screenshot, chart, or image analysis. | Vision |
| Document input | Upload and parse documents, then reference their file IDs in a supported conversation. | File Parsing |
| Web search and URL reading | With Flash, declare deepseek_web_search or deepseek_read_url for server-side retrieval. | Web Tools |
| OCR | Extract recognition results from documents or images without sending them through a chat model. | OCR |
| Speech | Generate audio from text or transcribe an uploaded audio file. | Text to Speech and Speech to Text |
Treat structured output as data to validate. The JSON guide warns that unusable generated content may be replaced with spaces, so check for blank output before parsing. A valid JSON document still needs application-level validation of required fields, types, and acceptable values.
For client-defined functions, the model proposes a call; your application controls execution. Check arguments and user permissions before an operation changes data or sends information elsewhere. Keep those checks in application code.
Built-in web tools can perform multiple inference steps in one conversational round. Their max_tokens setting applies per step, so it is not a hard total-spending ceiling for the whole round. The chatbot documentation explains this distinction.
Choose Chat Completions, Responses, or Messages
DeepSeek supports three conversation formats. The official endpoint map lists these routes:
| Format | Full HTTP endpoint | Common integration shape |
|---|---|---|
| Chat Completions | POST https://api.deepseek.com/chat/completions | Send messages; read choices. |
| Responses | POST https://api.deepseek.com/responses | Send input; read typed output items. |
| Messages | POST https://api.deepseek.com/anthropic/v1/messages | Use Anthropic-style messages and returned content blocks. |
For OpenAI-compatible clients, the base URL is https://api.deepseek.com. For Anthropic-compatible clients, use https://api.deepseek.com/anthropic. Use a DeepSeek credential for either route; the client library’s name does not determine which provider receives the request.

Review the Responses compatibility table or Messages compatibility table when migrating an existing application. For example, DeepSeek Responses does not support previous_response_id or conversation, and Messages ignores thinking.budget_tokens. Successful requests can therefore behave differently from an upstream provider’s API.
Choose the format your application already handles well. For a new small text integration, Chat Completions keeps the request and response straightforward. When porting a larger application, test its required features individually instead of treating a changed base URL as complete migration validation.
Troubleshoot Common DeepSeek API Problems
Use the returned HTTP status and error details to narrow the problem. The official error reference covers these common cases:
| Status or symptom | Next step |
|---|---|
Missing DEEPSEEK_API_KEY | Set the variable in the terminal or process running your code. |
| 400 or 422 | Correct the request format or invalid parameter identified by the error. |
| 401 | Check that the key is a DeepSeek key and that the authentication header is correct. |
| 402 | Check your API balance and add funds if needed. |
| 429 | Reduce request pressure or concurrency before retrying. |
| 500 or 503 | Wait briefly, check service status, and use a bounded retry policy. |
Answer cut off with finish_reason: "length" | Review the requested answer length, output allowance, and available context. |

The documented model concurrency limits are 2,500 simultaneous requests for Flash and 500 for Pro, counted across API keys in one account. These are concurrency limits, not requests per minute. See Rate Limit & Isolation for the rules that apply to your integration.
Use the official status page to investigate a possible service incident. For persistent failures, the API documentation lists [email protected] as the support contact. Keep the timestamp, model, request identifier when available, and error details; exclude your API key.
Correct authentication and request-format problems before retrying. For temporary failures, cap attempts and increase the delay between them. Repeatedly resubmitting an unchanged failing request can create more traffic and make the original issue harder to identify.
Before You Connect the API to Real Users
A successful test request is the beginning of an integration. Before wider use, make the behavior observable and decide what your application should do when the model cannot complete a task.
- Keep credentials on the backend. Configure secrets separately from public source code and frontend bundles.
- Record useful diagnostics. Track model selection, request status, finish reason, and token usage without indiscriminately logging private prompts.
- Validate results. Check generated data against your application’s requirements before storing or acting on it.
- Set a request policy. Define output allowances, client timeouts, bounded retries, and what users see when a request fails.
- Preserve user boundaries. For a multi-user service, review DeepSeek’s user_id isolation guidance alongside your own authentication and authorization.
- Evaluate representative tasks. Compare complete-task cost, response quality, and completion time before expanding traffic.
Add one feature at a time. Keeping a working text-only request available makes it easier to determine whether a later failure comes from credentials, the model request, a file, a tool, or your own application logic.
Frequently Asked Questions
Is the DeepSeek API Free?
The official API uses metered billing. Any free quota depends on the offer shown on the platform, as described in the platform terms. Check your account for available promotional credit; do not assume every new account receives a fixed free allowance.
Do I Need an OpenAI API Key to Use the OpenAI SDK?
For requests sent to DeepSeek, use a DeepSeek API key and configure the client’s base URL for DeepSeek. The official quickstart demonstrates this setup. Compatibility lets you reuse a client interface while sending requests to the selected provider.
What Should I Change in an Older R1 or V3 Tutorial?
Start with the currently supported model list and use deepseek-flash or deepseek-v4-pro as appropriate. Review the tutorial’s thinking settings, parameter support, and prices before copying it. An older example built around deepseek-chat or deepseek-reasoner should not be treated as current configuration guidance.
Does Context Caching Remember My Conversation?
No. Caching can reuse eligible input processing, while your application still supplies the context for each request. Follow the conversation-history guide and verify the actual cache usage instead of assuming earlier messages will be restored automatically.
Begin with one small request and confirm its answer, finish reason, and usage. Then select the model and additional features that meet your application’s needs, using the official documentation for each extension.
