Home > Back-end >  Adding another MediaType to REST api endpoint that is used by other clients
Adding another MediaType to REST api endpoint that is used by other clients

Time:01-29

In my app I am sharing REST api using Spring MVC, which users may use in their custom apps. Let's say I have an endpoint in Controller class:

@GET
@Path("/getNumber")
@Produces({ MediaType.TEXT_PLAIN })
public String getNumber(Long id) {
    return service.getNumber(id);
}

which response is available only as TEXT_PLAIN. What would happen, if for example one of the client say that his app will not work when he gets response as plain text and that the endpoint should return json/or should have possibility to return response in json? So when I add another MediaType to annotation @Produces, may that cause problems with other users custom apps using this endpoint? Because for ex. in their apps, client may be expecting response as plain text, and by getting response as json, response will not be handled correctly? If adding this MediaType may cause problems, what can I do to take into account users custom apps using this endpoint? Should I create similar endpoint, but this one will have MediaType APPLICATION_JSON, or both, with added for ex. "/v2" in endpoint path, or is there some better solution for that?

@GET
@Path("/v2/getNumber")
@Produces({ MediaType.TEXT_PLAIN, MediaType.APPLICATION_JSON })
public String getNumber(Long id) {
    return service.getNumber(id);
}

CodePudding user response:

No need to create multiple endpoints. You can define multiple mediaTypes in @Produces.

Inorder to decide which MediaType should be sent as response, Client has to set the type of MediaType they are expecting in the "Accept" header when making the request.

Based on this "Accept" header you can decide what content-type to return.

CodePudding user response:

you can use "consume" keyword for Multiple media type

@GET(value = "/configuration", consumes = { MediaType.APPLICATION_JSON_VALUE, MediaType.MULTIPART_FORM_DATA_VALUE }) public String setConfiguration(@RequestPart MultipartFile file, @RequestBody Configuration configuration)

  •  Tags:  
  • Related