Search code examples
javaxmlspring-bootpath-variables

XML response from API with PathVariable


I have the API:

@GetMapping(path = "/users/{userId}")
public ResponseEntity<UserDTO> getUserById(@PathVariable(value = "userId") Long userId) {
    //logic here
}

it returns JSON response, as it should.

And there's another app that I don't have access to, and it calls my API as, for example, GET /users/123.xml in order to receive XML response.

But in this case, my API fails with 400 error, because it cannot parse 123.xml into Long.

Option @GetMapping(value = {"/users/{userId}", "/users/{userId}.xml"}) fails with the same error.

What can I do to respond with XML syntax when calling /{userId}.xml and in the mean time, respond with JSON syntax when calling /{userId}?

EDIT:

I want it to do without specifically adding 'Accept' headers, and without writing any additional logic, that'll parse {userId}.xml and then set the appropriate response type.


Solution

  • That's can be done by using a ContentNegotiationConfigurer, you can configure it as follow :

    @Configuration
    @EnableWebMvc
    public class MvcConfig implements WebMvcConfigurer {
    
        @Override
        public void configureContentNegotiation(ContentNegotiationConfigurer configurer) {
            configurer
                    .defaultContentType(MediaType.APPLICATION_JSON)
                    .mediaType("xml", MediaType.APPLICATION_XML)
                    .mediaType("json", MediaType.APPLICATION_JSON);
        }
    }
    

    It should work fine with your endpoint :

    @GetMapping(path = "/users/{userId}", produces = {MediaType.APPLICATION_JSON_VALUE, MediaType.APPLICATION_XML_VALUE})
    public ResponseEntity<UserDTO> getUserById(@PathVariable(value = "userId") Long userId) {
        return new ResponseEntity<>(userService.get(userId), HttpStatus.OK);
    }