API

DeepSeek / Developer guide

DeepSeek API:
from key to first response.

Use a DeepSeek Platform API key to send a text request. Start with the runnable Python or Bash/cURL example, then check the answer, token usage and errors. We ran the Python example once against the official API and show its first result below.

By China AI Chat Team · Official documentation reviewed September 23, 2026 · Live Python request September 23; Bash/cURL checked offline · How we research

1. Get access to the official API

The developer API is separate from the consumer chat app. A signed-in chat session is not an API key, and consumer chat access does not include API credit. DeepSeek bills API token usage against your platform balance. See our DeepSeek pricing guide and calculator before sending requests.

  1. Open the official developer platform and sign in or complete its account setup.
  2. Check your available balance and any account requirements shown there. Do not assume a new account includes free credit.
  3. Create a key in the platform’s API keys area, linked from DeepSeek’s own documentation. Store it privately.
  4. Choose either the Python or cURL example below. Running both sends two separate requests.

A Together AI or OpenRouter key belongs to that provider. It does not authenticate requests to api.deepseek.com. Match the endpoint, key and model name to the same provider.

Keep keys off the public website. Run these examples on your own computer or server. For a web application, call DeepSeek from your backend and keep its key in a protected environment setting or secret store. Never put it in frontend JavaScript, a public repository, screenshots or logs. If exposed, revoke it at the provider and replace it.

2. Use the right endpoint and model

SettingValue for this guide
HTTP method and endpointPOST https://api.deepseek.com/chat/completions
Compatible SDK base URLhttps://api.deepseek.com
AuthenticationAuthorization: Bearer YOUR_DEEPSEEK_KEY — substitute privately, never in a published file
Content typeapplication/json
Model in the examplesdeepseek-flash
Alternative model identifierdeepseek-v4-pro

The current documentation maps deepseek-flash to DeepSeek-V4.1-Flash and deepseek-v4-pro to DeepSeek-V4-Pro-0813. Older Flash aliases may still be accepted while serving the replacement model. Check our model reference and DeepSeek’s current model mappings when updating an older integration.

DeepSeek documents both OpenAI-compatible and Anthropic-compatible formats. These examples use the former. The Anthropic-compatible base is https://api.deepseek.com/anthropic; follow its separate request guide. Compatible formats do not make providers’ keys, billing or every feature interchangeable.

3. Send one request with Python

This example uses Python 3’s standard library, so no extra package is required. Save it as deepseek_example.py. Run python3 deepseek_example.py on macOS/Linux, or py deepseek_example.py on Windows with the Python launcher installed. Use the command that runs Python 3 on your machine.

The script reads DEEPSEEK_API_KEY from the process environment if configured. Otherwise, it asks for the key without displaying it. Use a normal private terminal; it stops if hidden entry is unavailable. It does not save the key to the script or print request headers.

Example settings: one short prompt, thinking explicitly disabled, at most 256 generated tokens and a non-streaming response. DeepSeek enables thinking by default, so omitting the setting changes the example. The token ceiling covers output, not the entire request or a fixed dollar budget.

import getpass
import http.client
import json
import os
import warnings

# Stop if the terminal cannot hide typed credentials.
warnings.simplefilter("error", getpass.GetPassWarning)
key = os.environ.get("DEEPSEEK_API_KEY") or getpass.getpass("DeepSeek API key: ")
if not key.strip():
    raise SystemExit("No API key supplied.")

payload = {
    "model": "deepseek-flash",
    "messages": [{"role": "user", "content": "Explain an API in one sentence."}],
    "thinking": {"type": "disabled"},
    "max_tokens": 256,
    "stream": False,
}
connection = http.client.HTTPSConnection("api.deepseek.com", timeout=60)
try:
    connection.request(
        "POST", "/chat/completions",
        body=json.dumps(payload).encode("utf-8"),
        headers={
            "Authorization": f"Bearer {key}",
            "Content-Type": "application/json",
        },
    )
    response = connection.getresponse()
    if response.status != 200:
        raise SystemExit(f"HTTP {response.status}. Check the troubleshooting table.")
    response_body = response.read()
except (OSError, http.client.HTTPException):
    raise SystemExit("Connection failed or timed out. Check usage before retrying.")
except ValueError:
    raise SystemExit("Invalid request settings. Check the key privately.")
finally:
    connection.close()

try:
    data = json.loads(response_body)
except ValueError:
    raise SystemExit("The server did not return valid JSON.")

choices = data.get("choices") if isinstance(data, dict) else None
if not choices:
    raise SystemExit("No completion choice returned; inspect the response privately.")
choice = choices[0]
print("Answer:", choice.get("message", {}).get("content") or "[No answer text]")
print("Finish reason:", choice.get("finish_reason"))
print("Returned model:", data.get("model"))
print("Usage:", json.dumps(data.get("usage"), indent=2))

This script makes one request and does not automatically retry or follow redirects. Its 60-second timeout applies to blocking network operations, not a guaranteed total runtime or a billing cutoff. A timeout after sending a request does not prove the provider did no work.

If you prefer a compatible SDK, DeepSeek’s first-call documentation includes Python SDK examples. In the OpenAI Python SDK format, DeepSeek’s thinking setting goes inside extra_body. Use DeepSeek’s endpoint and key.

What our first live DeepSeek API request returned

We ran the exact Python example once on September 23, 2026 at 11:58 UTC, using Windows and Python 3.12.14. The key came from private encrypted storage. With deepseek-flash, thinking disabled, a 256-token cap and no streaming or retries, the official endpoint returned HTTP 200:

“An API is a set of rules that lets one piece of software request data or functionality from another.”

The answer satisfied “Explain an API in one sentence.” This checks a first connection, not accuracy on harder tasks.

Response fieldObserved value
Returned modeldeepseek-flash
Finish reasonstop
Input tokens11, all reported as cache misses
Generated tokens20; the 256-token setting was a ceiling, not the amount used
Total tokens31

At that UTC time, DeepSeek’s published off-peak Flash rates were $0.15 per million cache-miss input tokens and $0.60 per million output tokens. Applying them to the reported counts gives (11 × $0.15 + 20 × $0.60) / 1,000,000 = $0.00001365. This is our calculation, not an itemized provider charge; the account dashboard can round small amounts. It does not predict the cost of a longer prompt, reasoning, repeated calls or another pricing period. Use the calculator for your own token counts.

Test boundary: only the Python path made a live request. We previously checked the Bash/cURL payload and arguments offline, but did not execute that shell command against DeepSeek. We did not test streaming, thinking mode, multi-turn context, error responses or the model’s reliability. The returned model name is an API identifier; refer to the current official mapping for the underlying release.

Alternative: send the same request with cURL

Example status: checked offline, not executed against DeepSeek. The live result above came from Python.

Use this in Bash with curl 7.76.0 or later. It is not PowerShell syntax; Windows users can use the Python example or an installed Bash environment. Run it without shell tracing or verbose request logging.

The key is entered at a hidden prompt and passed to cURL through standard input rather than placed in its command-line arguments. The request body contains the same model, message and output limit as the Python example.

# Bash; curl 7.76.0 or later. Run in a private terminal without shell tracing.
(
read -r -s -p "DeepSeek API key: " DEEPSEEK_API_KEY
printf '\n'
if [ -z "$DEEPSEEK_API_KEY" ]; then
  printf 'No API key supplied.\n' >&2
  exit 1
fi
printf 'Authorization: Bearer %s\n' "$DEEPSEEK_API_KEY" | \
curl --silent --show-error --fail-with-body --max-time 60 \
  --header @- \
  --header 'Content-Type: application/json' \
  --data '{
    "model": "deepseek-flash",
    "messages": [{"role": "user", "content": "Explain an API in one sentence."}],
    "thinking": {"type": "disabled"},
    "max_tokens": 256,
    "stream": false
  }' \
  https://api.deepseek.com/chat/completions
request_status=$?
unset DEEPSEEK_API_KEY
exit "$request_status"
)

--fail-with-body retains the provider’s error body while making HTTP failures report a non-zero cURL status. The parentheses run the block in a subshell, which clears its key variable and returns that status without closing your terminal. --max-time 60 limits the whole cURL transfer; it is not a promise that provider-side processing or charges stop at that moment. This command has no automatic retry option. See the cURL manual for these options.

Check the answer, finish reason and usage

A successful HTTP status alone does not show that an answer finished. Read these fields from your actual response. The Python example prints the answer, finish reason, returned model field and usage object.

FieldWhat to check
choices[0].message.contentThe final answer text. Empty text requires investigation.
choices[0].finish_reasonstop indicates normal completion; length means the output hit a length limit. Other reasons can indicate filtering, tool calls, resource issues or an aborted response.
modelThe identifier returned by the service. Consult the current mapping rather than treating an alias as proof of a fixed historical release.
usage.prompt_tokensTotal input tokens, including context supplied in the request.
usage.completion_tokensTotal generated tokens. Reasoning tokens, when used, are a breakdown within completion usage; do not add them twice.
usage.prompt_cache_hit_tokens and prompt_cache_miss_tokensThe cached and uncached parts of input usage. Their sum is the prompt total.

These fields are defined in the official Chat Completions reference. Missing usage is unknown, not zero-cost usage. Use the pricing calculator with the reported counts and the applicable model and pricing period.

If the response ends with length, inspect the partial result before changing the prompt or increasing the limit. If you enable thinking later, allow for reasoning as well as final-answer tokens. Consult the thinking-mode guide; a tiny output limit may leave little room for an answer.

In our separate Flash vs Pro API comparison, both high-thinking code calls returned HTTP 200 but used their entire 4,096-token output caps as reasoning and delivered no final code. The first responses and a separate diagnostic are available there; inspect finish_reason and content even after a successful status.

Fix common DeepSeek API errors

Start with the HTTP status and a privately reviewed, redacted error message. The Python example prints only the status on HTTP failure; cURL also shows the returned body. Remove keys and private prompt content before sharing diagnostics.

Status or symptomNext action
400 — malformed requestCheck JSON syntax and message structure. Correct the request before resending it.
401 — authentication failedCheck that the key came from DeepSeek and is valid for this endpoint. Look for missing or accidental whitespace without printing the key.
402 — insufficient balanceCheck the developer-platform balance. A working consumer chat account does not resolve API billing.
422 — invalid parametersCheck the named parameter against the current model and endpoint documentation.
429 — request limit reachedReduce simultaneous requests and pace submissions. Current limits are calculated at account level, not separately for each key.
500 or 503 — service failure or overloadWait, then consider a bounded retry. Avoid a loop that repeatedly resends work.
Timeout or empty keep-alive linesCheck connectivity and provider usage before resending. Non-streaming requests can receive blank keep-alive lines while waiting; these are not an answer.
200, but no complete answerInspect finish_reason, content and usage. Do not treat truncation or an aborted response as success.

DeepSeek’s error-code guide documents the HTTP statuses. Its rate-limit and keep-alive guide explains account-level concurrency and waiting responses. Diagnose the cause before retrying; neither example implements a production retry policy.

Before you turn the example into an app

  • Conversation history: include the previous turns your application needs. The official chat’s saved conversations are not automatically attached to this request.
  • Tools and search: this text request has no browsing or tool loop. Use the relevant provider documentation and implement the required handling before advertising those features.
  • Usage controls: cap input, output, concurrency and retries on your server. A per-response token limit alone is not a monthly spending cap.
  • Results: review generated answers before relying on them. Treat model output as untrusted text when displaying it in an application.
  • Data handling: before processing real user or workplace data, check the application operator’s policy, DeepSeek’s platform terms and your approval route. Our DeepSeek safety guide separates official chat, API, third-party hosting and local models.

For a follow-up implementation, start with DeepSeek’s multi-round conversation guide and tool-call guide. Build one feature at a time so that each additional request and its cost remain visible.

Checks and implementation references

How we checked the examples

We reviewed DeepSeek’s official first-call, model/pricing and response documentation again on September 23, 2026. The exact Python example made one successful paid request to the official DeepSeek API that day; its unedited answer and usage are shown above. Eighteen earlier offline checks exercised the Python success and failure paths with fake credentials and simulated transport, and statically checked the Bash/cURL payload. Those simulations are not live error tests. We did not measure latency, execute Bash/cURL against the provider or test a production app.

Implementation references: Python HTTPS client, hidden key entry, and the cURL manual linked above. API behavior and model mappings can change; recheck the source before deploying.

Continue with DeepSeek models, API prices, our tested DeepSeek Vision API guide for image input, the DeepSeek Harness coding-agent guide, or the DeepSeek overview. Report an error in this guide.