Thursday, April 2, 2020

Spring REST Controller: Resolve conflicts between root controllers endpoints and swagger-ui.html


Our team had some issues setting up swagger. We've been adding swagger to multiple services and for a strange reason, one service was not loading the swagger-ui.html. After some testing, we realize there was a conflict with some endpoint that were mapping to the root of the site:

@RestController
public class ReportController {
    
    @RequestMapping(method = RequestMethod.GET, value = "/{reportId}")
    public ResponseEntity getReport(@PathVariable String reportId) {
        ....
    }
}

As we can see, since controller class has no request mapping, and endpoint method is mapping with /{some_id}, when we try to hit /swagger-ui.html, the request is mapped to this method.

After googling a lot, we ended up just making our request mapping more specific to a certain type of ids. In our case we are using mongo ids for the reports. It means ids can only have number or letters in lowercase.


@RestController
public class ReportController {
    
    @RequestMapping(method = RequestMethod.GET, value = "/{reportId:^[0-9a-f]+$}")
    public ResponseEntity getReport(@PathVariable String reportId) {
        ....
    }
}

Now because swagger-ui.html contains a dot (.) and a dash (-), the request is not being caught by this endpoint anymore.

No comments:

Post a Comment