SoFunction
Updated on 2025-05-14

Python uses curl to access deepseek's API

API application and recharge

Below is deepeek's API website

/

Register first when you go in. Whether the mobile phone account or password is not important, it is the same. After you recharge and play rice, you mainly create an API key in the API Keys on the left after playing rice. Pay attention to copying a key by yourself. You can't open it after you finish it, but you can't remember it but can only regenerate it.

Local curl access code script

Some parameters and options are marked in the code

import subprocess
import json
import os

def call_deepseek_api(prompt,
    api_key="sk-0d83************f3a3461486",
    model="deepseek-chat",
    temperature=0.7,
    max_tokens=1000
    ):
    """
    usecURLCallDeepSeek API
    
    parameter:
    - prompt: Prompt text
    - api_key: DeepSeek APIKey,Get from environment variable if not provided
    - model: 要use的模型名称
        By specifying model='deepseek-chat' 即可Call DeepSeek-V3。
        By specifying model='deepseek-reasoner',即可Call DeepSeek-R1。
    - temperature: 控制Randomity的温度parameter(Randomity,The lower the answer, the higher the probability of choosing,Highest1,lowest0,0.7Time balance,0.2Timeless,1Flexible)
    - max_tokens: Maximum generatedtokennumber(Billing is throughtoken,Model word participle(Tokenizer)Decide,Simply put,1 One word ≈ 1.3 indivual Token,1 indivual汉字 ≈ 1~1.5 indivual Token,Single fee=entertoken*0.0001+Outputtoken*0.0003    
    return:
    - APIResponsiveJSONAnalysis results
    """
    # If the API key is not provided, get it from the environment variable    if api_key is None:
        api_key = ("DEEPSEEK_API_KEY")
    
    if not api_key:
        raise ValueError("DeepSeek API key is required")
    
    # Build the JSON data requested by API    request_data = {
        "model": model,
        "messages": [{"role": "user", "content": prompt}],
        "temperature": temperature,
        "max_tokens": max_tokens,
        "stream":False
    }
    
    # Build cURL command    #There may be a problem here, the access address may be "/chat/completions"    curl_cmd = [
        "curl",
        "-X", "POST",
        "/v1/chat/completions",
        "-H", f"Authorization: Bearer {api_key}",
        "-H", "Content-Type: application/json",
        "-d", (request_data)
    ]
    
    try:
        # Execute cURL command        result = (
            curl_cmd,
            capture_output=True,
            text=True,
            encoding='utf-8', 
            check=True
        )
        
        # parse JSON response        response = ()
        return response
    
    except  as e:
        print(f"APIRequest failed: {}")
        raise
    except :
        print(f"Unable to parseAPIresponse: {}")
        raise

#User Exampleif __name__ == "__main__":
    # Method 1: Set API key through environment variables    # ["DEEPSEEK_API_KEY"] = "your_api_key_here"
    
    # Method 2: Provide API key directly in function calls    api_key = "sk-0d8*******f3a3461486"
    
    # Call API    try:
        response = call_deepseek_api(
            prompt="Hello, please introduce yourself",
            api_key=api_key
        )
        
        # Print the content returned by the API        if "choices" in response and len(response["choices"]) > 0:
            message = response["choices"][0]["message"]["content"]
            print("API Response:")
            print(message)
        else:
            print("API return format exception:", response)
    
    except Exception as e:
        print(f"An error occurred: {e}")

Here is the result of the above code trying to run

This is the article about python accessing deepseek API through curl. For more related python accessing deepseek API content, please search for my previous articles or continue browsing the related articles below. I hope everyone will support me in the future!