R Plumber API如何编程式指定请求JSON Schema填充Swagger示例
R Plumber 配置JSON Schema自动生成Swagger请求示例
你当前编写的基础Plumber接口可正常在8080端口启动,代码如下:
pr() %>% pr_post("/echo", function(req, res) { if (is.null(req$body)) return("No input") list( input = req$body ) }) %>% pr_run(port = 8080)
针对你要实现的「直接读取请求体JSON内容」「编程定义JSON Schema自动填充Swagger请求示例」两个需求,可按如下方式实现:
核心实现逻辑
- Plumber默认会自动识别
Content-Type为application/json的请求,将请求体JSON自动解析为R原生列表对象,直接通过req$body即可读取解析后的结构化内容,无需额外引入JSON解析包手动处理。 - 可通过Plumber内置的
pr_set_api_spec方法编程式修改OpenAPI规范,自定义请求体对应的JSON Schema和示例值,服务启动后会自动同步到Swagger文档中,无需手动维护静态swagger配置文件。
可直接运行的完整代码
library(plumber) # 统一定义接口请求体的JSON Schema,后续结构调整只需要改这里 echo_req_schema <- list( type = "object", properties = list( user_id = list( type = "integer", example = 1001L, description = "用户唯一ID" ), text = list( type = "string", example = "这是一段测试输入文本", description = "待处理的文本内容" ), tag_list = list( type = "array", items = list(type = "string"), example = list("测试", "Plumber", "API") ) ), required = c("user_id", "text") ) pr() %>% # 注入自定义OpenAPI配置 pr_set_api_spec(function(spec) { # 将定义好的Schema注册到OpenAPI公共组件 spec$components$schemas$EchoReq <- echo_req_schema # 给/echo接口绑定请求体配置 spec$paths$`/echo`$post$requestBody <- list( required = TRUE, content = list( `application/json` = list( schema = list(`$ref` = "#/components/schemas/EchoReq") ) ) ) return(spec) }) %>% pr_post("/echo", function(req, res) { # 直接读取自动解析后的JSON请求体 if (is.null(req$body)) { res$status <- 400 return(list(error = "请求体不能为空")) } list( received_data = req$body, tip = "JSON内容已自动解析" ) }) %>% pr_run(port = 8080)
效果说明
服务启动后访问默认的Swagger文档地址http://127.0.0.1:8080/__docs__/,即可看到/echo接口的请求体已经关联了你定义的Schema,每个字段的类型、说明、示例值都会自动展示,点击Swagger的「Try it out」按钮会自动填充你预设的请求示例。
如果需要对请求参数做格式校验,可以直接复用顶部定义的
echo_req_schema写校验逻辑,避免Schema定义和校验规则重复维护。
内容的提问来源于stack exchange,提问作者David Smith
相关产品推荐
相关产品推荐

