naver-openapi-helper
Compare original and translation side by side
🇺🇸
Original
English🇨🇳
Translation
ChineseNaver Open API Helper
Naver Open API 助手
Generate clean, production-ready Python code for Naver Open APIs by browsing the official live documentation at .
requestsdevelopers.naver.com通过浏览上的官方实时文档,为Naver Open API生成简洁、可用于生产环境的Python 代码。
developers.naver.comrequestsCovered APIs
覆盖的API
All Naver Open APIs on using simple header authentication:
https://openapi.naver.com- Search APIs: News (), Blog (
/v1/search/news), Web (/v1/search/blog), Image (/v1/search/webkr), Book (/v1/search/image), etc./v1/search/book - Datalab APIs: Search trends (), Shopping trends, etc.
/v1/datalab/search
Not covered: Naver Search Ad API () — that requires HMAC-SHA256 signatures and a different docs site.
api.searchad.naver.com所有使用简单头部认证的下的Naver Open API:
https://openapi.naver.com- 搜索API:新闻()、博客(
/v1/search/news)、网页(/v1/search/blog)、图片(/v1/search/webkr)、书籍(/v1/search/image)等。/v1/search/book - Datalab API:搜索趋势()、购物趋势等。
/v1/datalab/search
未覆盖范围:Naver搜索广告API()——该API需要HMAC-SHA256签名,且文档站点不同。
api.searchad.naver.comAuthentication
认证方式
Naver Open APIs use simple header-based auth:
X-Naver-Client-IdX-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
undefinedNaver Open API使用简单的基于头部的认证:
X-Naver-Client-IdX-Naver-Client-Secret
生成的代码中始终从环境变量加载这些凭证:
python
import os
CLIENT_ID = os.environ.get("NAVER_CLIENT_ID")
CLIENT_SECRET = os.environ.get("NAVER_CLIENT_SECRET")如果用户提供了明确的凭证,可使用但需添加警告注释:
python
undefinedWARNING: Hardcoding credentials is insecure. Use environment variables in production.
WARNING: Hardcoding credentials is insecure. Use environment variables in production.
undefinedundefinedImportant: 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 (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.
errorCode: "024"每个Naver API系列必须在Naver开发者中心中单独启用:
- 搜索API → 启用**“搜索”**
- Datalab API → 启用**“数据实验室(搜索词趋势)”**
- 购物API → 启用**“购物”**
如果收到(Scope Status Invalid,权限范围状态无效),说明你的密钥有效,但未启用该特定API。请前往你的应用API设置页面,勾选相关选项。
errorCode: "024"Workflow
工作流程
Step 1: Identify the API
步骤1:确定API
From the user's request, determine which API family they need:
| User mentions | API | Docs URL |
|---|---|---|
| "news", "article", "headline" | News Search | |
| "blog", "blog post" | Blog Search | |
| "web", "web document", "webkr" | Web Search | |
| "image", "picture", "photo" | Image Search | |
| "book", "책" | Book Search | |
| "datalab", "trend", "keyword trend", "search trend" | Datalab Search | |
| "shopping", "shop" | Shopping Search | |
| "encyc", "encyclopedia", "knowledge" | Encyclopedia | |
| "cafe", "cafegroup" | Cafe Search | |
If unsure, browse the Naver API docs index or ask the user.
根据用户的请求,确定他们需要的API系列:
| 用户提及内容 | 对应API | 文档URL |
|---|---|---|
| "news", "article", "headline" | 新闻搜索 | |
| "blog", "blog post" | 博客搜索 | |
| "web", "web document", "webkr" | 网页搜索 | |
| "image", "picture", "photo" | 图片搜索 | |
| "book", "책" | 书籍搜索 | |
| "datalab", "trend", "keyword trend", "search trend" | Datalab搜索 | |
| "shopping", "shop" | 购物搜索 | |
| "encyc", "encyclopedia", "knowledge" | 百科搜索 | |
| "cafe", "cafegroup" | 咖啡馆搜索 | |
若不确定,可浏览Naver API文档索引或询问用户。
Step 2: Browse Live Docs with Playwright
步骤2:使用Playwright浏览实时文档
Use to open the docs page and extract endpoint details.
npx @playwright/clibash
npx @playwright/cli open --browser=chromium <docs-url>
npx @playwright/cli snapshotFrom the snapshot, extract:
- Request URL (e.g., )
https://openapi.naver.com/v1/search/news.json - HTTP Method (GET or POST)
- Parameters (name, type, required, description)
- Request/Response examples
- 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 snapshotIf 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/clibash
npx @playwright/cli open --browser=chromium <docs-url>
npx @playwright/cli snapshot从快照中提取以下信息:
- 请求URL(例如:)
https://openapi.naver.com/v1/search/news.json - HTTP方法(GET或POST)
- 参数(名称、类型、是否必填、描述)
- 请求/响应示例
- 错误码
若页面内容未完全显示,可滚动页面并拍摄额外快照:
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 snapshotStep 3: Generate Python Code
步骤3:生成Python代码
Produce a complete, runnable Python script using the library.
requests生成完整、可运行的Python脚本,使用库。
requestsCode 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
要求
- Always use , not
requests.urllib - Always URL-encode Korean queries. Use or let
urllib.parse.quote(query, safe='')handle it via therequestsdict (which encodes automatically).params - Always include error handling for non-200 status codes, especially 400, 401, 403, and 500.
- Always load credentials from unless the user explicitly provides them inline.
os.environ - For Datalab (POST): Set and pass the body via
Content-Type: application/json.json=body_dict - For Search APIs (GET): Pass query parameters via .
params=will URL-encode them.requests - Pretty-print JSON responses with and
ensure_ascii=False.indent=2 - Add comments explaining each parameter based on the live docs.
- 始终使用,而非
requests。urllib - 始终对韩文查询进行URL编码。使用,或通过
urllib.parse.quote(query, safe='')字典让params自动处理编码。requests - 始终包含错误处理,针对非200状态码,尤其是400、401、403和500。
- 始终从加载凭证,除非用户明确提供内联凭证。
os.environ - 对于Datalab(POST请求):设置,并通过
Content-Type: application/json传递请求体。json=body_dict - 对于搜索API(GET请求):通过传递查询参数。
params=会自动对其进行URL编码。requests - 格式化JSON响应,使用和
ensure_ascii=False进行美观打印。indent=2 - 添加注释,根据实时文档解释每个参数。
Optional Enhancements
可选增强功能
If the user asks for a CLI tool, add :
argparsepython
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工具,添加:
argparsepython
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:
- Verify the endpoint URL matches what you saw in the docs.
- Verify all required parameters are included.
- Verify the HTTP method (GET vs POST) is correct.
- Check that auth headers are present.
- Run a syntax check if possible:
bash
python3 -m py_compile generated_script.py
在将代码呈现给用户之前:
- 验证端点URL与文档中的内容一致。
- 验证包含所有必填参数。
- 验证HTTP方法(GET或POST)正确。
- 检查是否包含认证头部。
- 若可能,运行语法检查:
bash
python3 -m py_compile generated_script.py
Important Notes
重要说明
- Base URL is always for Open APIs. Do not confuse with
https://openapi.naver.com(Search Ad API).https://api.searchad.naver.com - 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. does this automatically when you pass a string via
requests, but if building URLs manually, useparams.urllib.parse.quote
- 基础URL始终为,适用于开放API。请勿与
https://openapi.naver.com(搜索广告API)混淆。https://api.searchad.naver.com - 每日调用限制:搜索API = 每日25,000次调用。Datalab = 每日1,000次调用。
- 实时文档是唯一可信来源——始终浏览文档以确认最新的参数名称和端点。
- 搜索API查询必须为UTF-8编码。当通过传递字符串时,
params会自动处理编码,但如果手动构建URL,请使用requests。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 , parses the array, strips tags from titles, and prints them.
GET /v1/search/news.json?query=AIitems<b>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 with two , monthly , and prints the ratio data for each period.
POST /v1/datalab/searchkeywordGroupstimeUnitExample 3: Blog Search with CLI
Input: "Make a CLI tool to search Naver blogs."
Output: A Python script with that accepts a query, optional display count and sort order, calls , and prints results.
argparseGET /v1/search/blog.json示例1:新闻搜索
输入:“生成Python代码,在Naver新闻中搜索‘AI’并打印标题。”
输出:一个Python脚本,调用,解析数组,去除标题中的标签并打印。
GET /v1/search/news.json?query=AIitems<b>示例2:Datalab趋势
输入:“编写脚本,对比2024年每月‘Python’与‘JavaScript’的搜索趋势。”
输出:一个Python脚本,调用,传入两个、月度,并打印每个时段的比例数据。
POST /v1/datalab/searchkeywordGroupstimeUnit示例3:带CLI的博客搜索
输入:“制作一个CLI工具用于搜索Naver博客。”
输出:一个包含的Python脚本,接受查询、可选的结果数量和排序方式,调用并打印结果。
argparseGET /v1/search/blog.json