Search code examples
javaopenapiopenapi-generatoropenapi-generator-maven-plugin

Handling two different response media types with openapi-generator-maven-plugin


I'm generating the sources of an OpenAPI contract with the openapi-generator-maven-plugin maven plugin (version 5.4.0).

I'm using the java generator and the webclient library.

I have one endpoint that is responding either application/octet-stream or application/json :

    "responses": {
      "200": {
        "content": {
          "application/octet-stream": {
            "schema": {
              "type": "string",
              "format": "byte"
            }
          },
          "application/json": {
            "schema": {
              "$ref": "#/components/schemas/TheResponseObject"
            }
          }
        }
      },

The problem is that the plugin is just considering the first media type (in the order of declaration) to generate the according java return type.

With the example above, I have to deal with byte[].

If I invert the media types (application/json first), I have to deal with the TheResponseObject.

Is there a way to handle both of them and to get the good format according to the response headers ?


Solution

  • To handle this, I've changed the contract to always handle byte[] in the response.

            "content": {
              "application/plain": {
                "schema": {
                  "type": "string",
                  "format": "byte"
                }
              },
    

    Then, instead of calling api.theEndpoint(...), I'm calling api.theEndpointWithHttpInfo(...) which sends back a ResponseEntity<byte[]> object.

    According to the content type, I can choose how to process the result :

            if (MediaType.APPLICATION_JSON.isCompatibleWith(reponse.getHeaders().getContentType())) {
                // parse json response (reponse.getBody()) 
            } else {
                // it's a pdf 
            }