swashbuckleredoc

How to add x-code-samples for ReDoc with Swashbuckle.AspNetCore?


What's the best way to add x-code-samples for ReDoc to swagger.json through Swashbuckle.AspNetCore.Annotations?

EDIT (March 30, 2019)

I hope this is a better explanation. There is a way in Swashbuckle.AspNetCore to add content to the generated swagger.json.

What's documented (Example from GitHub-Page):

[HttpPost]

[SwaggerOperation(
    Summary = "Creates a new product",
    Description = "Requires admin privileges",
    OperationId = "CreateProduct",
    Tags = new[] { "Purchase", "Products" }
)]
public IActionResult Create([FromBody]Product product)

About what I try to achieve

What I'd like to do is something like this:

[MyCustomSwaggerOperation(
    x-code-samples = [
        {
          "lang": "CSharp", 
          "source": "console.log('Hello World');"
        }, 
        {
          "lang": "php",
          "source": ...
        }
    ]
)]
public IActionResult Create([FromBody]Product product)

Solution

  • Here is an IDocumentFilter that injects "x-code-samples" to a parameter

    public class InjectSamples : IDocumentFilter
    {
        public void Apply(SwaggerDocument swaggerDoc, DocumentFilterContext context)
        {
            PathItem path = swaggerDoc.Paths.Where(x => x.Key.Contains("Values")).First().Value;
            path.Post.Parameters.FirstOrDefault().Extensions.Add("x-code-samples", "123456");
        }
    }
    

    Yes you could complicate all this with annotations, but "x-code-samples" is not supported out of the box by Swashbuckle, so you will have to create your own and them use it on the iDocFilter.

    In the comments you kept pointing out that IDocumentFilters are added after the swagger document has been generated, Yes we want that!

    And the generated swagger.json with that looks like this:

    "post": {
        "tags": [ "Values" ],
        "operationId": "ApiValuesPost",
        "consumes": [ "application/json" ],
        "produces": [],
        "parameters": [
            {
                "name": "value",
                "in": "body",
                "required": false,
                "schema": { "type": "string" },
                "x-code-samples": "123456"
            }
        ],
        "responses": {
            "200": { "description": "Success" }
        }
    }