naver-openapi-helper

Compare original and translation side by side

🇺🇸

Original

English
🇨🇳

Translation

Chinese

Naver Open API Helper

Naver Open API 助手

Generate clean, production-ready Python
requests
code for Naver Open APIs by browsing the official live documentation at
developers.naver.com
.
通过浏览
developers.naver.com
上的官方实时文档,为Naver Open API生成简洁、可用于生产环境的Python
requests
代码。

Covered APIs

覆盖的API

All Naver Open APIs on
https://openapi.naver.com
using simple header authentication:
  • Search APIs: News (
    /v1/search/news
    ), Blog (
    /v1/search/blog
    ), Web (
    /v1/search/webkr
    ), Image (
    /v1/search/image
    ), Book (
    /v1/search/book
    ), etc.
  • Datalab APIs: Search trends (
    /v1/datalab/search
    ), Shopping trends, etc.
Not covered: Naver Search Ad API (
api.searchad.naver.com
) — that requires HMAC-SHA256 signatures and a different docs site.
所有使用简单头部认证的
https://openapi.naver.com
下的Naver Open API:
  • 搜索API:新闻(
    /v1/search/news
    )、博客(
    /v1/search/blog
    )、网页(
    /v1/search/webkr
    )、图片(
    /v1/search/image
    )、书籍(
    /v1/search/book
    )等。
  • Datalab API:搜索趋势(
    /v1/datalab/search
    )、购物趋势等。
未覆盖范围:Naver搜索广告API(
api.searchad.naver.com
)——该API需要HMAC-SHA256签名,且文档站点不同。

Authentication

认证方式

Naver Open APIs use simple header-based auth:
  • X-Naver-Client-Id
  • X-Naver-Client-Secret
Always load these from environment variables in generated code:
python
import os
CLIENT_ID = os.environ.get("NAVER_CLIENT_ID")
CLIENT_SECRET = os.environ.get("NAVER_CLIENT_SECRET")
If the user provides explicit credentials, use them but add a comment warning:
python
undefined
Naver Open API使用简单的基于头部的认证:
  • X-Naver-Client-Id
  • X-Naver-Client-Secret
生成的代码中始终从环境变量加载这些凭证:
python
import os
CLIENT_ID = os.environ.get("NAVER_CLIENT_ID")
CLIENT_SECRET = os.environ.get("NAVER_CLIENT_SECRET")
如果用户提供了明确的凭证,可使用但需添加警告注释:
python
undefined

WARNING: Hardcoding credentials is insecure. Use environment variables in production.

WARNING: Hardcoding credentials is insecure. Use environment variables in production.

undefined
undefined

Important: API Scope Enablement

重要提示:API权限范围启用

Each Naver API family must be enabled separately in the Naver Developer Center:
  • Search APIs → enable "검색"
  • Datalab APIs → enable "데이터랩 (검색어트렌드)"
  • Shopping API → enable "쇼핑"
If you get
errorCode: "024"
(Scope Status Invalid), your key is valid but the specific API is not enabled. Go to your app's API Settings and check the relevant box.
每个Naver API系列必须在Naver开发者中心中单独启用:
  • 搜索API → 启用**“搜索”**
  • Datalab API → 启用**“数据实验室(搜索词趋势)”**
  • 购物API → 启用**“购物”**
如果收到
errorCode: "024"
(Scope Status Invalid,权限范围状态无效),说明你的密钥有效,但未启用该特定API。请前往你的应用API设置页面,勾选相关选项。

Workflow

工作流程

Step 1: Identify the API

步骤1:确定API

From the user's request, determine which API family they need:
User mentionsAPIDocs URL
"news", "article", "headline"News Search
https://developers.naver.com/docs/serviceapi/search/news/news.md
"blog", "blog post"Blog Search
https://developers.naver.com/docs/serviceapi/search/blog/blog.md
"web", "web document", "webkr"Web Search
https://developers.naver.com/docs/serviceapi/search/web/web.md
"image", "picture", "photo"Image Search
https://developers.naver.com/docs/serviceapi/search/image/image.md
"book", "책"Book Search
https://developers.naver.com/docs/serviceapi/search/book/book.md
"datalab", "trend", "keyword trend", "search trend"Datalab Search
https://developers.naver.com/docs/serviceapi/datalab/search/search.md
"shopping", "shop"Shopping Search
https://developers.naver.com/docs/serviceapi/search/shop/shop.md
"encyc", "encyclopedia", "knowledge"Encyclopedia
https://developers.naver.com/docs/serviceapi/search/encyc/encyc.md
"cafe", "cafegroup"Cafe Search
https://developers.naver.com/docs/serviceapi/search/cafearticle/cafearticle.md
If unsure, browse the Naver API docs index or ask the user.
根据用户的请求,确定他们需要的API系列:
用户提及内容对应API文档URL
"news", "article", "headline"新闻搜索
https://developers.naver.com/docs/serviceapi/search/news/news.md
"blog", "blog post"博客搜索
https://developers.naver.com/docs/serviceapi/search/blog/blog.md
"web", "web document", "webkr"网页搜索
https://developers.naver.com/docs/serviceapi/search/web/web.md
"image", "picture", "photo"图片搜索
https://developers.naver.com/docs/serviceapi/search/image/image.md
"book", "책"书籍搜索
https://developers.naver.com/docs/serviceapi/search/book/book.md
"datalab", "trend", "keyword trend", "search trend"Datalab搜索
https://developers.naver.com/docs/serviceapi/datalab/search/search.md
"shopping", "shop"购物搜索
https://developers.naver.com/docs/serviceapi/search/shop/shop.md
"encyc", "encyclopedia", "knowledge"百科搜索
https://developers.naver.com/docs/serviceapi/search/encyc/encyc.md
"cafe", "cafegroup"咖啡馆搜索
https://developers.naver.com/docs/serviceapi/search/cafearticle/cafearticle.md
若不确定,可浏览Naver API文档索引或询问用户。

Step 2: Browse Live Docs with Playwright

步骤2:使用Playwright浏览实时文档

Use
npx @playwright/cli
to open the docs page and extract endpoint details.
bash
npx @playwright/cli open --browser=chromium <docs-url>
npx @playwright/cli snapshot
From the snapshot, extract:
  1. Request URL (e.g.,
    https://openapi.naver.com/v1/search/news.json
    )
  2. HTTP Method (GET or POST)
  3. Parameters (name, type, required, description)
  4. Request/Response examples
  5. Error codes
If the page content is not fully visible, scroll and take additional snapshots:
bash
npx @playwright/cli eval "window.scrollTo(0, document.body.scrollHeight)"
npx @playwright/cli snapshot
If the docs URL is a general index, navigate to the specific API page first:
bash
npx @playwright/cli goto <specific-docs-url>
npx @playwright/cli snapshot
使用
npx @playwright/cli
打开文档页面并提取端点详情。
bash
npx @playwright/cli open --browser=chromium <docs-url>
npx @playwright/cli snapshot
从快照中提取以下信息:
  1. 请求URL(例如:
    https://openapi.naver.com/v1/search/news.json
  2. HTTP方法(GET或POST)
  3. 参数(名称、类型、是否必填、描述)
  4. 请求/响应示例
  5. 错误码
若页面内容未完全显示,可滚动页面并拍摄额外快照:
bash
npx @playwright/cli eval "window.scrollTo(0, document.body.scrollHeight)"
npx @playwright/cli snapshot
若文档URL是通用索引页,需先导航至具体API页面:
bash
npx @playwright/cli goto <specific-docs-url>
npx @playwright/cli snapshot

Step 3: Generate Python Code

步骤3:生成Python代码

Produce a complete, runnable Python script using the
requests
library.
生成完整、可运行的Python脚本,使用
requests
库。

Code Template

代码模板

python
import os
import requests
import json
from urllib.parse import quote


def main():
    # Load credentials from environment variables
    client_id = os.environ.get("NAVER_CLIENT_ID")
    client_secret = os.environ.get("NAVER_CLIENT_SECRET")

    if not client_id or not client_secret:
        raise ValueError("NAVER_CLIENT_ID and NAVER_CLIENT_SECRET must be set")

    # API endpoint
    url = "<endpoint-url>"

    # Auth headers
    headers = {
        "X-Naver-Client-Id": client_id,
        "X-Naver-Client-Secret": client_secret,
    }

    # For POST requests (Datalab), add Content-Type
    # headers["Content-Type"] = "application/json"

    # Parameters
    params = {
        "query": quote("<search-term>"),
        "display": 10,
        "start": 1,
        "sort": "sim",  # sim (accuracy) or date
    }

    # Make request
    response = requests.get(url, headers=headers, params=params)
    # For POST: response = requests.post(url, headers=headers, json=params)

    # Handle response
    if response.status_code == 200:
        data = response.json()
        print(json.dumps(data, ensure_ascii=False, indent=2))
    elif response.status_code == 400:
        print(f"Error 400 - Bad Request: {response.text}")
        print("Check your parameters (query encoding, display/start/sort values).")
    elif response.status_code == 401:
        print(f"Error 401 - Unauthorized: {response.text}")
        print("Check your Client ID and Secret. Ensure the API scope is enabled in Naver Developer Center.")
    elif response.status_code == 403:
        print(f"Error 403 - Forbidden: {response.text}")
        print("Ensure the API is enabled for your application in the Naver Developer Center.")
    elif response.status_code == 500:
        print(f"Error 500 - Internal Server Error: {response.text}")
    else:
        print(f"Error {response.status_code}: {response.text}")


if __name__ == "__main__":
    main()
python
import os
import requests
import json
from urllib.parse import quote


def main():
    # Load credentials from environment variables
    client_id = os.environ.get("NAVER_CLIENT_ID")
    client_secret = os.environ.get("NAVER_CLIENT_SECRET")

    if not client_id or not client_secret:
        raise ValueError("NAVER_CLIENT_ID and NAVER_CLIENT_SECRET must be set")

    # API endpoint
    url = "<endpoint-url>"

    # Auth headers
    headers = {
        "X-Naver-Client-Id": client_id,
        "X-Naver-Client-Secret": client_secret,
    }

    # For POST requests (Datalab), add Content-Type
    # headers["Content-Type"] = "application/json"

    # Parameters
    params = {
        "query": quote("<search-term>"),
        "display": 10,
        "start": 1,
        "sort": "sim",  # sim (accuracy) or date
    }

    # Make request
    response = requests.get(url, headers=headers, params=params)
    # For POST: response = requests.post(url, headers=headers, json=params)

    # Handle response
    if response.status_code == 200:
        data = response.json()
        print(json.dumps(data, ensure_ascii=False, indent=2))
    elif response.status_code == 400:
        print(f"Error 400 - Bad Request: {response.text}")
        print("Check your parameters (query encoding, display/start/sort values).")
    elif response.status_code == 401:
        print(f"Error 401 - Unauthorized: {response.text}")
        print("Check your Client ID and Secret. Ensure the API scope is enabled in Naver Developer Center.")
    elif response.status_code == 403:
        print(f"Error 403 - Forbidden: {response.text}")
        print("Ensure the API is enabled for your application in the Naver Developer Center.")
    elif response.status_code == 500:
        print(f"Error 500 - Internal Server Error: {response.text}")
    else:
        print(f"Error {response.status_code}: {response.text}")


if __name__ == "__main__":
    main()

Requirements

要求

  1. Always use
    requests
    , not
    urllib
    .
  2. Always URL-encode Korean queries. Use
    urllib.parse.quote(query, safe='')
    or let
    requests
    handle it via the
    params
    dict (which encodes automatically).
  3. Always include error handling for non-200 status codes, especially 400, 401, 403, and 500.
  4. Always load credentials from
    os.environ
    unless the user explicitly provides them inline.
  5. For Datalab (POST): Set
    Content-Type: application/json
    and pass the body via
    json=body_dict
    .
  6. For Search APIs (GET): Pass query parameters via
    params=
    .
    requests
    will URL-encode them.
  7. Pretty-print JSON responses with
    ensure_ascii=False
    and
    indent=2
    .
  8. Add comments explaining each parameter based on the live docs.
  1. 始终使用
    requests
    ,而非
    urllib
  2. 始终对韩文查询进行URL编码。使用
    urllib.parse.quote(query, safe='')
    ,或通过
    params
    字典让
    requests
    自动处理编码。
  3. 始终包含错误处理,针对非200状态码,尤其是400、401、403和500。
  4. 始终从
    os.environ
    加载凭证
    ,除非用户明确提供内联凭证。
  5. 对于Datalab(POST请求):设置
    Content-Type: application/json
    ,并通过
    json=body_dict
    传递请求体。
  6. 对于搜索API(GET请求):通过
    params=
    传递查询参数。
    requests
    会自动对其进行URL编码。
  7. 格式化JSON响应,使用
    ensure_ascii=False
    indent=2
    进行美观打印。
  8. 添加注释,根据实时文档解释每个参数。

Optional Enhancements

可选增强功能

If the user asks for a CLI tool, add
argparse
:
python
import argparse

parser = argparse.ArgumentParser(description="Naver API Client")
parser.add_argument("query", help="Search query")
parser.add_argument("--display", type=int, default=10, help="Results per page (1-100)")
parser.add_argument("--sort", choices=["sim", "date"], default="sim", help="Sort order")
args = parser.parse_args()
If the user asks to save results, include file I/O:
python
with open("output.json", "w", encoding="utf-8") as f:
    json.dump(data, f, ensure_ascii=False, indent=2)
If the user asks for data processing (e.g., extracting titles from news results), include parsing logic:
python
for item in data.get("items", []):
    print(item["title"].replace("<b>", "").replace("</b>", ""))
如果用户需要CLI工具,添加
argparse
python
import argparse

parser = argparse.ArgumentParser(description="Naver API Client")
parser.add_argument("query", help="Search query")
parser.add_argument("--display", type=int, default=10, help="Results per page (1-100)")
parser.add_argument("--sort", choices=["sim", "date"], default="sim", help="Sort order")
args = parser.parse_args()
如果用户需要保存结果,添加文件I/O逻辑:
python
with open("output.json", "w", encoding="utf-8") as f:
    json.dump(data, f, ensure_ascii=False, indent=2)
如果用户需要数据处理(例如从新闻结果中提取标题),添加解析逻辑:
python
for item in data.get("items", []):
    print(item["title"].replace("<b>", "").replace("</b>", ""))

Step 4: Validate the Code

步骤4:验证代码

Before presenting the code to the user:
  1. Verify the endpoint URL matches what you saw in the docs.
  2. Verify all required parameters are included.
  3. Verify the HTTP method (GET vs POST) is correct.
  4. Check that auth headers are present.
  5. Run a syntax check if possible:
    bash
    python3 -m py_compile generated_script.py
在将代码呈现给用户之前:
  1. 验证端点URL与文档中的内容一致。
  2. 验证包含所有必填参数。
  3. 验证HTTP方法(GET或POST)正确。
  4. 检查是否包含认证头部。
  5. 若可能,运行语法检查:
    bash
    python3 -m py_compile generated_script.py

Important Notes

重要说明

  • Base URL is always
    https://openapi.naver.com
    for Open APIs. Do not confuse with
    https://api.searchad.naver.com
    (Search Ad API).
  • Daily rate limits: Search APIs = 25,000 calls/day. Datalab = 1,000 calls/day.
  • The live docs are the source of truth — always browse them to confirm the latest parameter names and endpoints.
  • Search API queries must be UTF-8 encoded.
    requests
    does this automatically when you pass a string via
    params
    , but if building URLs manually, use
    urllib.parse.quote
    .
  • 基础URL始终为
    https://openapi.naver.com
    ,适用于开放API。请勿与
    https://api.searchad.naver.com
    (搜索广告API)混淆。
  • 每日调用限制:搜索API = 每日25,000次调用。Datalab = 每日1,000次调用。
  • 实时文档是唯一可信来源——始终浏览文档以确认最新的参数名称和端点。
  • 搜索API查询必须为UTF-8编码。当通过
    params
    传递字符串时,
    requests
    会自动处理编码,但如果手动构建URL,请使用
    urllib.parse.quote

Examples

示例

Example 1: News Search Input: "Generate Python code to search Naver News for 'AI' and print the titles." Output: A Python script that calls
GET /v1/search/news.json?query=AI
, parses the
items
array, strips
<b>
tags from titles, and prints them.
Example 2: Datalab Trends Input: "Write a script to compare search trends for 'Python' vs 'JavaScript' monthly in 2024." Output: A Python script that calls
POST /v1/datalab/search
with two
keywordGroups
, monthly
timeUnit
, and prints the ratio data for each period.
Example 3: Blog Search with CLI Input: "Make a CLI tool to search Naver blogs." Output: A Python script with
argparse
that accepts a query, optional display count and sort order, calls
GET /v1/search/blog.json
, and prints results.
示例1:新闻搜索 输入:“生成Python代码,在Naver新闻中搜索‘AI’并打印标题。” 输出:一个Python脚本,调用
GET /v1/search/news.json?query=AI
,解析
items
数组,去除标题中的
<b>
标签并打印。
示例2:Datalab趋势 输入:“编写脚本,对比2024年每月‘Python’与‘JavaScript’的搜索趋势。” 输出:一个Python脚本,调用
POST /v1/datalab/search
,传入两个
keywordGroups
、月度
timeUnit
,并打印每个时段的比例数据。
示例3:带CLI的博客搜索 输入:“制作一个CLI工具用于搜索Naver博客。” 输出:一个包含
argparse
的Python脚本,接受查询、可选的结果数量和排序方式,调用
GET /v1/search/blog.json
并打印结果。