ANALYSIS
Dify API 集成完整指南
概述
Dify 的 API 让你将 AI 能力集成到现有应用程序中,而无需从零开始构建 AI 基础设施。你可以获得大型语言模型的全部功能,同时拥有创建自定义用户体验的灵活性。
为什么使用 Dify API
核心优势
| 优势 | 说明 |
|---|---|
| 跳过后端复杂性 | 直接从前端应用访问 LLM 能力,无需管理 AI 基础设施 |
| 可视化应用管理 | 可视化设计和更新 AI 行为——更改会立即同步到所有 API 消费者 |
| 提供商灵活性 | 在 AI 提供商之间切换并集中管理 API 密钥,无需更改代码 |
API 集成的工作原理
PRTCL // PLAINTEXT
1. 构建应用 └─ 在 Dify Studio 中构建具有所需 AI 能力的应用
2. 生成 API 凭据 └─ 安全访问应用功能
3. 调用 API └─ 从你的应用程序调用 API 获取 AI 驱动的响应
4. 用户交互 └─ 用户通过你的自定义界面交互,Dify 处理 AI 处理过程功能继承
你的 API 会自动继承 Dify 应用的所有功能:
- 提示词
- 知识库
- 工具
- 模型配置
API 访问设置
访问 API 设置页面
- 进入你的应用
- 在左侧边栏找到 API Access
- 进入 API 设置页面
创建 API 凭据
步骤:
- 点击 创建凭据
- 输入凭据名称(可选)
- 选择环境(开发、测试、生产)
- 点击 创建
- 保存生成的 API Key
重要提示:
- 永远不要在前端代码或客户端请求中暴露 API 密钥
- 始终从后端调用 Dify API
- 定期轮换密钥
查看 API 文档
Dify 会自动生成针对你应用配置的完整 API 文档,包括:
- 端点 URL
- 请求方法
- 请求参数
- 响应格式
- 示例代码
API 安全
凭据管理
最佳实践:
PRTCL // YAML
凭据管理: environment: - name: "development" api_key: "${DIFY_DEV_API_KEY}" - name: "testing" api_key: "${DIFY_TEST_API_KEY}" - name: "production" api_key: "${DIFY_PROD_API_KEY}"
lifecycle: rotate: true rotation_period: "90days" revoke_unused: true定期轮换:
- 每 90 天轮换一次密钥
- 撤销未使用的凭据
- 监控 API 使用情况
安全措施
后端存储:
PRTCL // PYTHON
# 使用环境变量存储 API 密钥import os
DIFY_API_KEY = os.getenv("DIFY_API_KEY")速率限制:
PRTCL // PYTHON
from flask_limiter import Limiter
limiter = Limiter( app=app, key_func=get_remote_address, default_limits=["100 per hour"])
@app.route("/api/chat")@limiter.limit("20 per minute")def chat(): pass请求验证:
PRTCL // PYTHON
def validate_request(request): # 验证请求来源 if not verify_origin(request): return False
# 验证请求格式 if not validate_format(request.json): return False
return True日志记录:
PRTCL // PYTHON
import logging
logging.basicConfig(level=logging.INFO)
def log_api_call(endpoint, user_id, status): logging.info(f"API Call: {endpoint} by {user_id} - Status: {status}")文本生成应用 API
端点信息
URL:POST https://api.dify.ai/v1/completion-messages
请求参数
| 参数 | 类型 | 必填 | 说明 |
|---|---|---|---|
| inputs | object | 是 | 应用输入变量 |
| response_mode | string | 是 | 响应模式:streaming, blocking |
| user | string | 是 | 用户标识 |
| files | array | 否 | 文件列表 |
cURL 示例
PRTCL // BASH
curl --location --request POST 'https://api.dify.ai/v1/completion-messages' \ --header 'Authorization: Bearer ENTER-YOUR-SECRET-KEY' \ --header 'Content-Type: application/json' \ --data-raw '{ "inputs": { "text": "Hello, how are you?" }, "response_mode": "streaming", "user": "abc-123" }'Python 示例
PRTCL // PYTHON
import requestsimport json
url = "https://api.dify.ai/v1/completion-messages"headers = { 'Authorization': 'Bearer ENTER-YOUR-SECRET-KEY', 'Content-Type': 'application/json',}data = { "inputs": { "text": 'Hello, how are you?' }, "response_mode": "streaming", "user": "abc-123"}response = requests.post(url, headers=headers, data=json.dumps(data))print(response.text)响应格式
PRTCL // JSON
{ "result": "Hello! I'm doing well, thank you for asking. How can I assist you today?", "message_id": "550e8400-e29b-41d4-a716-446655440000", "created_at": 1678901234, "metadata": { "usage": { "prompt_tokens": 10, "prompt_unit_price": "0.00001", "prompt_price_unit": "1K tokens", "prompt_price": "0.0001", "completion_tokens": 20, "completion_unit_price": "0.00002", "completion_price_unit": "1K tokens", "completion_price": "0.0004", "total_tokens": 30, "total_price": "0.0005", "currency": "USD", "latency": 1.5 } }}对话应用 API
端点信息
URL:POST https://api.dify.ai/v1/chat-messages
conversation_id 的关键注意事项
重要说明:
- API 不会共享 WebApp 创建的对话
- 通过 API 创建的对话与在 WebApp 界面中创建的对话是隔离的
生成 conversation_id:
PRTCL // PYTHON
# 开始新对话时,将 conversation_id 字段留空data = { "inputs": {}, "query": "Hello", "response_mode": "streaming", "user": "abc-123" # conversation_id 不设置,系统将生成新的}在现有会话中处理 conversation_id:
PRTCL // PYTHON
# 一旦生成 conversation_id,后续调用应包含此 IDdata = { "inputs": {}, # 会被忽略 "query": "How are you?", "response_mode": "streaming", "conversation_id": "1c7e55fb-1ba2-4e10-81b5-30addcea2276", "user": "abc-123"}管理动态变量:
PRTCL // PYTHON
# 使用会话变量调整机器人行为data = { "query": "Change your language to Chinese", "response_mode": "streaming", "conversation_id": "1c7e55fb-1ba2-4e10-81b5-30addcea2276", "user": "abc-123", "variables": { "language": "Chinese" }}请求参数
| 参数 | 类型 | 必填 | 说明 |
|---|---|---|---|
| inputs | object | 是 | 应用输入变量 |
| query | string | 是 | 用户查询 |
| response_mode | string | 是 | 响应模式:streaming, blocking |
| conversation_id | string | 否 | 对话 ID |
| user | string | 是 | 用户标识 |
| files | array | 否 | 文件列表 |
cURL 示例
PRTCL // BASH
curl --location --request POST 'https://api.dify.ai/v1/chat-messages' \ --header 'Authorization: Bearer ENTER-YOUR-SECRET-KEY' \ --header 'Content-Type: application/json' \ --data-raw '{ "inputs": {}, "query": "Hello", "response_mode": "streaming", "conversation_id": "1c7e55fb-1ba2-4e10-81b5-30addcea2276", "user": "abc-123" }'Python 示例
PRTCL // PYTHON
import requestsimport json
url = 'https://api.dify.ai/v1/chat-messages'headers = { 'Authorization': 'Bearer ENTER-YOUR-SECRET-KEY', 'Content-Type': 'application/json',}data = { "inputs": {}, "query": "Hello", "response_mode": "streaming", "conversation_id": "1c7e55fb-1ba2-4e10-81b5-30addcea2276", "user": "abc-123"}response = requests.post(url, headers=headers, data=json.dumps(data))print(response.text)响应格式
PRTCL // JSON
{ "result": "Hello! I'm doing well, thank you for asking. How can I assist you today?", "conversation_id": "1c7e55fb-1ba2-4e10-81b5-30addcea2276", "message_id": "550e8400-e29b-41d4-a716-446655440001", "created_at": 1678901234, "metadata": { "usage": { "prompt_tokens": 15, "prompt_unit_price": "0.00001", "prompt_price_unit": "1K tokens", "prompt_price": "0.00015", "completion_tokens": 25, "completion_unit_price": "0.00002", "completion_price_unit": "1K tokens", "completion_price": "0.0005", "total_tokens": 40, "total_price": "0.00065", "currency": "USD", "latency": 2.0 } }}流式响应处理
流式响应格式
流式响应以 Server-Sent Events (SSE) 格式返回:
PRTCL // PLAINTEXT
data: {"event": "message", "task_id": "xxx", "id": "xxx", "answer": "Hello"}
data: {"event": "message", "task_id": "xxx", "id": "xxx", "answer": "Hello, how"}
data: {"event": "message", "task_id": "xxx", "id": "xxx", "answer": "Hello, how are"}
data: {"event": "message_end", "task_id": "xxx", "id": "xxx", "metadata": {...}}Python 流式处理示例
PRTCL // PYTHON
import requestsimport json
def stream_chat(): url = 'https://api.dify.ai/v1/chat-messages' headers = { 'Authorization': 'Bearer ENTER-YOUR-SECRET-KEY', 'Content-Type': 'application/json', } data = { "inputs": {}, "query": "Tell me a story", "response_mode": "streaming", "user": "abc-123" }
response = requests.post(url, headers=headers, json=data, stream=True)
for line in response.iter_lines(): if line: line = line.decode('utf-8') if line.startswith('data: '): data = json.loads(line[6:]) if data.get('event') == 'message': print(data.get('answer'), end='', flush=True) elif data.get('event') == 'message_end': print('\n\nResponse completed!') print(f"Metadata: {data.get('metadata')}")
stream_chat()JavaScript 流式处理示例
PRTCL // JAVASCRIPT
async function streamChat() { const response = await fetch('https://api.dify.ai/v1/chat-messages', { method: 'POST', headers: { 'Authorization': 'Bearer ENTER-YOUR-SECRET-KEY', 'Content-Type': 'application/json', }, body: JSON.stringify({ inputs: {}, query: "Tell me a story", response_mode: "streaming", user: "abc-123" }) });
const reader = response.body.getReader(); const decoder = new TextDecoder();
while (true) { const { done, value } = await reader.read(); if (done) break;
const chunk = decoder.decode(value); const lines = chunk.split('\n');
for (const line of lines) { if (line.startsWith('data: ')) { const data = JSON.parse(line.substring(6)); if (data.event === 'message') { process.stdout.write(data.answer); } else if (data.event === 'message_end') { console.log('\n\nResponse completed!'); console.log('Metadata:', data.metadata); } } } }}
streamChat();错误处理
常见错误代码
| 错误代码 | 说明 | 解决方案 |
|---|---|---|
| 401 | 未授权 | 检查 API 密钥 |
| 429 | 速率限制 | 减少请求频率 |
| 500 | 服务器错误 | 稍后重试 |
| 400 | 请求错误 | 检查请求参数 |
错误处理示例
PRTCL // PYTHON
import requestsfrom requests.exceptions import RequestException
def chat_with_retry(url, headers, data, max_retries=3): for attempt in range(max_retries): try: response = requests.post(url, headers=headers, json=data) response.raise_for_status() return response.json() except RequestException as e: if response.status_code == 429: wait_time = 2 ** attempt # 指数退避 time.sleep(wait_time) continue elif response.status_code >= 500: if attempt < max_retries - 1: time.sleep(wait_time) continue raise e return None最佳实践
性能优化
批量请求:
PRTCL // PYTHON
def batch_chat(messages): # 批量处理多个请求 results = [] for message in messages: result = chat_with_retry(url, headers, { "inputs": {}, "query": message, "response_mode": "blocking", "user": "abc-123" }) results.append(result) return results缓存响应:
PRTCL // PYTHON
from functools import lru_cache
@lru_cache(maxsize=100)def cached_chat(query): return chat_with_retry(url, headers, { "inputs": {}, "query": query, "response_mode": "blocking", "user": "abc-123" })监控和日志
监控 API 使用:
PRTCL // PYTHON
import logging
def log_api_call(endpoint, status, response_time): logging.info(f"API: {endpoint} | Status: {status} | Time: {response_time}ms")
def monitor_chat(): start_time = time.time() response = chat_with_retry(url, headers, data) response_time = (time.time() - start_time) * 1000 log_api_call('chat', response.status_code, response_time) return response测试策略
单元测试:
PRTCL // PYTHON
import unittest
class TestDifyAPI(unittest.TestCase): def test_chat(self): response = chat_with_retry(url, headers, { "inputs": {}, "query": "Hello", "response_mode": "blocking", "user": "test" }) self.assertIsNotNone(response) self.assertIn('result', response)集成测试:
PRTCL // PYTHON
def test_conversation_flow(): # 开始对话 response1 = chat_with_retry(url, headers, { "inputs": {}, "query": "Hello", "response_mode": "blocking", "user": "test" }) conversation_id = response1['conversation_id']
# 继续对话 response2 = chat_with_retry(url, headers, { "inputs": {}, "query": "How are you?", "response_mode": "blocking", "conversation_id": conversation_id, "user": "test" })
self.assertIsNotNone(response2)资源链接
- API 文档: https://docs.dify.ai/zh/use-dify/publish/developing-with-apis
- API 参考: https://docs.dify.ai/zh/reference/api
- 示例代码: https://github.com/langgenius/dify-api-examples
最后更新: 2026-03-12 作者: EchoHaoRan
R P
Rhine Lab Pioneer Division
Auth_Verified: 2026.05.29
Auth_Verified: 2026.05.29
