I am using Swashbuckle 5.6.0
and Swashbuckle.Examples.3.5.1
to document a WebApi2 project. I have an action which consumes an XML body and returns a text response. I want the documentation to include an example of the XML input - e.g. <SampleXml><!-- example XML --></SampleXml>
.
My swagger output is below, except that for the purposes of this question I have added the content-type application/json
to the comsumes
property. In reality, I only want to allow application/xml
and text/xml
.
When I view this with Swagger, I see:
When parameter content type application/xml
is selected, I get a generated XML example with my model name, i.e. <XmlModel></XmlModel>
.
When parameter content type application/json
is selected, I get my desired example input <SampleXml><!-- example XML --></SampleXml>
.
How can I get the example input while parameter content type application/xml
is selected?
{
"swagger": "2.0",
"info": {
"version": "v1",
"title": "Sample"
},
"host": "localhost:63434",
"schemes": [
"http"
],
"paths": {
"/sampleXml/": {
"post": {
"tags": [
"xmlSample"
],
"summary": "XML sample.",
"description": "Post XML sample",
"operationId": "Xml_Post",
"consumes": [
"application/xml",
"application/json",
"text/xml",
],
"produces": [
"text/plain"
],
"parameters": [
{
"name": "xmlContent",
"in": "body",
"description": "The content of the XML document.",
"required": true,
"schema": {
"$ref": "#/definitions/XmlModel"
}
}
],
"responses": {
"200": {
"description": "OK",
"schema": {
"type": "string"
}
},
}
}
}
},
"definitions": {
"XmlModel": {
"type": "object",
"properties": {},
"example": "<SampleXml><!-- example XML --></SampleXml>"
}
}
}
To change the root XML tag from <XmlModel>
to <SampleXml>
, add xml.name
to your schema definition:
"definitions": {
"XmlModel": {
"type": "object",
"xml": {
"name": "SampleXml"
}
}
}
This will produce the following sample XML in Swagger UI:
<?xml version="1.0" encoding="UTF-8"?>
<SampleXml>
</SampleXml>
And if you add property definitions:
"definitions": {
"XmlModel": {
"type": "object",
"xml": {
"name": "SampleXml"
},
"properties": {
"id": {
"type": "integer",
"example": 7,
"xml": {
"attribute": true
}
},
"foo": {
"type": "string",
"example": "bar"
}
}
}
}
your XML example will include the corresponding elements:
<?xml version="1.0" encoding="UTF-8"?>
<SampleXml id="7">
<foo>bar</foo>
</SampleXml>
However, if you want the literal string <SampleXml><!-- example XML --></SampleXml>
containing a <!-- comment -->
, it's not possible AFAIK.
Update: Swagger UI supports using literal XML strings only in response examples:
"responses": {
"200": {
"description": "OK",
"schema": {
"type": "string"
},
"examples": {
"application/xml": "<SampleXml><!-- example XML --></SampleXml>"
}
}
}
but not in request body examples.
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