RicoSuter / NSwag

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

Example support in swagger doc generation not working #2397

Closed xantari closed 5 years ago

xantari commented 5 years ago

I've added example tags to my objects however they are not shown in the Swagger UI.

This seems to indicate that it will now process tags automatically without any operation processor.

https://github.com/RicoSuter/NJsonSchema/issues/1010

If you look at the above link it gives you an example: https://github.com/RicoSuter/NJsonSchema/wiki/XML-Documentation#define-examples

I have set the following:

My Controller:

[SwaggerResponse(HttpStatusCode.OK, typeof(bool))]
[SwaggerResponse(HttpStatusCode.InternalServerError, typeof(ApiResponse<List<ApiResponseCode>>))]
[HttpPost, Route("ProcessActivityUsingVendorData")]
public async Task<IHttpActionResult> ProcessActivityUsingVendorData(DownloadPaymentDataRequestDto request)
{
    _logger.GetLogger().Information("ProcessActivityUsingVendorData -> {@request}", request);
    var result = await _paymentGateway.GetPaymentActivityFromVendorData(request);

    var saveSuccessful = await _paymentProcessor.SaveWithARRTAsync(result);

    return Ok(saveSuccessful);
}

My object:

/// <example>
/// { "OrderNumber": 1,
///   "MerchantType": "ARRTRenewal" }
/// </example>
public class DownloadPaymentDataRequestDto
{
    public ARRTMerchants MerchantType { get; set; }
    //public string RequestId { get; set; }
    public int? OrderNumber { get; set; }
}

Swagger setup:

            app.UseSwaggerUi3(typeof(PaymentApiStartup).Assembly, settings =>
            {
                settings.DocExpansion = "list";
                settings.GeneratorSettings.SchemaType = SchemaType.OpenApi3;
                settings.GeneratorSettings.DefaultUrlTemplate = "api/{controller}/{id?}";
                settings.GeneratorSettings.GenerateExamples = true;
                settings.PostProcess = document =>
                {
                    document.Info.Title = "Internal API";
                    document.Info.Version = Assembly.GetExecutingAssembly().GetName().Version.ToString();
                };
            });

However it is not showing the Example tag:

image

Update 1: I can see the example in the swagger.json file, The UI for some reason doesn't interpret them properly?

      "DownloadPaymentDataRequestDto": {
        "type": "object",
        "example": {
          "OrderNumber": 1,
          "MerchantType": "ARRTRenewal"
        },
        "additionalProperties": false,
        "properties": {
          "MerchantType": {
            "$ref": "#/components/schemas/ARRTMerchants"
          },
          "OrderNumber": {
            "type": "integer",
            "format": "int32",
            "nullable": true
          }
        }
      },

I can see it reference that object here:

    "/Payment/ProcessActivityUsingVendorData": {
      "post": {
        "tags": [
          "Payment"
        ],
        "summary": "Saves a completed payment to the database using Cybersource REST API's to retrieve the order details",
        "operationId": "Payment_ProcessActivityUsingVendorData",
        "requestBody": {
          "x-name": "request",
          "content": {
            "application/json": {
              "schema": {
                "nullable": true,
                "oneOf": [
                  {
                    "$ref": "#/components/schemas/DownloadPaymentDataRequestDto"
                  }
                ]
              }
            }
          },
          "required": true,
          "x-position": 1
        },
        "responses": {
          "200": {
            "description": "",
            "content": {
              "application/json": {
                "schema": {
                  "type": "boolean"
                }
              }
            }
          },
          "500": {
            "description": "",
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/ApiResponseOfListOfApiResponseCode"
                }
              }
            }
          }
        }
      }
    },

It seems that perhaps the example shouldn't be on the components, but instead on the responseBody according to this? https://swagger.io/docs/specification/describing-request-body/

However that seems a bit odd, as it seems you would want it defined just on the component object so any other method that uses it would get the same example.

xantari commented 5 years ago

Figured out what it was!

Added this and all is right with the world now. Apparently when it is nullable, it wants to give you the example of blank / null instead of the example tag.

settings.GeneratorSettings.AllowNullableBodyParameters = false;