Reputation: 7217
I have a swagger definition and I'm using XML comments to describe the request and response and give meaningful samples. Example model as follows:
/// <summary>Created item information.</summary>
public class ItemCreated
{
/// <summary>Outcome of the item being created.</summary>
/// <value>The outcome.</value>
/// <example>Item has been Created</example>
public string Outcome { get; set; }
/// <summary>Unique item reference.</summary>
/// <value>The Item reference.</value>
/// <example>6001002982178</example>
public string Reference { get; set; }
/// <summary>The external reference for the package.</summary>
/// <value>The carrier reference.</value>
/// <example>5558702516</example>
public string ExternalReference { get; set; }
/// <summary>The items documents.</summary>
/// <value>The items documentation.</value>
/// <example>???</example>
public List<Documentation> Documents { get; set; }
}
/// <summary>Item documentation information.</summary>
[JsonObject("Documentation")]
public class Documentation
{
/// <summary>The document in base64 format.</summary>
/// <value>The document base64 string.</value>
/// <example>JVBERi0xLjMNCjEgMCBvYmoNCjw8DQovVHlwM...</example>
[JsonProperty("Document")]
public string Document { get; set; }
/// <summary>The type of the document.</summary>
/// <value>The documentation type.</value>
/// <example>ITEMDOCUMENT_SLIP1</example>
public DocumentationType Type { get; set; }
/// <summary>Document format.</summary>
/// <value>The format of the document.</value>
/// <example>Pdf</example>
public string Format { get; set; }
/// <summary>The document resource uri.</summary>
/// <value>The link to the document resource.</value>
public string Link { get; set; }
}
Showing as this in swagger:
What I need is to show a more complex response example. You can see one of the properties is an array here - I'd like to show multiple document types - so multiple array items. How do I show this? The "" node doens't allow for multiple examples in an array.
Thanks for any points in advance!
Upvotes: 2
Views: 3012
Reputation: 4614
One way to do this would be using Schema Filters:
[SwaggerSchemaFilter(typeof(ItemCreatedSchemaFilter))
public class ItemCreated
{
⋮
}
public class ItemCreatedSchemaFilter : ISchemaFilter
{
public void Apply(OpenApiSchema schema, SchemaFilterContext context)
{
if (schema.Type == typeof(ItemCreated))
{
schema.Example = new OpenApiObject
{
// Other Properties
["Documents"] = new OpenApiArray
{
new OpenApiObject
{
// Other Properties
["Document"] = new OpenApiString("JVBERi0xLjMNCjEgMCBvYmoNCjw8DQovVHlwM..."),
["Format"] = new OpenApiString("Pdf")
},
new OpenApiObject
{
// Other Properties
["Document"] = new OpenApiString("Something else"),
["Format"] = new OpenApiString("Something else")
}
}
};
}
}
}
Reference: Apply Schema Filters to Specific Types
Remember to add the new filter to the SwaggerGen options:
services.AddSwaggerGen(c =>
{
c.SchemaFilter<ItemCreatedFilter>();
...
}
Upvotes: 2