How to automatically generate an OpenAPI documentation from a jsonresult response?

81 Views Asked by At

Swashbuckle can automatically generates API documentation based on code (with details return model)

[HttpGet]
public ActionResult<List<Student>> GetStudents()
{
    return CollegeRepository.Students;
}

API document

Is there any way to make Swashbuckle automatically generates API documentation a JsonResult?

[HttpGet]
public JsonResult GetStudents()
{
    var json = new JsonResult(new
    {
        data = CollegeRepository.Students,
        message = "success"
    });

    json.StatusCode = StatusCodes.Status200OK;

    return json;
}
1

There are 1 best solutions below

3
Anuj Karki On

You could do something similar as below.

public static void SaveSwaggerJson(this IServiceProvider provider)
{
    ISwaggerProvider sw = provider.GetRequiredService<ISwaggerProvider>();
    OpenApiDocument doc = sw.GetSwagger("v1", null, "/");
    string swaggerFile = doc.SerializeAsJson(Microsoft.OpenApi.OpenApiSpecVersion.OpenApi3_0);
    var root = AppDomain.CurrentDomain.BaseDirectory ?? "~";
    string swaggerDir = Path.Combine(root, "swagger");
    if(!Directory.Exists(swaggerDir))
    {
        Directory.CreateDirectory(swaggerDir);
    }
    string fileName = DateTime.Now.ToString("MM_dd_yyyy_hh_mm_ss_") + "swaggerfile.json";
    string filePath = Path.Combine(swaggerDir, fileName);
    File.WriteAllText(filePath, swaggerFile);
}

In this above, I have saved file on the basis of time. You could modify it as per you need.

It use SerializeAsJson function from ISwaggerProvider which returns Json data as you wanted.