系列文章目录
第一章 Dify部署篇
第二章 Dify社区版使用篇-工作室-新手适用
第三章 Dify社区版使用篇-知识库
第四章 Dify社区版使用篇-工具
第五章 Dify社区版使用篇-工具-自定义
文章目录
SwaggerApi使用
OpenAPI-Swagger 使用规范
文档结构规范
- OpenAPI 版本:明确标注使用的 OpenAPI 版本(如
openapi: 3.0.0
)。 - 基本信息:包含
info
字段,需定义title
、version
、description
等基本信息。 - 服务器配置:通过
servers
字段指定 API 的基础访问路径。 - 路径与操作:在
paths
中定义 API 端点,每个端点需包含支持的 HTTP 方法(如get
、post
)。
参数与请求规范
- 路径参数:使用
parameters
定义路径中的变量,需注明name
、in
(如path
)、required
及schema
类型。 - 查询参数:通过
in: query
定义,需说明是否必填(required
)及数据类型(如string
、integer
)。 - 请求体:对于
POST
或PUT
请求,使用requestBody
描述请求数据的结构和示例。
响应与错误码规范
- 响应格式:每个操作需包含
responses
字段,至少定义成功(如200
)和错误(如400
、500
)的响应。 - 响应内容:使用
content
指定返回的数据类型(如application/json
)和结构(通过schema
或$ref
引用模型)。 - 错误信息:错误响应需包含清晰的
description
和示例,便于调试。
数据模型规范
- 组件复用:在
components
中定义可复用的模型(schemas
)、参数(parameters
)和响应(responses
)。 - 模型描述:每个模型需包含字段类型(
type
)、格式(format
)、示例(example
)及说明(description
)。
安全规范
- 认证方式:在
securitySchemes
中声明支持的认证类型(如apiKey
、OAuth2
)。 - 全局安全:通过
security
字段指定默认的认证方式,或在操作级别覆盖。
注释与扩展
- 注释:使用
description
字段为路径、参数、模型等添加详细说明。 - 扩展字段:可通过
x-
前缀添加自定义扩展属性(如x-deprecated
标记废弃接口)。
示例代码(JSON片段)
{
"openapi": "3.1.0",
"info": {
"title": "Get weather data",
"description": "Retrieves current weather data for a location.",
"version": "v1.0.0"
},
"servers": [
{
"url": "https://weather.example.com"
}
],
"paths": {
"/location": {
"get": {
"description": "Get temperature for a specific location",
"operationId": "GetCurrentWeather",
"parameters": [
{
"name": "location",
"in": "query",
"description": "The city and state to retrieve the weather for",
"required": true,
"schema": {
"type": "string"
}
}
],
"deprecated": false
}
}
},
"components": {
"schemas": {}
}
}
遵循上述规范可确保生成的 Swagger 文档清晰、易读且符合 OpenAPI 标准。
Dify工具如何自定义工具
对dify不了解的请看之前发布的几章内容。
- 登录dify页面,选择工具=>自定义,点击创建自定义工具
- 键入名称,比如我们自己制作一个天气小工具,输入名称 天气,选择例子中 天气JSON
- 这时我们会看到给出的JSON样例,需要调整内容
- 如下是我已经调整过的内容,用的是高德地图api接口,需要登录高德天气注册。大家可以去看我另外一篇文章 玩转PostMan之调试天气接口-高德天气 API,
{
"openapi": "3.1.0",
"info": {
"title": "Get weather data",
"description": "Retrieves current weather data for a location.",
"version": "v1.0.0"
},
"servers": [{
"url": "https://restapi.amap.com"
}],
"paths": {
"/v3/weather/weatherInfo": {
"get": {
"description": "Get temperature for a specific location",
"operationId": "GetCurrentWeather",
"parameters": [ {
"name": "city",
"in": "query",
"description": "The city and state to retrieve the weather for",
"required": true,
"schema": {
"type": "string"
}
}
],
"deprecated": false
}
}
},
"components": {
"schemas": {}
}
}
-
修改后,点击下面测试按钮进行测试
-
点击鉴权方法右侧设置图标,输入从高德地图获取的apikey
-
输入city值,这时北京城市编码,更多编码去另外一篇文章 玩转PostMan之调试天气接口-高德天气 API 查看高德API文档或者直接访问高德官网API。这时点击测试会看到下图显示
-
最后保存,就会做好一个小工具了。
-
天气小工具可以在dify中使用, 参看 第四章 Dify社区版使用篇-工具
把代码解释器换成天气小工具就可以了