Skip to content
Five.Reviews
Menu

How-To & Tutorials

How to Use DeepSeek Search API and Fetch API

Laptop displaying code on a desk used to represent tool setup and technical review work
Free browser-based audio. No tracking or paid API required.

Language models cannot browse the web on their own, so AI applications need a way to find current sources and read them. The DeepSeek Search API and Fetch API cover both steps. Search returns web pages that match a query, and Fetch retrieves the content of one page as Markdown. This tutorial shows how to authenticate, send requests, read responses, handle errors, and combine both endpoints in Python.

Quick Summary

What Are the DeepSeek Search API and Fetch API?

According to the official guide, both APIs give agents and RAG applications access to live web content. The Search API is powered by DeepSeek’s in-house search engine.

What Is the DeepSeek Search API?

The Search API takes a text query and returns a results array. Each item can include a title, URL, a short snippet for display, a longer summary for a model, and page content if you request it. A query with no matches returns an empty array, not an error.

What Is the DeepSeek Fetch API?

The Fetch API takes one URL and returns the page’s title and content, with the content in Markdown. Retrieval depends on the target site’s availability and access policies, so some pages cannot be fetched.

DeepSeek Search API vs. Fetch API

Search APIFetch API
Endpoint/v1/tools/search/v1/tools/fetch
Required inputquery (1 to 128 characters)url (HTTP or HTTPS, up to 8,192 characters)
Outputresults array with metadata and snippetstitle and Markdown content
Typical useDiscover candidate pagesRead a chosen page

Search discovers pages. Fetch retrieves the one you pick.

How to Set Up DeepSeek API Authentication

Create an API key on the DeepSeek Platform, then store it in an environment variable rather than in your code:

bash

export DEEPSEEK_API_KEY=”your-key-here”   # macOS/Linux

pip install requests

Every request must send Authorization: Bearer <DeepSeek API Key> and Content-Type: application/json. Never hardcode the key or print it in logs.

How to Use the DeepSeek Search API

Make Your First Search Request

python

import os

import requests

headers = {

    “Authorization”: f”Bearer {os.environ[‘DEEPSEEK_API_KEY’]}”,

    “Content-Type”: “application/json”,

}

response = requests.post(

    “https://api.deepseek.com/v1/tools/search”,

    headers=headers,

    json={“query”: “DeepSeek V4 release”, “count”: 5, “need_content”: False},

    timeout=30,

)

response.raise_for_status()

for result in response.json().get(“results”, []):

    print(result.get(“title”), result.get(“url”))

    print(result.get(“snippet”))

Understand the Search Parameters

Unknown fields are ignored.

Use Search Operators to Improve Results

Understand the Search Response

Each result can include these fields:

These are ranking signals. They do not confirm that a page is factually correct, so check important claims against more than one source.

How to Use the DeepSeek Fetch API

Fetch a Webpage With Python

python

page = requests.post(

    “https://api.deepseek.com/v1/tools/fetch”,

    headers=headers,

    json={“url”: “https://example.com/article”},

    timeout=30,

)

page.raise_for_status()

data = page.json()

print(data.get(“title”, “”))

print(data.get(“content”, “”))

Understand the Fetch API Response

The response contains title, which is empty when unavailable, and content, which is Markdown. The URL must be HTTP or HTTPS, include a host, contain no username or password, and be no longer than 8,192 characters.

A 404 means Fetch could not retrieve usable content. Causes include an unavailable URL, a site policy block, an upstream error, an unsupported content type, or a page with no extractable Markdown. A 403 means the request was rejected by security policy.

Process Retrieved Markdown

You can save the content to a file, display it, or pass it to a language model. Check that content is not empty before using it, and treat it as untrusted input, because a web page can contain text that looks like instructions.

Combine DeepSeek Search and Fetch APIs in Python

This workflow searches for a topic, ranks the results, skips unusable candidates, fetches the best one, and prints its Markdown. It reads the key from os.environ, uses explicit timeouts, retries only the statuses the guide marks as retryable, and validates each URL before fetching.

python

import os

import sys

import time

from urllib.parse import urlparse

import requests

BASE_URL = “https://api.deepseek.com”

SEARCH_URL = f”{BASE_URL}/v1/tools/search”

FETCH_URL = f”{BASE_URL}/v1/tools/fetch”

TIMEOUT_SECONDS = 30

MAX_ATTEMPTS = 3

MAX_FETCH_CANDIDATES = 3

def get_headers():

    api_key = os.environ.get(“DEEPSEEK_API_KEY”)

    if not api_key:

        raise RuntimeError(“DEEPSEEK_API_KEY is not set.”)

    return {

        “Authorization”: f”Bearer {api_key}”,

        “Content-Type”: “application/json”,

    }

def is_safe_url(url):

    “””Basic validation only. It is not a complete defense against SSRF.”””

    if not isinstance(url, str) or not url or len(url) > 8192:

        return False

    try:

        parsed = urlparse(url)

    except ValueError:

        return False

    return (

        parsed.scheme in (“http”, “https”)

        and bool(parsed.hostname)

        and not parsed.username

        and not parsed.password

    )

def post_json(url, payload):

    “””POST with a timeout. Retries only 408, 429, and 5xx responses.”””

    for attempt in range(1, MAX_ATTEMPTS + 1):

        response = requests.post(

            url, headers=get_headers(), json=payload, timeout=TIMEOUT_SECONDS

        )

        if response.ok:

            return response.json()

        retryable = response.status_code in (408, 429) or response.status_code >= 500

        if not retryable or attempt == MAX_ATTEMPTS:

            response.raise_for_status()

        time.sleep(2 ** attempt)

def search(query, count=5):

    data = post_json(SEARCH_URL, {“query”: query, “count”: count, “need_content”: False})

    return data.get(“results”) or []

def fetch(url):

    return post_json(FETCH_URL, {“url”: url})

def main():

    query = ” “.join(sys.argv[1:]).strip() or “DeepSeek API documentation”

    if len(query) > 128:

        print(“Query must be 128 characters or fewer.”)

        return 1

    try:

        results = search(query)

    except requests.RequestException as err:

        print(f”Search failed: {err}”)

        return 1

    candidates = [r for r in results if is_safe_url(r.get(“url”))]

    candidates.sort(key=lambda r: r.get(“rerank_score”) or 0, reverse=True)

    if not candidates:

        print(“No usable search results.”)

        return 0

    for item in candidates[:MAX_FETCH_CANDIDATES]:

        try:

            page = fetch(item[“url”])

        except requests.RequestException as err:

            print(f”Skipping {item[‘url’]}: {err}”)

            continue

        content = (page.get(“content”) or “”).strip()

        if not content:

            print(f”Skipping {item[‘url’]}: no content returned.”)

            continue

        print(f”Title: {page.get(‘title’) or item.get(‘title’) or ‘Untitled’}”)

        print(f”URL: {item[‘url’]}\n”)

        print(content[:2000])

        return 0

    print(“None of the top candidates could be fetched.”)

    return 1

if __name__ == “__main__”:

    raise SystemExit(main())

Run it with python research.py “DeepSeek V4 release”. The script covers each step as follows:

  1. It reads the key from DEEPSEEK_API_KEY.
  2. It sends a search request with a bounded count.
  3. It returns early when results is empty.
  4. It sorts candidates by rerank_score, treating missing scores as zero.
  5. It validates each URL’s scheme, host, credentials, and length.
  6. It calls the Fetch endpoint for up to three candidates.
  7. It catches HTTP errors and timeouts, retrying only 408, 429, and 5xx responses.
  8. It prints the title, URL, and the first 2,000 characters of Markdown. Remove the slice to print the full content.

To extend this into a research assistant or RAG pipeline, pass the fetched Markdown and its URL into your model prompt, store the URL with each chunk, and keep the source attached to every answer. Search and Fetch retrieve content, but they do not guarantee that an answer is verified.

DeepSeek Search and Fetch API Pricing, Rate Limits, and Errors

EndpointBilling unitPrice
SearchPer 1,000 successful requests$0.75
FetchPer 1,000 successful requests$0.75

A request is billable only when it returns HTTP 200 with a non-empty results array (Search) or page content (Fetch). Failed requests, empty results, and timeouts are not billed.

The guide also says that server-side tool calls made through DeepSeek Harness, Claude Code, or Codex are currently free. Per-request billing for those calls begins at 00:00 Beijing time on November 1, 2026. This does not change the pricing above for direct API calls.

Each account has independent limits of 5 requests per second for Search and 5 for Fetch. Fetch also has a per-domain limit, which the guide does not specify. Exceeding a limit returns HTTP 429.

StatusMeaningAction
400Invalid headers, body, or field valueFix the request. Do not retry unchanged.
401Missing or invalid API keyCheck the key.
402Insufficient balanceTop up, then retry.
403Fetch rejected by security policyUse a different URL.
404Fetch could not retrieve usable contentTry another source.
408Request body read timed outWait and retry.
413Request body too largeReduce the payload.
429Search or Fetch QPS limit exceededWait and retry with backoff.
500Internal server errorWait and retry.
504Downstream request timed outWait and retry.

Best Practices for DeepSeek API Integration

Conclusion

Search finds the pages, and Fetch reads the ones you choose. Start by running the individual endpoints with a narrow query, then add the combined script to your application. Before production use, check the official guide for current pricing, limits, and the status of the free arrangement for Harness, Claude Code, and Codex.

Frequently Asked Questions

What is the DeepSeek Search API used for?

It finds web pages for a text query and returns structured results with titles, URLs, snippets, and summaries. Developers use it in AI agents and RAG applications to discover current sources. Query operators can restrict results by domain, language, and publication date.

What is the difference between DeepSeek Search API and Fetch API?

The Search API discovers candidate pages and returns metadata for each. The Fetch API takes one URL and returns that page’s title and content as Markdown. A common workflow runs Search first, selects a result, and then sends its URL to Fetch.

How do you use the DeepSeek Search API in Python?

Send a POST request to https://api.deepseek.com/v1/tools/search with a bearer token in the Authorization header and a JSON body containing a query. You can add count and need_content. Call raise_for_status(), then read the results array from the response.

How do you use the DeepSeek Fetch API in Python?

Send a POST request to https://api.deepseek.com/v1/tools/fetch with the same authentication and a JSON body containing url. The URL must be HTTP or HTTPS, include a host, and contain no credentials. Read title and content from the response.

Do DeepSeek Search and Fetch APIs require the OpenAI SDK?

No. The guide describes both as raw JSON APIs that use the same bearer authentication as the DeepSeek API. You can call them with Python’s requests library, curl, or any HTTP client.

How much do DeepSeek Search and Fetch APIs cost?

Each costs $0.75 per 1,000 successful requests, according to the official guide. Only HTTP 200 responses that return results or page content are billed. Certain server-side calls through DeepSeek Harness, Claude Code, or Codex are currently free, with billing starting November 1, 2026.

What does the DeepSeek Fetch API return?

It returns a JSON object with title and content. The title is empty when unavailable. The content is the page text in Markdown. Content may be empty, so check it before use. Retrieval depends on the target site’s availability and access policies.

Can DeepSeek Fetch retrieve any webpage?

No. Fetch returns 404 when it cannot produce usable content, such as for unavailable URLs, blocked pages, unsupported content types, or pages with no extractable Markdown. It returns 403 when a request violates its security policy.

What should you do when the DeepSeek API returns a 429 error?

A 429 means the Search or Fetch QPS limit was exceeded. Wait, then retry with exponential backoff. Limits are 5 requests per second per endpoint for each account, and Fetch also has a per-domain limit. Throttle your own requests to stay under them.

Can DeepSeek Search and Fetch APIs be used in RAG applications?

Yes. The official guide says both serve agents and RAG applications. Search finds sources, and Fetch retrieves their content for chunking and embedding. Retrieved text is not automatically verified, so store source URLs and check important claims.