DEV Community

Cover image for How to Use DeepSeek's API: A Working Python Example From My First Side Project
Hamimelon2026
Hamimelon2026

Posted on

How to Use DeepSeek's API: A Working Python Example From My First Side Project

The Tutorial I Wish I'd Had

I spent about forty minutes stuck on a 401 Unauthorized error the first time I tried to use DeepSeek's API. The fix took ten seconds once I found it. The forty minutes was me not knowing where to look.

I was building a small side project — a script that summarizes long PDFs into short study notes, mostly for going through research papers faster. DeepSeek came up as a cheap, capable option, and I figured I'd document the actual steps I took, errors included, since most "getting started" guides skip the part where things don't work the first time.

Step 1: Get an API Key

Sign up at DeepSeek's platform and generate an API key from your account dashboard. Keep it somewhere you won't accidentally commit to git — I use a .env file and python-dotenv, which is where my forty minutes actually went. (I'd put the key in the wrong environment variable name. Double-check this before you assume the API itself is broken.)

pip install openai python-dotenv
Enter fullscreen mode Exit fullscreen mode

Yes, openai — DeepSeek's API is OpenAI-compatible, so you use the same SDK, just pointed at a different base URL.

Step 2: Your First Request

import os
from dotenv import load_dotenv
from openai import OpenAI

load_dotenv()

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

response = client.chat.completions.create(
    model="deepseek-chat",
    messages=[
        {"role": "system", "content": "You are a helpful assistant that summarizes text concisely."},
        {"role": "user", "content": "Summarize this in three bullet points: [your text here]"}
    ],
    temperature=0.3
)

print(response.choices[0].message.content)
Enter fullscreen mode Exit fullscreen mode


That's the whole thing for a basic call. If you're coming from OpenAI's own API, this will look almost identical — that's intentional, and it's why the SDK doesn't need to change.

Step 3: Handling Longer Documents

For my actual use case (summarizing PDFs), the text usually blows past a reasonable single-prompt length. I ended up chunking the document and summarizing each piece, then doing a final pass to combine them:

def summarize_chunk(text, client):
    response = client.chat.completions.create(
        model="deepseek-chat",
        messages=[
            {"role": "system", "content": "Summarize the following text in 2-3 sentences."},
            {"role": "user", "content": text}
        ],
        temperature=0.3
    )
    return response.choices[0].message.content

def summarize_document(chunks, client):
    partial_summaries = [summarize_chunk(chunk, client) for chunk in chunks]
    combined = "\n".join(partial_summaries)

    final_response = client.chat.completions.create(
        model="deepseek-chat",
        messages=[
            {"role": "system", "content": "Combine these partial summaries into one coherent summary."},
            {"role": "user", "content": combined}
        ],
        temperature=0.3
    )
    return final_response.choices[0].message.content
Enter fullscreen mode Exit fullscreen mode

This is intentionally simple — no retry logic, no async, nothing fancy. It's the version that got my prototype working, not the version I'd ship to production.

What I'd Add Before Using This for Real
Retries with backoff for rate limit errors (429s happen, especially at volume)
Token counting before sending, so you're not surprised by a request that's too long
Error handling around the response object, since response.choices[0].message.content will throw if the request failed silently
The Part After "It Works"

Once this was running, the next question I had was whether a different model would handle long documents better or cost less for my volume. Answering that with DeepSeek's SDK directly would've meant repeating steps 1–3 above for each new provider — new base URL, new auth pattern, occasionally a slightly different response shape to handle.

I ended up routing requests through RouteAI instead, which uses the same OpenAI-compatible format shown above — same client.chat.completions.create() call, just a different base_url and model name. That let me test the same chunking logic against a couple of other models without rewriting the functions above. Worth being clear about what this does and doesn't solve: it saved me integration time, not token cost — pricing still depends entirely on which model you pick.

If You're Just Getting Started

Get the basic request working first, with your own API key, before adding anything else. Everything above builds on that one call. The chunking function is specific to my use case (long documents) — if you're doing something simpler, like a chatbot or single-turn queries, you may not need it at all.

TL;DR: DeepSeek's API is OpenAI-compatible, so getting started is mostly pip install openai, swap the base_url, and use your DeepSeek key. Full working example above, including a basic document-chunking pattern for long text.

Linking the tool mentioned above: www.fastrouteai.com

Top comments (0)