How DeepSeek API Authentication Works (and How to Do It Right)

Master DeepSeek API authentication with Bearer tokens, the Anthropic x-api-key header, key rotation and 401 fixes, with code for deepseek-flash and V4-Pro.

API·April 25, 2026·By DS Guide Editorial
Title card 'API Authentication', eyebrow 'API · Authentication', tagline 'One secret key, sent with every request.', with four items: 401 wrong API key, 402 out of balance, key in an environment variable, 2 base URLs.

You signed up at platform.deepseek.com, generated a key, pasted it into your script, and the response came back as a 401. Or your code worked yesterday and stopped working today. DeepSeek API authentication is short on surprises once you understand the model: a single secret key sent with every request — as an HTTP Bearer token on the OpenAI-compatible endpoint at https://api.deepseek.com. There is no OAuth flow, no signed request, no token-exchange dance. The complexity lives in how you store, rotate and recover that key — and in distinguishing authentication failures (401) from billing failures (402) when something breaks. This guide walks through the full authentication surface, with working Python and curl examples, key-handling patterns, and what changed for the legacy deepseek-chat and deepseek-reasoner model IDs.

What DeepSeek API authentication actually is

Diagram of DeepSeek API authentication flow with a bearer token from client to API gateway and model

DeepSeek uses a single authentication mechanism for its developer API: an API key. Its API reference lists the security scheme as HTTP Bearer Auth and asks you to create an API key first; on the OpenAI-format endpoints you send it as Authorization: Bearer YOUR_API_KEY. There is no separate signing step, no HMAC, no rotating session token. The server checks the key on each request and either accepts it or returns a 401.

Two things make that simple model worth a dedicated article. First, DeepSeek’s docs say: “The DeepSeek API uses an API format compatible with OpenAI/Anthropic. By modifying the configuration, you can use the OpenAI/Anthropic SDK or softwares compatible with the OpenAI/Anthropic API to access the DeepSeek API.” Anthropic-format support was announced with DeepSeek-V3.1 in August 2025. The same DeepSeek key therefore authenticates two request shapes, each with its own base URL and header. Second, the API is stateless — every request must carry both the key and the full conversation history. There is no session you log into; the header is the entire handshake.

Quickstart: authenticate your first request

Below is the minimum authenticated request, in two forms, following DeepSeek’s Your First API Call page. Both target the chat endpoint POST /chat/completions on https://api.deepseek.com. Set DEEPSEEK_API_KEY as an environment variable before running either snippet.

curl

curl https://api.deepseek.com/chat/completions \
  -H "Content-Type: application/json" \
  -H "Authorization: Bearer ${DEEPSEEK_API_KEY}" \
  -d '{
        "model": "deepseek-flash",
        "messages": [
          {"role": "system", "content": "You are a helpful assistant."},
          {"role": "user", "content": "Hello!"}
        ],
        "thinking": {"type": "enabled"},
        "reasoning_effort": "high",
        "stream": false
      }'

Python with the OpenAI SDK

The official OpenAI Python SDK works against DeepSeek by changing only base_url and api_key. Install it with pip install openai, then:

import os
from openai import OpenAI

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

response = client.chat.completions.create(
    model="deepseek-flash",
    messages=[
        {"role": "system", "content": "You are a helpful assistant."},
        {"role": "user", "content": "Hello"},
    ],
    stream=False,
    reasoning_effort="high",
    extra_body={"thinking": {"type": "enabled"}},
)
print(response.choices[0].message.content)

Thinking mode is on by default for both deepseek-flash and deepseek-v4-pro; the reasoning_effort parameter and the extra_body thinking flag make it explicit, and the response returns reasoning_content alongside the final content. Authentication itself is the same regardless of mode or model. For the full request reference, see our DeepSeek API documentation guide.

Where keys live: the platform.deepseek.com console

Every key originates on the DeepSeek platform. DeepSeek’s docs link the step “create an API key” to the API keys page at platform.deepseek.com, and the same platform is where you top up your balance — DeepSeek’s Error Codes page sends 402 errors to its Top up page. A key with no balance behind it still authenticates, but requests fail with 402 Insufficient Balance.

When you create a key, give it a name you will recognise later (for example, by environment) and copy it into your secret store straight away. If you lose a key, create a new one and delete the old one rather than trying to recover it. For the full sign-up walkthrough including billing, see our dedicated get a DeepSeek API key tutorial.

What a key looks like and what it can do

  • Format: an opaque secret string. Treat it as a password — never log it, never embed it in client-side bundles.
  • Scope: DeepSeek’s docs describe no per-key scopes (read-only, model-restricted or IP-restricted keys) as of October 2026, so treat every key as able to call any model and spend your balance.
  • Expiry: the docs do not describe automatic key expiry or rotation; plan to rotate keys yourself.
  • Rate limiting: DeepSeek calculates concurrency limits at the account level, regardless of which API key is used — 2,500 concurrent requests for deepseek-flash and 500 for deepseek-v4-pro — so generating more keys does not add throughput. See our DeepSeek API rate limits reference.

The Authorization header in detail

On the OpenAI-format endpoints, the header has one shape:

Authorization: Bearer <your DeepSeek API key>

Common ways to get this wrong:

  1. Missing the literal word “Bearer”. The Bearer scheme needs the word before the key; a bare key in the header will not authenticate.
  2. Wrong header for the endpoint. Query-string keys are not part of DeepSeek’s documented scheme. The x-api-key header is documented for the Anthropic-format endpoint (see below), not as a replacement for the Bearer header on /chat/completions.
  3. Whitespace or newlines in the key. Pasting from a terminal that wrapped the line, or a trailing newline in a secrets file, corrupts the value.
  4. Stale environment variable. If you rotated the key but your serverless runtime cached the old value, requests look authenticated to your code and unauthenticated to DeepSeek.

OpenAI vs Anthropic compatibility — same key, two surfaces

DeepSeek exposes two SDK-compatible request formats, each at its own base URL. The same DeepSeek API key works for both; only the base URL, the header and the request body schema differ.

Surface Base URL SDK Auth header
OpenAI-compatible (Chat Completions; also the Responses API format) https://api.deepseek.com openai-python, openai-node Authorization: Bearer <key>
Anthropic-compatible (Messages) https://api.deepseek.com/anthropic anthropic-python, anthropic-sdk-typescript x-api-key: <key> (listed as fully supported in DeepSeek’s Anthropic API guide)

DeepSeek’s Anthropic API guide configures the Anthropic SDK with two environment variables, which the SDK picks up automatically:

export ANTHROPIC_BASE_URL=https://api.deepseek.com/anthropic
export ANTHROPIC_API_KEY=${DEEPSEEK_API_KEY}

If you already maintain an Anthropic-shape codebase, the Anthropic surface is the smaller migration. Most new code should pick OpenAI-compatible. For a deeper treatment, see our DeepSeek OpenAI SDK compatibility reference.

Model IDs: current names and legacy IDs

Title card 'One Key, Two Headers', eyebrow 'Auth · Two formats', tagline 'Bearer for OpenAI format; x-api-key for Anthropic.', with four figures: 2 base URLs, 1 key for both, 2,500 concurrent requests for deepseek-flash and 500 for deepseek-v4-pro per account.

Authentication is decoupled from the model you target, but a wrong model ID returns an error that is easy to mistake for an auth failure (DeepSeek’s Anthropic API guide, for example, returns a 400 for unsupported model names that do not start with claude). Use the current IDs in new code:

  • deepseek-flash — served by DeepSeek-V4.1-Flash-1017; the default recommendation for most chat workloads, and the only current model with image input.
  • deepseek-v4-pro — served by DeepSeek-V4-Pro-0813.

The legacy IDs deepseek-chat and deepseek-reasoner were scheduled for retirement on 2026-07-24 15:59 UTC and are no longer listed in DeepSeek’s docs; until then they pointed to the non-thinking and thinking modes of deepseek-v4-flash. The names deepseek-v4-flash and deepseek-v4-flash-vision-exp are still accepted, but the original models are retired and those requests are served by DeepSeek-V4.1-Flash-1017 at the Flash price. Migrating is a one-line model= swap; the base_url and the key do not change. Detail on both models lives on our DeepSeek Flash and DeepSeek V4-Pro pages.

Authentication errors and what they actually mean

DeepSeek separates authentication problems from billing problems with two distinct status codes, which matters because the fix is different in each case. Its Error Codes page describes 401 Authentication Fails as “Authentication fails due to the wrong API key” and 402 Insufficient Balance as “You have run out of balance.”

Status Meaning (DeepSeek’s wording) What to check first
401 Authentication Fails Wrong API key Header format, key value, key not deleted, no whitespace; create a key if you don’t have one
402 Insufficient Balance You have run out of balance Check the balance and top up on the platform — the key is fine
400 Invalid Format Invalid request body format The request body, using the hints in the error message
422 Invalid Parameters Request contains invalid parameters Parameter names and values, using the hints in the error message
429 Rate Limit Reached Requests too fast, or over a concurrency or QPS limit Back off and retry; not an auth problem

A useful diagnostic when 401s appear out of nowhere: call DeepSeek’s Lists Models endpoint (GET https://api.deepseek.com/models) with your key in a curl request. If that returns 200, your key is valid and the bug is in your client code. If it returns 401, the key itself is the problem. For 402s, the GET /user/balance endpoint reports whether your balance is sufficient for API calls. Our DeepSeek API error codes reference covers the full list.

Security patterns for API keys

Bearer auth is only as safe as your key-handling discipline. These patterns are standard practice for API secrets and apply directly to DeepSeek keys.

Use environment variables, not source files

Hardcoding a key into config.py or a frontend bundle is the most common way keys leak. Read from os.environ in Python, process.env in Node, or a runtime secret manager (AWS Secrets Manager, HashiCorp Vault, GCP Secret Manager, 1Password Secrets Automation). For a deeper code-level treatment, see DeepSeek Python integration.

Never expose the key in browsers or mobile binaries

Never expose a live API key in browser JavaScript, mobile binaries, public Git repositories, or screenshots. If your product is a web app, route requests through your own backend and forward sanitised responses to the client. The backend holds the key; the browser never sees it. The same rule applies to mobile — keys embedded in an app binary can be extracted.

Rotate on a schedule and on incidents

Rotate keys on a fixed schedule (quarterly is a common choice) and immediately whenever a teammate leaves, a laptop is lost, or a CI secret is suspected of leaking. The flow is: create the new key on the platform, deploy it as the active secret, confirm requests succeed with it, then delete the old key. DeepSeek’s docs describe no automatic rotation, so this is a manual hygiene job — but it is cheap.

One key per environment, not per developer

Production, staging, and development each get their own key with a descriptive name (prod-2026-q4, staging, dev-shared). This lets you revoke a single environment without touching the others. Avoid one-key-per-developer; humans copy keys to laptops, phones, and shared scripts faster than you can audit them.

Watch billing and usage independently

A leaked key shows up first as unexpected spend, not as a 401. Check your balance regularly — DeepSeek’s API reference includes a Get User Balance endpoint you can poll — and use a tool like our DeepSeek cost estimator to baseline what “normal” looks like for your workload before you go live.

Cost worked example: what an authenticated call costs

Authentication is free; the request body is not. Below is a transparent cost calculation for a typical chat workload on deepseek-flash — 1,000,000 calls with a 2,000-token cached system prompt, a 200-token user message, and a 300-token response. Rates are USD per 1M tokens from DeepSeek’s Models & Pricing page as of October 2026. Peak hours are 01:00–04:00 and 06:00–10:00 UTC, Monday to Friday, excluding Chinese public holidays; all other hours are off-peak at half price.

                                         PEAK                       OFF-PEAK
Input, cache hit  : 2,000,000,000 × $0.006/M = $ 12.00     × $0.003/M = $  6.00
Input, cache miss :   200,000,000 × $0.30/M  = $ 60.00     × $0.15/M  = $ 30.00
Output            :   300,000,000 × $1.20/M  = $360.00     × $0.60/M  = $180.00
                                               -------                  -------
Total                                          $432.00                  $216.00

The same workload on deepseek-v4-pro ($0.044 cache hit / $1.32 cache miss / $3.96 output per 1M at peak; $0.022 / $0.66 / $1.98 off-peak) costs $88.00 + $264.00 + $1,188.00 = $1,540.00 at peak and $44.00 + $132.00 + $594.00 = $770.00 off-peak — about 3.6× Flash. Pick Flash unless deepseek-v4-pro measurably improves results on your own tasks. The cached-input line uses the cache-hit rate; the user message on each call is still an uncached miss against that prefix. Skipping the uncached line is a common cost-modelling mistake. For more detail, see our DeepSeek API pricing page.

Granted balances and free trials — read the small print

DeepSeek may offer a granted balance — a small promotional credit that can expire. Check the billing console for current offers before you build a business case around it, and don’t assume a permanent free tier for the API. DeepSeek’s Get User Balance endpoint reports the granted and topped-up balances separately, and fees are deducted from the granted balance first when both exist.

The API is stateless — auth doesn’t change that

Title card 'Stateless Calls', eyebrow 'Auth · Stateless API', tagline 'Send the key and full history with each request.', with four items: key read from an environment variable, full history sent per call, no server session, POST chat endpoint.

Even with a valid key, the API does not remember anything about your previous calls. There is no session to authenticate into. Every POST /chat/completions request must include the full messages array — system prompt, prior user turns, prior assistant turns — for the model to have context. The web chat at chat.deepseek.com keeps history for you; the API does not. If you are coming from the chat UI, this is the single biggest behavioural difference. For a primer on stitching multi-turn conversations together correctly, see our DeepSeek API getting started tutorial.

Where to go next

Once your authentication is solid, the natural next steps are streaming, function calling, and JSON mode — all of which use the same key you already have. For the broader landscape of developer-facing pages, the DeepSeek API docs and guides hub indexes everything in one place.

How do you authenticate with the DeepSeek API?

Create a key on the platform’s API keys page, then send it on every request as Authorization: Bearer YOUR_API_KEY. The chat endpoint is POST /chat/completions at https://api.deepseek.com. There is no OAuth flow — the key is the entire authentication mechanism. The same key also works on the Anthropic-compatible surface at https://api.deepseek.com/anthropic, where it goes in the x-api-key header. Step-by-step setup lives in our get a DeepSeek API key guide.

What does a 401 Unauthorized mean from the DeepSeek API?

DeepSeek calls it “401 Authentication Fails”: authentication failed because of the wrong API key — missing, mistyped, deleted, or sent without the literal “Bearer” prefix. It is not a billing problem; that returns 402. Confirm the header reads Authorization: Bearer <key> with no whitespace, then test the key against GET https://api.deepseek.com/models to isolate client-side bugs. The full status-code list lives in our DeepSeek API error codes reference.

Can you use the OpenAI Python SDK to authenticate against DeepSeek?

Yes. Install openai, then construct a client with base_url="https://api.deepseek.com" and your DeepSeek key as api_key. The SDK adds the Bearer header automatically and sends OpenAI-shape Chat Completions requests, which DeepSeek accepts. Apart from the model name, no changes are needed at the call sites; DeepSeek-specific fields such as thinking go in extra_body. Our DeepSeek OpenAI SDK compatibility reference covers edge cases.

Is the DeepSeek API key the same for the web chat and the developer API?

No. The web chat at chat.deepseek.com uses an account sign-in — DeepSeek’s Privacy Policy (10 February 2026) mentions an email address and/or telephone number with a password, or Apple or Google sign-in where available — and keeps conversation history for you. The developer API at api.deepseek.com uses an API key created on the platform, and is fully stateless — your client must resend conversation history with every call. DeepSeek’s docs don’t say whether chat and platform sign-ins are interchangeable, so sign in to each surface you need. See DeepSeek login for the chat side.

How should you store and rotate a DeepSeek API key?

Read it from an environment variable or a runtime secret manager — never hardcode it, never ship it in browser or mobile bundles. Use one key per environment with descriptive names (prod, staging, dev), rotate on a schedule and after any suspected leak, and delete old keys once the new one is confirmed working. Check your balance regularly so a leaked key shows up as unexpected spend before it costs you much. Our DeepSeek API best practices guide goes deeper.

Sources & Methodology

Last source check: October 25, 2026

Primary sources

Technical references

Context sources

Methodology

Pricing figures were checked against the official DeepSeek pricing page and normalised into estimated monthly costs using sample token usage scenarios. Actual costs may vary depending on caching, input/output ratio, regional availability, and provider updates.

Data confidence

High — figures checked directly against the official pricing page on the review date.

Editorial note

The site's pricing dataset is fetched daily from DeepSeek's official pricing page; this article reflects the prices on the date shown above.

Leave a Reply

Your email address will not be published. Required fields are marked *