swagger-ui icon indicating copy to clipboard operation
swagger-ui copied to clipboard

xml example cannot be generated for response type of array

Open borcherspm opened this issue 6 years ago • 37 comments

Q&A (please complete the following information)

  • OS: Windows 10
  • Browser: Firefox, Chrome, Edge
  • Method of installation: npm
  • Swagger-UI version: 3.11.0
  • Swagger/OpenAPI version: Swagger 2.0

Content & configuration

I've reproduced this locally, but even easier to demonstrate, petstore has the same issue.

Example Swagger/OpenAPI definition: https://generator.swagger.io/api/swagger.json

snippet from swagger.json

      responses:
        200:
          description: "successful operation"
          schema:
            type: "array"
            items:
              $ref: "#/definitions/Pet"

Describe the bug you're encountering

In swagger ui, when you have a GET that has a response that is a list, and you selected content type of xml, the Example Value has an error "XML example cannot be generated".

To reproduce...

Steps to reproduce the behavior:

  1. Go to https://editor.swagger.io
  2. Expand /pet/findByStatus
  3. Make sure Response content type is application/xml
  4. Example Value for status code 200 has "XML example cannot be generated"

Expected behavior

I would expect to see the example xml for the response.

Screenshots

image

borcherspm avatar Jun 15 '18 19:06 borcherspm

Hello @shockey , any ETA on a fix regarding this issue?

Mic75 avatar Mar 11 '19 17:03 Mic75

@shockey We're facing issue with XML sample generation in case of collection is part of response object. Kindly let us know about ETA on a fix.

euroform-pa avatar Apr 25 '19 09:04 euroform-pa

Added the demo project to reproduce the issue with Swashbuckle for Xml sample generation issue. Demo project Kindly suggest the solution to view correct Xml sample generation.

euroform-pa avatar Apr 30 '19 06:04 euroform-pa

Added the demo project to reproduce the issue with Swashbuckle for Xml sample generation issue. Demo project Kindly suggest the solution to view correct Xml sample generation.

Any update on this?

euroform-pa avatar May 17 '19 12:05 euroform-pa

Any workaround solution for this?

wambling avatar Jul 13 '19 05:07 wambling

I think this might be related to older issue: XML Example for Arrays does not display #3132

Above issue does speak to at least some issue with Swashbuckle OpenAPI generation:

Yes we are but its an issue with Swashbuckle not generating the appropriate swagger doc info; once i add that information in, the UI renders fine ... the Petstore example is also broken in the same way and needs to be amended to include the xml.name/wrapped elements

Re. workaround, there is more information in above issue:

I just realized a single-item example is actually correct. To have array items wrapped into an extra tag, the array schema must have xml.wrapped=true.

Another issue ´seems to be related as well: XML example cannot be generated with 'allOf' #4423

This has been an issue for a while, but apparently not a priority to fix (I assume collaborators are all using json or don't mind too much about XML examples).

NickNiebling avatar Sep 26 '19 06:09 NickNiebling

I'm using NuGet Package Swashbuckle.AspNetCore 5.0.0-rc4 and this is still an Issue on November 12, 2019

ghost avatar Nov 13 '19 05:11 ghost

When you generate the schema for response type 200 for app/ToDoItems/1 we get the following schema for responses:

"responses": { "200": { "description": "Success", "content": { "application/json": { "schema": { "$ref": "#/components/schemas/TodoItem" } }, "application/xml": { "schema": { "$ref": "#/components/schemas/TodoItem" } } } },

When you generate the schema for response type 200 for app/ToDoItems we get the following schema for responses:

"responses": { "200": { "description": "Success", "content": { "application/json": { "schema": { "type": "array", "items": { "$ref": "#/components/schemas/TodoItem" } } }, "application/xml": { "schema": { "type": "array", "items": { "$ref": "#/components/schemas/TodoItem" } } } } },

Its this second scenario that is producing the error "XML example cannot be generated; root element name is undefined" in the Swagger UI.

ghost avatar Nov 13 '19 06:11 ghost

You can use something like this to wrap

    responses:
      '200':
        description: Success
        content:
        
          'application/xml':
            schema:
              type: array
              items:
                $ref: '#/components/schemas/SDDLItem'
              xml:
                name: response

components: schemas:

SDDLItem:
  type: object
  xml:
    name: SDDLItem  

calife avatar Jan 29 '20 11:01 calife

Did anyone figure out a workaround for this issue or does this issue still exist?

whateverxforever avatar Mar 12 '20 12:03 whateverxforever

You can use something like this to wrap

    responses:
      '200':
        description: Success
        content:
        
          'application/xml':
            schema:
              type: array
              items:
                $ref: '#/components/schemas/SDDLItem'
              xml:
                name: response

components: schemas:

SDDLItem:
  type: object
  xml:
    name: SDDLItem  

This is not working due to some reason.

whateverxforever avatar Mar 12 '20 12:03 whateverxforever

Did anyone figure out a workaround for this issue or does this issue still exist?

Providing any schema: xml: name: ... did the trick for me. The value is ignored (because schema: xml: wrapped: true is not set), but at least the example is rendered fine.

fdcds avatar Apr 08 '20 16:04 fdcds

Hi all

Are there some updates about this? I think I have a similar problem:

I have a Spring Boot Rest Api and I want to have the swagger documentation. Mostly the Api produces application/xml. When the return class is annotated with XmlRootElement and the properties have the XmlElement attributes everything is working fine. But if a primitive type or a List is returned, the root element is missing. Is it somehow possible to tell springdoc he should use jaxb to generate all this information/names. So that the xml has the root name and everything which then really gets returned?

Thank you very much and best Simon

Sslimon avatar Jun 08 '20 19:06 Sslimon

I found a work-around for this https://app.swaggerhub.com/apis/whateverxforever/SampleApi/v1-oas3

 get:
      summary: List of all orders
      operationId: getOrderList
      responses:
        '200':
          description: OK
          content:
            application/json:
              schema:
                type: object
                properties:
                  data:
                    type: array
                    items:
                      $ref: '#/components/schemas/Order'
            application/xml:
              schema:
                type: object
                xml:
                  name: Data
                properties:
                  data:
                    type: array
                    items:
                      $ref: '#/components/schemas/Order'

I hope this helped! 😉

whateverxforever avatar Jun 08 '20 19:06 whateverxforever

@whateverxforever Thanks for you response :)

This would work, yes. But I use springdoc openapi which generates the swagger json file for me. When I annotate my models with @XmlRootElement and @XmlElement the generated schema: xml: is written correctly.

For example like this:

@XmlRootElement
public class Employee {
    @XmlElement
    private Address address;
}

@XmlRootElement
public class Address {
}

But if the return type of an endpoint is a primitive data type like boolean or a List<SomeObject> than the schema: xml: is completely missing.

I could add them manually, but the project is quite big. Or I could write wrapper classes, but I should not change the code.

My idea then was if swagger could use jaxb to create this xml informations. Like this, the xml names would be exactly the same as the rest endpoint returns.

Do you know more or less what i mean :)

Sslimon avatar Jun 08 '20 19:06 Sslimon

Hello @Sslimon,

I faced the same issue while generating docs using Stoplight for my project. Stoplight was generating the doc fine for JSON data but for XML I had to manually go at each end point and write the code myself. I know it's not what you wanted to hear 😓, but I think this is a common issue in swagger. Sorry couldn't be of any more help.

whateverxforever avatar Jun 08 '20 19:06 whateverxforever

Okay, too bad. I was hoping that somebody maybe knows a workaround, but then I can't avoid to adapt it myself :) The JSON is also correct, only the xml stuff is sometime wrong/not complete. But thank you very much for your answers and help!

Sslimon avatar Jun 08 '20 20:06 Sslimon

I just hit this bug and wow almost 3 years and no fix...

arivera12 avatar Jun 22 '21 00:06 arivera12

Same here - Using Swashbuckle 6.1.4 for .NET 5.0.7; I guess no one cares about XML anymore? :)

MDerrickGlass avatar Jul 16 '21 06:07 MDerrickGlass

Oh my god... I worked many hours for setting up integration between Maven, Jersey, Swagger, Swagger UI... for documenting my WS and now I discover that there is such a big blocking bug, open since 3 years??? I ask for Swagger developers intervention and for workaround suggestions from peers. Thanks

bluish5 avatar Jul 23 '21 16:07 bluish5

At least someone understood if the problem is in the swagger.json generated by Swagger Core or in the way that Swagger UI interprets it? Just to find where we could try to create a workaround in the meanwhile... Thanks

bluish5 avatar Jul 23 '21 16:07 bluish5

Thanks to these posts:

  • https://stackoverflow.com/a/14265494/505893 (a simple technique to define your customized swagger.json)
  • https://github.com/swagger-api/swagger-ui/issues/4650#issuecomment-640815541 (how to correct swagger.json)

I solved the problem with this workaround, waiting for the bug to be solved:

  • i take the generated swagger.json
  • i format it with Notepad++ and its JSON plugin
  • wherever I find a block like this:
"type": "array",
"items": {
	"$ref": "#/definitions/MyObject"
}

I replace it with a block like this:

"type": "object",
"xml": {
	"name": "MyObjects"
},
"properties": [
	{
		"type": "array",
		"items": {
			"$ref": "#/definitions/MyObject"
		}
	}
]
  • I save the new file in a webapp folder and use its URL in Swagger UI for rendering docs

bluish5 avatar Jul 23 '21 23:07 bluish5

The issue doesn't seem to have a workaround when the XML is just one element with a text node.

The goal is <token>xxxx</token> but I got

<token>
	<token>string</token>
</token>
            application/xml:
              schema:
                type: object
                xml:
                  name: token
                properties:
                  token:
                    type: string

ppazos avatar Nov 25 '21 06:11 ppazos

I found out that if you include an xml name AND wrapped: true it wil generate a correct xml example, and even arrays of string can be controlled how the xml examle is shown for the element tag.

For example in the Pet example code if you add these 3 lines to the response code and/or these 2 lines to the items section in de definitions:

responses:
        "200":
          description: "successful operation"
          schema:
            type: "array"
            xml:             # <<
              name: "Pets"   # << root tag name
              wrapped: true  # << mandatory
            items:
              $ref: "#/definitions/Pet"
...
definitions:
  Pet:
    type: "object"
    required:
    - "name"
    - "photoUrls"
    properties:
      id:
        type: "integer"
        format: "int64"
        xml:
          attribute: true
      category:
        $ref: "#/definitions/Category"
      name:
        type: "string"
        example: "doggie"
      photoUrls:
        type: "array"
        xml:
          name: "PhotoUrls"
          wrapped: true
        items:
          xml:                # <<
            name: "PhotoUrl"  # <<  
          type: "string"
          example: "(uuencoded string)"
      tags:
        type: "array"
        xml:
          name: "Tags"
          wrapped: true
        items:
          $ref: "#/definitions/Tag"
      status:
        type: "string"
        description: "pet status in the store"
        enum:
        - "available"
        - "pending"
        - "sold"
    xml:
      name: "Pet"

it wil correctly make an example with a root tag <Pets>:

<?xml version="1.0" encoding="UTF-8"?>
<Pets>
	<Pet id="0">
		<Category id="0">
			<name>shepherd</name>
		</Category>
		<name>doggie</name>
		<PhotoUrls>
			<PhotoUrl>(uuencoded string)</PhotoUrl>
		</PhotoUrls>
		<Tags>
			<Tag id="0">
				<name>playfull</name>
			</Tag>
		</Tags>
		<status>available</status>
	</Pet>
</Pets>

JeroenHeemskerk avatar Jan 21 '22 11:01 JeroenHeemskerk

Thank you @JeroenHeemskerk, your workaround works and is simpler than mine! For my own reference I report it in JSON format. When Swagger writes a block like this:

"200": {
    "description": "successful operation",
    "schema": {
        "type": "array",
        "items": {
            "$ref": "#/definitions/MyObject"
        }
    }
},

we can correct it inserting this block:

"xml": {
    "name": "MyObjects",
    "wrapped": "true"
},

and obtaining this:

"200": {
    "description": "successful operation",
    "schema": {
        "type": "array",
        "xml": {
            "name": "MyObjects",
            "wrapped": "true"
        },
        "items": {
            "$ref": "#/definitions/MyObject"
        }
    }
},

bluish5 avatar Feb 15 '22 08:02 bluish5

@bluish5 Thanks for this. I am getting a similar issue when I am using the Swagger-ui with Java OpenAPI and I am not understanding where to add the wrapped:true in this:

import javax.ws.rs.Consumes;
import javax.ws.rs.POST;
import javax.ws.rs.Path;
import javax.ws.rs.Produces;
import javax.ws.rs.core.MediaType;
import java.util.Map;

@Path("/api")
public class RestControllerResponse {

    @Path("/generate")
    @POST
    @Consumes({MediaType.APPLICATION_JSON, MediaType.APPLICATION_XML})
    @Produces({MediaType.APPLICATION_JSON, MediaType.APPLICATION_XML})
    public String generator(final Map<String, Object> input) throws Exception {
        return "Hello From Generator Method";
    }
}

Please let me know where to add.

Aravinda93 avatar Apr 25 '22 11:04 Aravinda93

@Aravinda93, I do not understand your question. The workaround I described is for yaml or json file. Are you generating swagger files from a RestController or do you have a swagger yaml or json file as well?

JeroenHeemskerk avatar Apr 26 '22 09:04 JeroenHeemskerk

@JeroenHeemskerk I am developing a RestController application using the Quarkus. Within this, I am using the OpenAPI to add the annotations to my method. This functionality can be tested on the Swagger-UI.

When the application gets started the openapi.yaml is created automatically based on the OpenAPI annotations. In my Swagger-UI I am getting the error XML example cannot be generated; root element name is undefined.

I am not creating the yaml files myself so I wanted to know where can I add the wrapped:true in my Annotations so as to fix this issue.

Ref document: https://quarkus.io/guides/openapi-swaggerui

Aravinda93 avatar Apr 26 '22 10:04 Aravinda93

Hi @Aravinda93, my solution is to edit the generated YAML (or JSON in my case) file, after it has been generated. You save it with a different file name and when user opens Swagger-UI you feed it with your edited file instead of the generated one. Obviously, from now on, whenever your introduce changes in your API annotations (e.g. when you create a new WS method), you must keep your edited version up-to-date. Hope it's all clear ;)

bluish5 avatar Apr 27 '22 07:04 bluish5

@borcherspm, I see the XML attribute it is added to the 3.0.0 spec https://github.com/OAI/OpenAPI-Specification/blob/main/versions/3.0.0.md#xml-attribute-prefix-and-namespace but i do not see an annotation for it in the swagger-ui in the https://github.com/eclipse/microprofile-open-api/wiki/Annotation-Samples nor in the code on GitHub. I am affraid there is no annotation for it build yet.

There may be a workaround if you make a OASFilter: https://github.com/eclipse/microprofile-open-api/wiki/OASFilter-Samples using a "filterSchema". Something like the pseudocode below (warning untested code block)

@Override
Schema filterSchema(Schema schema) {
  if ( /* test if this is the corrrect definition/response */ ) {
     schema.SetXml(new Xml().name("myObjects").wrapped(true));
  }
  return schema;
}

JeroenHeemskerk avatar Apr 28 '22 09:04 JeroenHeemskerk