'How do I manually order the endpoints displayed on Swagger UI?
I'm using Docket to configure my Swagger 2 instance. But the only Options I currently see are to sort by Type (POST, GET, etc.) or by endpoint name (a-z).
There is a logical order to my endpoints and I'd like to display them in that order
What I want:
POST /start
POST /uplaod
POST /finalize
POST /checkStatus
Instead I get something like this:
POST /checkStatus
POST /finalize
POST /start
POST /upload
Code:
@Bean
public Docket api() {
return new Docket(DocumentationType.SWAGGER_2)
.host(swaggerHost)
.pathProvider(new RelativePathProvider(servletContext) {
@Override
public String getApplicationBasePath() {
return swaggerBasePath;
}
})
.select()
.apis(RequestHandlerSelectors.withClassAnnotation(Api.class))
.build()
.apiInfo(apiInfo())
.securitySchemes(Collections.singletonList(securitySchema()))
.securityContexts(Collections.singletonList(securityContext()));
}
Solution 1:[1]
Sorting operations in Swagger UI - Sort by specific http verb order, then by path
operationsSorter: function (a, b) {
const order = {
'get': '0', 'post': '1', 'patch': '2', 'put': '3', 'delete': '4',
'head': '5', 'options': '6', 'connect': '7', 'trace': '8'
};
return (
order[a.get("method")].localeCompare(order[b.get("method")])
|| a.get("path").localeCompare(b.get("path"))
);
}
Solution 2:[2]
An easy way to order the endpoints for swagger UI is to use tags: https://swagger.io/docs/specification/grouping-operations-with-tags/
Edit: adding the alternative I use to address a comment below: I tend to use the operationsSorter with a custom comparison function. Example:
operationsSorter: function (a, b) {
var order = {'get': '0', 'post': '1', 'patch': '2', 'put': '3', 'delete': '4'};
if (a.get('path') == b.get('path')) {
return order[a.get('method')].localeCompare(order[b.get('method')]);
}
if (a.get('path').split('/').length == b.get('path').split('/').length) {
return a.get('path').split('/').slice(-1)[0].localeCompare(b.get('path').split('/').slice(-1)[0]);
}
return a.get('path').split('/').length - b.get('path').split('/').length;
}
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | Peter |
| Solution 2 |
