我是使用swagger-node(swagger-spec 2.0)的新手,我需要使用我的API来生成和生成XML和JSON(因为这是客户想要的) . 目前我只关注“产品”部分 .
在生成响应时,我知道我可以使用jstoxml或easyxml等工具将我的js对象转换为XML . 所以问题是:在使用swagger-node时这是必要的还是假设要处理这个问题的工具?我想我需要帮助我的控制器代码应该返回什么 .
例如,使用swagger swagger project create myproject (choose express framework)
创建一个新项目
更改 /hello
api的yaml文件,以便 get:
同时返回json或xml
paths:
/hello:
# binds a127 app logic to a route
x-swagger-router-controller: hello_world
get:
description: Returns 'Hello' to the caller
# used as the method name of the controller
operationId: hello
produces:
- application/json
- application/xml
然后更改hello_world.js控制器以返回json对象而不是字符串
// variables defined in the Swagger document can be referenced using req.swagger.params.{parameter_name}
var name = req.swagger.params.name.value || 'stranger';
var hello = util.format('Hello, %s!', name);
// this sends back a JSON response which is a single string
res.json({message:hello});
}
当我启动项目并使用Postman with Header Accept = application / json时,我得到了响应:
{
"message": "Hello, stranger!"
}
如果我更改了 Headers Accept application/xml
,我仍然得到JSON响应,而不是XML . 我希望看到的是:
<object>
<message>Hello, stranger!</message>
</object>
我知道我的代码使用 res.json()
是错误的,因为我相信它将Content-Type设置为 application/json
.
我不知道还有什么用来产生XML响应 . 当我更改res.json()以使用easyxml时
var xml = easyxml.render({message:hello});
res.type('xml').end(xml);
然后我从swagger获得验证错误:
[
{
"status": 500,
"message": "Response validation failed: value expected to be an array/object but is not"
}
]
那么我的控制器应如何格式化响应以返回XML或JSON?
2 回答
我'm not exactly sure what easyxml is doing or why it'无法正常工作,但
jstoxml
效果很好:Accept: application/json
Accept: application/xml
显然,有正确的方式 no . remus的答案没有考虑Swagger explicit XML support . 在任何情况下,控制器绝对不应该混淆API i / o格式,而只是实现业务逻辑 .