Swagger..Unable to render this definition The provided definition does not specify a valid version field
Your API definition is missing the OpenAPI/Swagger version number, in this case "swagger": "2.0"
. Add it at the beginning, like so:
{
"swagger": "2.0",
"title" : "Music API Documentation",
...
I encountered this same problem today. In my case it is the Gson
configuration which lead to the error. If you are also using Gson
with SpringMVC
, may be you could try this out:
I am setting up a rest-api project using spring boot 2.2.4 and spring fox swagger 2.9.2 . Since I am more familiar with Gson
than Jackson
, I replaced the default MessageConverter:
@Configuration
@EnableWebMvc
public class MvcConfiguration implements WebMvcConfigurer {
private final Gson gson = new Gson();
// ......
@Override
public void configureMessageConverters(List<HttpMessageConverter<?>> converters) {
GsonHttpMessageConverter gsonHttpMessageConverter = new GsonHttpMessageConverter();
gsonHttpMessageConverter.setGson(gson);
converters.add(gsonHttpMessageConverter);
}
// ......
}
After that the "http://localhost:8080/swagger-ui.html" breaks like the question described. Then I typed "http://localhost:8080/v2/api-docs" in browser and noticed the swagger doc was wrapped into another layer, with an unnecessary "value" field like this:
{
value: "{"swagger":"2.0","info":{"description": ......}}"
}
No doubt swagger cannot find the "swagger":"2.0"
field if api-docs yields something like that. The value of "value" field is the actual swagger doc.
After some search I found that swagger doc will be incorrectly serialized by Gson if you leave it be. The solution is simple - register a serializer for swagger to your Gson bean:
private final Gson gson = new GsonBuilder()
.registerTypeAdapter(Json.class, new SpringfoxJsonToGsonAdapter())
.create();
private static class SpringfoxJsonToGsonAdapter implements JsonSerializer<Json> {
@Override
public JsonElement serialize(Json json, Type type, JsonSerializationContext context) {
final JsonParser parser = new JsonParser();
return parser.parse(json.value());
}
}
where Json
is a class provided by springfox:
import springfox.documentation.spring.web.json.Json;
Hope this would help.