-1

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).

@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?

halfer
  • 19,824
  • 17
  • 99
  • 186
  • This can simplify, as most of the concerns will be handled by Spring [Create two method for same url pattern]( https://stackoverflow.com/a/15853217/7878602) – ImtiazeA Sep 08 '20 at 04:41

2 Answers2

1

you need to version your API . There are many ways to do it.

  1. URI versioning

    ex: http://myapi/v1/users http://myapi/v2/users

  2. Media Type versioning Example Accept: application/vnd.myapi.v1+json

Achalveer
  • 61
  • 3
0

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

vaquar khan
  • 10,864
  • 5
  • 72
  • 96