How to add example value to 200 OK response in ASP.NET Core 6 Web API?

Cenk 956 Reputation points
2023-03-29T07:33:31.9466667+00:00

Hi,

I have an ASP.NET Core 6 Web API, I am using Swagger UI. Is it possible to add an example value to 200 like the one in the 400?

I want to add an example like this;

{
    "referenceId": "732aa76f-6c9c-4598-adaf-775aef8a0f3d",
    "productCode": "000000001585",
    "quantity": 1,
    "productDescription": "2100 ZA",
    "currency": "TRY",
    "unitPrice": 5,
    "totalPrice": 5,
    "purchaseStatusDate": "2023-03-29T09:44:58",
    "coupons": [
        {
            "serial": "778529",
            "pin": "KV33-JRPP-FJYR-4CEP"
        }
    ]
}

Here is SwaggerGen on Program.cs:

builder.Services.AddSwaggerGen(c =>
{
    c.EnableAnnotations();
    c.SwaggerDoc("v1", new OpenApiInfo
    {
        Title = "Palas API", 
        Version = "v1",
        Description = "Online Game Code Transactions",
        Contact = new OpenApiContact
        {
            Name = "Support",
            Email = "destek@destek.com"
            
        }

    });
    // Set the comments path for the Swagger JSON and UI.
    var xmlFile = $"{Assembly.GetExecutingAssembly().GetName().Name}.xml";
    var xmlPath = Path.Combine(AppContext.BaseDirectory, xmlFile);
    c.IncludeXmlComments(xmlPath);
});

Here is the sample code:

/// <summary>
        /// This API endpoint allows you to purchase game codes online.
        /// </summary>
        /// <remarks>
        ///
        /// Here is an example of how to make a purchase request:
        ///
        ///     
        ///     {
        ///       "productCode": "0187209",
        ///       "quantity": 1
        ///     }
        ///
        ///
        /// 
        /// </remarks>
        /// <returns>
        ///
        ///
        /// </returns>
        /// <response code="200">If the purchase is successful, this response will return the Serial, Pin, Quantity, Currency and Price of the purchased game. </response>
        /// <response code="400">This response will be returned if the request is invalid or missing required information.</response>
        /// <response code="401">This response will be returned if the request is not authorized to access this resource.</response>
        /// <response code="418">This response will be returned if the requested game is not available for purchase.</response>
        /// <response code="500">This response will be returned if there is an error in the system that prevents the purchase from being completed.</response>
        [Authorize]
        [HttpPost]
        [ProducesResponseType(StatusCodes.Status200OK)]
        [ProducesResponseType(StatusCodes.Status400BadRequest)]
        [ProducesResponseType(StatusCodes.Status401Unauthorized)]
        [ProducesResponseType(StatusCodes.Status500InternalServerError)]
        [ProducesResponseType(StatusCodes.Status418ImATeapot)]
        [Route("purchase")]
        public async Task<IActionResult> PurchaseGame([FromForm] RequestDto game)
        {
          ...

Ekran görüntüsü 2023-03-29 103041

ASP.NET Core
ASP.NET Core
A set of technologies in the .NET Framework for building web applications and XML web services.
4,188 questions
0 comments No comments
{count} votes

Accepted answer
  1. AgaveJoe 26,136 Reputation points
    2023-03-29T12:36:35.78+00:00

    Working Example below. Click the "Try it out" button -> Execute. My example does not pass any parameters but if your unknown web api action takes parameters then you'll need to populate the parameter values. Swagger provides a JSON template that matches your parameter design.

    The official documentation also has examples.

    ASP.NET Core web API documentation with Swagger / OpenAPI

            [HttpGet]
            [ProducesResponseType(typeof(GameConfirmResponseDto), StatusCodes.Status200OK)]
            public ActionResult<GameConfirmResponseDto> Get()
            {
                string json = "{\r\n    \"referenceId\": \"732aa76f-6c9c-4598-adaf-775aef8a0f3d\",\r\n    \"productCode\": \"000000001585\",\r\n    \"quantity\": 1,\r\n    \"productDescription\": \"2100 ZA\",\r\n    \"currency\": \"TRY\",\r\n    \"unitPrice\": 5,\r\n    \"totalPrice\": 5,\r\n    \"purchaseStatusDate\": \"2023-03-29T09:44:58\",\r\n    \"coupons\": [\r\n        {\r\n            \"serial\": \"778529\",\r\n            \"pin\": \"KV33-JRPP-FJYR-4CEP\"\r\n        }\r\n    ]\r\n}";
                GameConfirmResponseDto dto = JsonSerializer.Deserialize<GameConfirmResponseDto>(json);
                return Ok(dto);
            }
    

    Capture

    Capture

    Capture

    0 comments No comments

1 additional answer

Sort by: Most helpful
  1. Cenk 956 Reputation points
    2023-03-29T08:05:41.8933333+00:00

    I added this to the controller method;

    [ProducesResponseType(typeof(GameConfirmResponseDto),StatusCodes.Status200OK)]

    and added the summary to the response DTO.

    public class GameConfirmResponseDto
        {
            /// <summary>
            /// Unique ID for online game purchase.
            /// </summary>
            /// <example>732aa76f-6c9c-4598-adaf-775aef8a0f3d</example>
            public string referenceId { get; set; }
    
    

    But the example value did not show up on the reference id.

    User's image

    1 person found this answer helpful.