英文:
Designing a REST API in Spring Boot
问题
@RequestMapping(value = "/listMessages", produces = {MediaType.APPLICATION_JSON_VALUE, MediaType.APPLICATION_XML_VALUE})
@ResponseBody
public List<?> getAllMessages(@RequestParam Map<String,String> allParams){
if(allParams.get("version").equalsIgnoreCase("v1") && allParams.size()==1)
return listMessagesService.getAllMessages();
else if (allParams.get("version").equalsIgnoreCase("v2") && allParams.size()>1)
return listMessagesService.getAllMessagesV2("v2");
return null;
}
这是我的代码。这段代码可接受吗?像这样设计API可以吗?
英文:
I need to design a REST api ListMessages service (there are 4 fields in title, url, content and sender) that service should support two response versions within the same endpoint. The caller is able to define which response version he can handle.
-
Messages returned by the first version should contain only title, content and sender fields. The first version must not accept any other parameters than the version parameter.
-
Messages returned by the second version should return all 4 fields.The second version also takes a parameter which defines the format in which the response is returned (supported formats could be e.g. JSON and XML).
<!-- comment -->
@RequestMapping(value ="/listMessages" , produces = {MediaType.APPLICATION_JSON_VALUE, MediaType.APPLICATION_XML_VALUE})
@ResponseBody
public List<?> getAllMessages(@RequestParam Map<String,String> allParams){
if(allParams.get("version").equalsIgnoreCase("v1" ) && allParams.size()==1)
return listMessagesService.getAllMessages();
else if (allParams.get("version").equalsIgnoreCase("v2") && allParams.size()>1)
return listMessagesService.getAllMessagesV2("v2");
return null;
}
This is my code. Is the code acceptable and is it OK to design API like this?
答案1
得分: 1
你需要对你的API进行版本管理。有许多方法可以实现。
-
URI版本管理
示例:http://myapi/v1/users
http://myapi/v2/users -
媒体类型版本管理
示例:
Accept:application/vnd.myapi.v1+json
英文:
you need to version your API . There are many ways to do it.
-
URI versioning
ex: http://myapi/v1/users
http://myapi/v2/users -
Media Type versioning
Example
Accept: application/vnd.myapi.v1+json
答案2
得分: 0
在提供解决方案之前,我有几个问题,根据您的回答,将更新设计:
问题:您是否获取到任何标识符,用于识别在响应中返回的两个字段还是全部四个字段?
假设:您在请求 JSON 中有一个标识符来识别客户端。
在您的响应 POJO 中使用 @JsonIgnore 属性:
因此,当您为 '客户A仅设置2个字段,其他字段为null,客户B设置所有4个字段' 返回响应时,
@JsonInclude(JsonInclude.Include.NON_NULL) 将隐藏响应 JSON 中的所有null值。
英文:
Before provide solution i have few question based on your answer will update design
Q. Are you getting any identifier which help you to identify return two fields in response or all four fields ?
Assumption : You have identifier in request json to identify clients
Use @JsonIgnore properties into your response POJO
So when you return response for '
Coutomer A set only 2 fields and other or null
Coutomer B set All 4 fields
@JsonInclude(JsonInclude.Include.NON_NULL) will hide all null values into your response Json
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论