Search code examples
springspring-bootopenapi-generator

HttpMessageNotWritableException: No converter for [...] with preset Content-Type 'null'] with OpenApi Spring generator


I am implementing the petstore API with openAPI in a (gradle) spring boot project. I generate a server with the openapi generator plugin and implement a simple request:

@Service
@RestController
public class PetApiController implements PetApi {

    @Override
    public ResponseEntity<Pet> getPetById(Long petId) {
        Pet p = new Pet();
        p.setId(0L);
        p.setName("fido");
        p.setPhotoUrls(new ArrayList<String>());
        p.setStatus(StatusEnum.AVAILABLE);
        p.setTags(new ArrayList<Tag>());
        Category c = new Category();
        c.setId(3L);
        c.setName("dummy category");
        p.setCategory(c);
        
        ResponseEntity<Pet> r = new ResponseEntity<Pet>(p, HttpStatus.OK);
        
        return r;
    }
}

The swagger-ui that I generate offers both xml and json queries for a request, but xml doesn't seem to work:

$ curl -X GET "http://localhost:8080/pet/1" -H  "accept: application/xml"; echo ""

$ curl -X GET "http://localhost:8080/pet/1" -H  "accept: application/json"; echo ""
{"id":0,"name":"fido","category":{"id":3,"name":"dummy category"},"photoUrls":[],"tags":[],"status":"available"}

I even get an error message:

2020-09-10 09:04:34.213  WARN 23958 --- [nio-8080-exec-1] .w.s.m.s.DefaultHandlerExceptionResolver : Resolved [org.springframework.http.converter.HttpMessageNotWritableException: No converter for [class com.petstore.server.model.Pet] with preset Content-Type 'null']

However I cannot catch this exception and print the whole context, it only happens after return r

There is already a question with my exact error message: Springboot HttpMessageNotWritableException: No converter for [...] with preset Content-Type 'null'] But I still think my context is different since I generate my POJOs so I have no controll over them and I shouldn't have this problem in the first place since the plugin should generate everything fittingly.


Solution

  • The spring generator discriminates against xml by default, see the documentation: https://openapi-generator.tech/docs/generators/spring under

    Option  | Description                                       | Default
    --------+---------------------------------------------------+---------
    withXml | whether to include support for application/xml    | false
            | content type and include XML annotations in the   |
            | model (works with libraries that provide support  |
            | for JSON and XML)                                 |