Unable to render this definition The provided definition does not specify a valid version field.
Please indicate a valid Swagger or OpenAPI version field. Supported version fields are swagger: "2.0" and those that match openapi: 3.0.n (for example, openapi: 3.0.0).
Where do I need to insert the correct version to the stop the error below. Swagger editor works ok, but when launching a particular project I receive this error.First time using Swagger. Many Thanks
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With