Skip to content

Authentication

DeepSeek API uses API keys for authentication. You need to include your API key in the request headers to access our services.

Getting Your API Key

  1. Sign up for a DeepSeek account at https://platform.deepseek.com
  2. Navigate to the API Keys section in your dashboard
  3. Generate a new API key
  4. Copy and securely store your API key

Security Notice

Keep your API key secure and never expose it in client-side code or public repositories.

Authentication Methods

Bearer Token Authentication

Include your API key in the Authorization header using the Bearer token format:

bash
curl -X POST "https://api.deepseek.com/v1/chat/completions" \
  -H "Authorization: Bearer YOUR_API_KEY" \
  -H "Content-Type: application/json" \
  -d '{
    "model": "deepseek-chat",
    "messages": [
      {"role": "user", "content": "Hello, world!"}
    ]
  }'

API Key Header

Alternatively, you can pass the API key directly in a custom header:

bash
curl -X POST "https://api.deepseek.com/v1/chat/completions" \
  -H "X-API-Key: YOUR_API_KEY" \
  -H "Content-Type: application/json" \
  -d '{
    "model": "deepseek-chat",
    "messages": [
      {"role": "user", "content": "Hello, world!"}
    ]
  }'

SDK Authentication

Python

python
from openai import OpenAI

client = OpenAI(
    api_key="YOUR_API_KEY",
    base_url="https://api.deepseek.com/v1"
)

response = client.chat.completions.create(
    model="deepseek-chat",
    messages=[
        {"role": "user", "content": "Hello, world!"}
    ]
)

Node.js

javascript
import OpenAI from 'openai';

const client = new OpenAI({
  apiKey: 'YOUR_API_KEY',
  baseURL: 'https://api.deepseek.com/v1'
});

const response = await client.chat.completions.create({
  model: 'deepseek-chat',
  messages: [
    { role: 'user', content: 'Hello, world!' }
  ]
});

Go

go
package main

import (
    "context"
    "fmt"
    "github.com/sashabaranov/go-openai"
)

func main() {
    config := openai.DefaultConfig("YOUR_API_KEY")
    config.BaseURL = "https://api.deepseek.com/v1"
    client := openai.NewClientWithConfig(config)

    resp, err := client.CreateChatCompletion(
        context.Background(),
        openai.ChatCompletionRequest{
            Model: "deepseek-chat",
            Messages: []openai.ChatCompletionMessage{
                {
                    Role:    openai.ChatMessageRoleUser,
                    Content: "Hello, world!",
                },
            },
        },
    )
    
    if err != nil {
        fmt.Printf("Error: %v\n", err)
        return
    }
    
    fmt.Println(resp.Choices[0].Message.Content)
}

Environment Variables

For security and convenience, store your API key in environment variables:

Linux/macOS

bash
export DEEPSEEK_API_KEY="your_api_key_here"

Windows

cmd
set DEEPSEEK_API_KEY=your_api_key_here

Python with Environment Variables

python
import os
from openai import OpenAI

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

API Key Management

Best Practices

  1. Rotate Keys Regularly: Generate new API keys periodically and retire old ones
  2. Use Different Keys: Use separate API keys for different environments (development, staging, production)
  3. Monitor Usage: Regularly check your API usage and billing in the dashboard
  4. Restrict Access: Limit API key permissions to only what's necessary

Key Permissions

API keys can have different permission levels:

  • Read: Access to model information and account details
  • Write: Ability to make API calls and generate content
  • Admin: Full access to account settings and billing

Rate Limiting by Key

Each API key has its own rate limits based on your subscription plan:

  • Free Tier: 100 requests per minute
  • Pro Tier: 1,000 requests per minute
  • Enterprise: Custom limits based on agreement

Error Handling

Authentication Errors

Common authentication error responses:

Invalid API Key

json
{
  "error": {
    "message": "Invalid API key provided",
    "type": "invalid_request_error",
    "code": "invalid_api_key"
  }
}

Missing API Key

json
{
  "error": {
    "message": "You didn't provide an API key",
    "type": "invalid_request_error",
    "code": "missing_api_key"
  }
}

Expired API Key

json
{
  "error": {
    "message": "API key has expired",
    "type": "invalid_request_error",
    "code": "expired_api_key"
  }
}

Handling Authentication Errors

python
from openai import OpenAI
import openai

try:
    client = OpenAI(
        api_key="YOUR_API_KEY",
        base_url="https://api.deepseek.com/v1"
    )
    
    response = client.chat.completions.create(
        model="deepseek-chat",
        messages=[{"role": "user", "content": "Hello!"}]
    )
    
except openai.AuthenticationError as e:
    print(f"Authentication failed: {e}")
except openai.RateLimitError as e:
    print(f"Rate limit exceeded: {e}")
except Exception as e:
    print(f"An error occurred: {e}")

Security Considerations

API Key Security

  1. Never commit API keys to version control systems
  2. Use environment variables or secure configuration management
  3. Implement key rotation policies
  4. Monitor for unauthorized usage

Network Security

  1. Use HTTPS only for all API requests
  2. Implement proper TLS verification
  3. Consider IP whitelisting for production environments
  4. Use secure proxy configurations if required

Application Security

  1. Validate all inputs before sending to the API
  2. Implement proper error handling
  3. Log security events for monitoring
  4. Use least privilege principles

Troubleshooting

Common Issues

  1. API Key Not Working

    • Verify the key is correctly copied
    • Check if the key has expired
    • Ensure proper header formatting
  2. Rate Limit Errors

    • Implement exponential backoff
    • Check your current usage limits
    • Consider upgrading your plan
  3. Network Issues

    • Verify internet connectivity
    • Check firewall settings
    • Ensure proper DNS resolution

Getting Help

If you encounter authentication issues:

  1. Check the API Status Page
  2. Review the FAQ section
  3. Contact Technical Support
  4. Join our Developer Community

Next Steps

基于 DeepSeek AI 大模型技术