RicoSuter / NSwag

The Swagger/OpenAPI toolchain for .NET, ASP.NET Core and TypeScript.
http://NSwag.org
MIT License
6.69k stars 1.24k forks source link

Support property level examples #653

Open robert-matusewicz opened 7 years ago

robert-matusewicz commented 7 years ago

Hi,

I noticed that there is no way to define an example for a property. What I'm talking about is nicely explained here: https://stackoverflow.com/questions/36379298/how-to-provide-an-example-of-an-object-definition-in-swagger-that-contains-an-ar

Is there a change that you could add support for example property? Or offer some guidance how to implement it?

Thanks, Robert

RicoSuter commented 7 years ago

How would you specify the example?

dgioulakis commented 7 years ago

I would love to have this ability. Although, it's more an issue with NJsonSchema; unless NSwag inherits from JsonSchema4 to create properties specific to OpenAPI and leave NJsonSchema pure to the spec.

jokin commented 6 years ago

Thanks to @Cephei pointing in the NJsonSchema direction, I have found that it's something already doable.

you can add an attribute to the property and the schema will have the example informed.

[JsonSchemaExtensionData("example", "912345678")]
public string Phone  {get; set;}
"Phone": {
  "type": "string",
  "maxLength": 50,
  "minLength": 0,
  "example": "912345678"
},
RicoSuter commented 6 years ago

The latest version of NJS already has the example property, just NSwag is not yet released with this version... maybe there will be a problem with that when there is an "example" property and you add example to the extension data?

jokin commented 6 years ago

Well, it really feels like a workaround, but once is supported I can switch it. right now I'm just changing some properties so the automatic example object generated by swagger pass the validation.

RicoSuter commented 6 years ago

The exapmle properties are added to the model now (see master branch). But generating these (eg with an attribute) is still open... i think we need the concept of schema processers (like operation or document processors

RicoSuter commented 6 years ago

Just FYI: The next version of nswag/njs will support a jsonschemaprocessorattribute, https://github.com/RSuter/NJsonSchema/wiki/Schema-Processors

RicoSuter commented 6 years ago

... maybe we need this for properties too

icnocop commented 1 year ago

Example values for properties can be specified in XML comments.

For example:

public class Person
{
    /// <example>John</example>
    public string FirstName { get; set; }
}

Startup.cs:

services.AddOpenApiDocument((settings, serviceProvider) =>
{
    settings.GenerateExamples = true; // generate the example property of the schemas based on the <example> xml docs entry as JSON (requires <see cref="UseXmlDocumentation"/> to be true, default: true).
});