如何解决如何在OpenAPI YAML文件中添加JAX-RS响应
我拥有REST服务,并且已经使用OpenAPI的YAML文件定义了API签名。
类似的东西
title: Sample Pet Store App
description: This is a sample server for a pet store.
termsOfService: http://example.com/terms/
contact:
name: API Support
url: http://www.example.com/support
email: support@example.com
paths:
v1/employees/{employeeId}:
get:
responses:
'200':
content:
....
从YAML文件中,我使用OpenAPI generator之类的东西生成API请求。
但是如何在我的YAML文件中指定https://docs.oracle.com/javaee/7/api/javax/ws/rs/core/Response.html?
这就是我要从Java代码发送响应的方式。我想知道如何将this Response object添加到OpenAPI的YAML中?
import javax.ws.rs.core.Response;
@Path("/v1/employees")
public Response getEmployee(String employeeId) {
// ...
return Response
.status(Response.Status.OK)
.entity(employee)
.build();
}
我是REST API开发的新手。我checked the documentation,但在OpenAPI中找不到有关如何添加Javax响应的详细信息。
解决方法
取决于您使用的模板,默认情况下不存在,但是您可以创建要使用的自定义模板。
here是可用模板的列表。
您必须指定根据OpenAPI规范返回的响应类型。像这样:
v1/employees/{employeeId}:
get:
operationId: getUser
responses:
200:
description: Return user
content:
application/json:
schema:
$ref: '#/components/schemas/UsertResponseDTO'
在那之后,如果您使用默认模板,则手动添加错字响应,如下所示:
import javax.ws.rs.core.Response;
@Path("/v1/employees")
public Response getEmployee(String employeeId) {
// ...
return Response.ok(employee).build();
}
,
为解决我的问题,我没有抛出Response对象,而是抛出了javax.ws.rs.WebApplicationException并添加了ExceptionTranslator代码以将所有异常转换为WebApplicationException。
这是有关异常翻译的示例代码。
// Actual code to convert Java exception into javax.ws.rs.WebApplicationException.
catch (Exception e) {
throw new WebApplicationException(getResponse(e));
}
// Exception translation code sample. This can be made into a nice generic function to handle different types of exceptions.
Response getResponse(Throwable t) {
if (throwable instanceof NotFoundException) {
Error error = new Error();
error.setType("404");
error.setMessage("Requested entry could not be found");
Response.status(Status.NOT_FOUND)
.entity(error)
.build();
}
}
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。