question-mark
Stuck on an issue?

Lightrun Answers was designed to reduce the constant googling that comes with debugging 3rd party libraries. It collects links to all the places you might be looking at while hunting down a tough bug.

And, if you’re still stuck at the end, we’re happy to hop on a call to see how we can help out.

What's the easiest way to retrieve swagger.json documentation file?

See original GitHub issue

Hello!

I’m trying to understand if it’s possible to generate swagger.json documentation file manually from code? Or I need to run my WebAPI anyway?

If I need to run WebAPI anyway, is it easier just to request swagger endpoint rather than trying to generate this json manually from code?

By manually from code I mean something like this:

var swaggerConfig = new SwaggerDocsConfig();
MyWebApplication.SwaggerConfig.ConfigureSwagger(swaggerConfig);

// to retrieve httpConfig from somewhere
var httpConfig = new HttpConfiguration();

MyWebApplication.WebApiConfig.Register(httpConfig);

var generatorOptions = new SwaggerGeneratorOptions();

var versionInfoBuilder = new VersionInfoBuilder();
versionInfoBuilder.Version("v1", "MyWebApplication");

var defaultProvider = new SwaggerGenerator(
    httpConfig.Services.GetApiExplorer(),
    httpConfig.Formatters.JsonFormatter.SerializerSettings,
    versionInfoBuilder.Build(),
    generatorOptions);

SwaggerDocument swaggerDocument = defaultProvider.GetSwagger("http://localhost", "v1");

string result = JsonConvert.SerializeObject(swaggerDocument);

However, I guess this code still requires my WebAPI to be running? Because HttpConfiguration should be initialized first.

So finally what’s the easiest way to retrieve swagger.json documentation file generated automatically from my WebAPI by Swagger/Swashbuckle?

To run self-hosted WebAPI, configure Swagger/Swashbuckle and request api/swagger/docs/v1?

Thanks, Gordey

Issue Analytics

  • State:closed
  • Created 8 years ago
  • Reactions:1
  • Comments:15 (4 by maintainers)

github_iconTop GitHub Comments

16reactions
fizxmikecommented, Nov 3, 2018

Serously? The answer is 100+ lines of code? This is not maintainable: if this ends up breaking in the future, how would anyone know how to fix it without having to basically grock the entire thing and re-write it? This should have a solution in Swashbuckle project (some simple XML in .csproj to write out .json file to a location at build time).

15reactions
stevenkuhncommented, Nov 11, 2015

If you are using OWIN/Katana with your WebAPI project, then it is possible to generate a swagger.json file from the project without hosting it on an actual port. Instead, you use the In-Memory hosting capabilities supplied by the Microsoft.Owin.Testing nuget package. For more on In-Memory testing, here are a couple of blog posts:

http://www.strathweb.com/2013/12/owin-memory-integration-testing/ http://www.juliencorioland.net/archives/using-owin-to-test-your-web-api-controllers

For example, I have a Startup.cs file with something like the following in my WebAPI project (I’m including Autofac to show how I also handle dependency injection, but you can ignore it if you like):

public class Startup
{
    public void Configuration(IAppBuilder app)
    {
        var config = new HttpConfiguration();
        ConfigureAutofac(app, config);

        config.MapHttpAttributeRoutes();
        config.IncludeErrorDetailPolicy = IncludeErrorDetailPolicy.Always;

        // Configures Swagger using Swashbuckle here. For this example, the
        // API version is "v1"
        SwaggerConfig.Register(config);

        app.UseWebApi(config);
    }

    public virtual IContainer ConfigureAutofac(IAppBuilder app, HttpConfiguration config)
    {
        var builder = new ContainerBuilder();

        builder.RegisterAssemblyModules(typeof(Startup).Assembly);

        var container = builder.Build();

        // Allows the Autofac container to be accessed from the OWIN context.
        app.UseAutofacMiddleware(container);

        // Informs ASP.NET WebApi 2 to use Autofac when resolving dependencies
        // (e.g. dependencies in Controllers).
        config.DependencyResolver = new AutofacWebApiDependencyResolver(container);

        return container;
    }
}

Then I created a new Console project called ProjectName.Api.SwaggerGenerator with a project reference to my WebAPI project and added the Microsoft.Owin.Testing NuGet package. In Program.cs I have the following code:

public class Program
{
    public static void Main(string[] args)
    {
        using (var server = TestServer.Create<ApiStartup>())
        {
            var response = server.CreateRequest("/swagger/docs/v1").GetAsync().Result;
            var content = response.Content.ReadAsStringAsync().Result;
            File.WriteAllText("swagger.json", content);
        }
    }
}

I then run the console app and a file called swagger.json is created with the output of that request. As a side note, the url of /swagger/docs/v1 might vary depending on your Swagger configuration.

With this solution, you don’t need to worry about exposing your WebAPI to the public or a potential port conflict because it is all hosted in memory without requiring a port for listening to incoming requests.

If you are not using OWIN/Katana, then it might still be possible, but you would have the Startup.cs file in the SwaggerGenerator project and not in the WebAPI project. I haven’t tested that though, so I cannot be sure.

Hope that helps! I’ve successfully used this method along with the AutoRest project to generate .NET client code for my WebAPI project every time I build my solution.

Read more comments on GitHub >

github_iconTop Results From Across the Web

API Documentation Made Easy with OpenAPI & Swagger
How to generate OpenAPI from existing APIs. Head over to Swagger Inspector, and insert the end point of the resource you want to...
Read more >
How to generate swagger.json [duplicate]
Navigate to your Swagger docs endpoint; Open the browser console; Refresh the page; Navigate to the network tab and filter by XHR requests ......
Read more >
Generating a Swagger JSON File
json file is generated and displayed in a new tab of the browser. Click the Raw Data tab, and then click Save to...
Read more >
How to generate a swagger.json file on build in .NET core, . ...
You can simply access this file by navigation to your API and adding /swagger.json and the end of the url. Generate the file...
Read more >
Question: How do I get the swagger.json file for an API?
We have Services Enablement and I'm trying to get the swagger file for one of our deployed web services. I've followed the instructions...
Read more >

github_iconTop Related Medium Post

No results found

github_iconTop Related StackOverflow Question

No results found

github_iconTroubleshoot Live Code

Lightrun enables developers to add logs, metrics and snapshots to live code - no restarts or redeploys required.
Start Free

github_iconTop Related Reddit Thread

No results found

github_iconTop Related Hackernoon Post

No results found

github_iconTop Related Tweet

No results found

github_iconTop Related Dev.to Post

No results found

github_iconTop Related Hashnode Post

No results found