Issue
I am using Swagger version 2 with Java Spring. I have declared a property and it works fine and it generates a drop down list of value I assigned.
@ApiParam(value = "Pass any one Shuttle provider ID from the list", allowableValues = "1,2,3,4,10")
private Long hotelId;
Now, I need a way to populate this list which is passed in allowableValues
from my database as it could be random list as well as huge data. How can I assign list of values dynamically from database in this allowableValues
?
Solution
- You need to create constructor in SwaggerConfiguration class.
- @Autowire service and withdraw data you need from database
- assign this to
final
variable - assign this
final
variable toallowableValues
in annotation enjoy not efficient api
private final String allowableValues; public SwaggerConfiguration() { List<YourEntitiy> list = someService.findAll(); //code to get every value you need and add create comma separated String StringJoiner stringJoiner = new StringJoiner(","); stringJoiner.add(list.get(0).getValue()); this.allowableValues = stringJoiner.toString(); } @ApiParam(allowableValues = allowableValues)
But I think it's bad idea getting all ids from database just to create allowable values. Just validate in api method if that id exist and/or Create new api to get ids from database, use pagination from Spring Data project, like PageImpl<> javadocs
Answered By - Jakub PomykaĆa
Answer Checked By - Clifford M. (JavaFixing Volunteer)