Hi
As per Swagger 2.0 specification schema object now includes example. Could you please explain how to achieve that using Swashbuckle?
Thanks,
Paresh
You can set the example property on a schema object by wiring up an "ISchemaFilter" as shown below:
AddSchemaExamples.cs
public class AddSchemaExamples : ISchemaFilter
{
public void Apply(Schema schema, SchemaRegistry schemaRegistry, Type type)
{
if (type == typeof(Product))
{
schema.example = new Product
{
Id = 123,
Type = ProductType.Book,
Description = "Treasure Island",
UnitPrice = 10.0M
};
}
}
}
SwaggerConfig.cs
.EnableSwagger(c =>
{
c.SchemaFilter<AddSchemaExamples>()
});
NOTE: while this WILL be emitted in the Swagger JSON it will NOT show up any differently in the UI. Unfortunately, swagger-ui is well behind the 2.0 spec and playing catch up to support a lot of the new spec items:
Thank you for your reply. It makes sense now why I wasn't able to see it in Swagger UI
Is there currently any workaround for this to work all the way?
Instead of setting "schema.example" could you try setting "schema.@default" in your schema filter?
I think (unexpectedly IMO) this is the property that the swagger-ui uses to pre-populate the JSON in the swagger-ui.
Let me know if this works - thx
Actually, even setting schema.example worked for SOME of the types but not for the others. And after I updated the Swashbuckle to the latest version they even showed up in the UI. However, I couldn't get other types set in schema.example to show up no matter what I did. And I don't see ANY difference in terms of definitions between the types that show up and the ones that don't show up. Changing code so that it sets schema.@default instead of schema.example worked for ALL the types that I defined, but I am wondering if this is the right approach and what is the difference between schema.example and schema.@default ?
Thanks.
Also, is there any way to specify a sample for collection (array) of objects? In HelpPageConfig I used to be able to specify it as IEnumerable
...
typeof(IEnumerable<AccountWarningModel>), GetSampleAccWarnings()
...
public static AccountWarningModel[] GetSampleAccWarnings() {
return new AccountWarningModel[]
{
GetSampleAccWarning(123),
GetSampleAccWarning(345)
};
}
Here it always return a single object from the collection. How can I tell it to look at the collections as well?
It's been almost a year since I posted my last question I am still looking for an answer. Is there any way to specify a sample for collection (array) of objects? Please tell how?
Is there any way to achieve this without using swashbuckle? Just using swagger core?
Most helpful comment
It's been almost a year since I posted my last question I am still looking for an answer. Is there any way to specify a sample for collection (array) of objects? Please tell how?