JDGale8
JDGale8

Reputation: 35

Swagger throws 400 error when optional query is not included

I have defined an endpoint in Spring, and defined a single ApiParam as optional.

@RequestMapping(value = "/searchResult/getList", method = RequestMethod.GET)
@ApiOperation(value = "populate list")
public JasonMessage getList(@ApiParam(name="id", value = "id", required = false)
                            @RequestParam Integer id) {

However when I write the url without the ?id=xxx parameter, I get a 400 error, which I expect is a malformed Url error.

Why is this? I have defined it as required = false, and it's not a path variable, however there's no way I can write the url without including at least an empty query parameter, like ?id=.

Am I confused about what is a genuinely optional parameter for URLs, is it an issue with swagger, an issue with spring, or a mistake I have made somewhere.

The response body is no content and the Response Code is just 400.

Upvotes: 2

Views: 1936

Answers (1)

ug_
ug_

Reputation: 11440

You need to change your annotation to @RequestParam(required = false) the required field is defaulted to true. Additionally you can delete the required on @ApiParam because swagger will detect that from Springs annotations.

Remember, Swagger annotations are for additional information about your api and have NO impact on functionality of endpoints (outside their api page which is generated).

Additionally you should put the name of your request parameter on the @RequestParam annotation, this is again because Swagger annotations have no effect on Springs behavior.

Your final code should read

@RequestMapping(value = "/searchResult/getList", method = RequestMethod.GET)
@ApiOperation(value = "populate list")
public JasonMessage getList(@ApiParam
                            @RequestParam(value = "id", required = false) Integer id) {

Upvotes: 2

Related Questions