Visual Studio Code Swagger



-->

By Christoph Nienaber and Rico Suter

Swagger (OpenAPI) is a language-agnostic specification for describing REST APIs. It allows both computers and humans to understand the capabilities of a REST API without direct access to the source code. Its main goals are to:

Extension for Visual Studio Code - Swagger Viewer lets you preview and validate Swagger 2.0 and OpenAPI files as you type in Visual Studio Code. A Visual Studio Code extension which will bring interactivity into your swagger documents! Ember-swagger-ui: An ember-cli addon for quickly and easily adding swagger-ui to your EmberJS application. Commandcar: cURL on steroids. Invoke any API from the commandline. SwagGen: Swift command line tool for generating client side code from a Swagger spec.

SwaggerCodeGenerator - Generates a single file C# REST API Client using Swagger Codegen CLI v3.0.14. Using /swagger/v1/swagger.json instructs the app to look for the JSON file at the true root of the URL (plus the route prefix, if used). See screenshot below. I now have an updated version of the Swagger file and need to also update the auto-generated client code. How do I do this in Visual Studio? I have not been able to find a way to update the auto-generated code without completely deleting the code.

  • Minimize the amount of work needed to connect decoupled services.
  • Reduce the amount of time needed to accurately document a service.

The two main OpenAPI implementations for .NET are Swashbuckle and NSwag, see:

OpenApi vs. Swagger

The Swagger project was donated to the OpenAPI Initiative in 2015 and has since been referred to as OpenAPI. Both names are used interchangeably. However, 'OpenAPI' refers to the specification. 'Swagger' refers to the family of open-source and commercial products from SmartBear that work with the OpenAPI Specification. Subsequent open-source products, such as OpenAPIGenerator, also fall under the Swagger family name, despite not being released by SmartBear.

In short:

  • OpenAPI is a specification.
  • Swagger is tooling that uses the OpenAPI specification. For example, OpenAPIGenerator and SwaggerUI.

OpenAPI specification (openapi.json)

The OpenAPI specification is a document that describes the capabilities of your API. The document is based on the XML and attribute annotations within the controllers and models. It's the core part of the OpenAPI flow and is used to drive tooling such as SwaggerUI. By default, it's named openapi.json. Here's an example of an OpenAPI specification, reduced for brevity:

Swagger UI

Swagger UI offers a web-based UI that provides information about the service, using the generated OpenAPI specification. Both Swashbuckle and NSwag include an embedded version of Swagger UI, so that it can be hosted in your ASP.NET Core app using a middleware registration call. The web UI looks like this:

Each public action method in your controllers can be tested from the UI. Select a method name to expand the section. Add any necessary parameters, and select Try it out!. Adobe flash mac os.

Note

The Swagger UI version used for the screenshots is version 2. For a version 3 example, see Petstore example.

Next steps

-->

View or download sample code (how to download)

There are three main components to Swashbuckle:

  • Swashbuckle.AspNetCore.Swagger: a Swagger object model and middleware to expose SwaggerDocument objects as JSON endpoints.

  • Swashbuckle.AspNetCore.SwaggerGen: a Swagger generator that builds SwaggerDocument objects directly from your routes, controllers, and models. It's typically combined with the Swagger endpoint middleware to automatically expose Swagger JSON.

  • Swashbuckle.AspNetCore.SwaggerUI: an embedded version of the Swagger UI tool. It interprets Swagger JSON to build a rich, customizable experience for describing the web API functionality. It includes built-in test harnesses for the public methods.

Package installation

Swashbuckle can be added with the following approaches:

  • From the Package Manager Console window:

    • Go to View > Other Windows > Package Manager Console

    • Navigate to the directory in which the TodoApi.csproj file exists

    • Execute the following command:

  • From the Manage NuGet Packages dialog:

    • Right-click the project in Solution Explorer > Manage NuGet Packages
    • Set the Package source to 'nuget.org'
    • Ensure the 'Include prerelease' option is enabled
    • Enter 'Swashbuckle.AspNetCore' in the search box
    • Select the latest 'Swashbuckle.AspNetCore' package from the Browse tab and click Install
  • Right-click the Packages folder in Solution Pad > Add Packages..
  • Set the Add Packages window's Source drop-down to 'nuget.org'
  • Ensure the 'Show pre-release packages' option is enabled
  • Enter 'Swashbuckle.AspNetCore' in the search box
  • Select the latest 'Swashbuckle.AspNetCore' package from the results pane and click Add Package

Run the following command from the Integrated Terminal:

Run the following command:

Add and configure Swagger middleware

Add the Swagger generator to the services collection in the Startup.ConfigureServices method:

In the Startup.Configure method, enable the middleware for serving the generated JSON document and the Swagger UI:

Note

Swashbuckle relies on MVC's Microsoft.AspNetCore.Mvc.ApiExplorer to discover the routes and endpoints. If the project calls AddMvc, routes and endpoints are discovered automatically. When calling AddMvcCore, the AddApiExplorer method must be explicitly called. For more information, see Swashbuckle, ApiExplorer, and Routing.

The preceding UseSwaggerUI method call enables the Static File Middleware. If targeting .NET Framework or .NET Core 1.x, add the Microsoft.AspNetCore.StaticFiles NuGet package to the project.

Launch the app, and navigate to http://localhost:<port>/swagger/v1/swagger.json. The generated document describing the endpoints appears as shown in OpenAPI specification (openapi.json).

The Swagger UI can be found at http://localhost:<port>/swagger. Explore the API via Swagger UI and incorporate it in other programs.

Tip

To serve the Swagger UI at the app's root (http://localhost:<port>/), set the RoutePrefix property to an empty string:

If using directories with IIS or a reverse proxy, set the Swagger endpoint to a relative path using the ./ prefix. For example, ./swagger/v1/swagger.json. Using /swagger/v1/swagger.json instructs the app to look for the JSON file at the true root of the URL (plus the route prefix, if used). For example, use http://localhost:<port>/<route_prefix>/swagger/v1/swagger.json instead of http://localhost:<port>/<virtual_directory>/<route_prefix>/swagger/v1/swagger.json.

Note

By default, Swashbuckle generates and exposes Swagger JSON in version 3.0 of the specification—officially called the OpenAPI Specification. To support backwards compatibility, you can opt into exposing JSON in the 2.0 format instead. This 2.0 format is important for integrations such as Microsoft Power Apps and Microsoft Flow that currently support OpenAPI version 2.0. To opt into the 2.0 format, set the SerializeAsV2 property in Startup.Configure:

Customize and extend

Swagger provides options for documenting the object model and customizing the UI to match your theme.

In the Startup class, add the following namespaces:

API info and description

The configuration action passed to the AddSwaggerGen method adds information such as the author, license, and description:

In the Startup class, import the following namespace to use the OpenApiInfo class:

Using the OpenApiInfo class, modify the information displayed in the UI:

The Swagger UI displays the version's information:

XML comments

XML comments can be enabled with the following approaches:

  • Right-click the project in Solution Explorer and select Edit <project_name>.csproj.
  • Manually add the highlighted lines to the .csproj file:
  • Right-click the project in Solution Explorer and select Properties.
  • Check the XML documentation file box under the Output section of the Build tab.
  • From the Solution Pad, press control and click the project name. Navigate to Tools > Edit File.
  • Manually add the highlighted lines to the .csproj file:
  • Open the Project Options dialog > Build > Compiler
  • Check the Generate xml documentation box under the General Options section

Manually add the highlighted lines to the .csproj file:

Manually add the highlighted lines to the .csproj file:

Enabling XML comments provides debug information for undocumented public types and members. Undocumented types and members are indicated by the warning message. For example, the following message indicates a violation of warning code 1591:

To suppress warnings project-wide, define a semicolon-delimited list of warning codes to ignore in the project file. Appending the warning codes to $(NoWarn); applies the C# default values too.

To suppress warnings only for specific members, enclose the code in #pragma warning preprocessor directives. This approach is useful for code that shouldn't be exposed via the API docs. In the following example, warning code CS1591 is ignored for the entire Program class. Enforcement of the warning code is restored at the close of the class definition. Specify multiple warning codes with a comma-delimited list.

Configure Swagger to use the XML file that's generated with the preceding instructions. For Linux or non-Windows operating systems, file names and paths can be case-sensitive. For example, a TodoApi.XML file is valid on Windows but not CentOS.

In the preceding code, Reflection is used to build an XML file name matching that of the web API project. The AppContext.BaseDirectory property is used to construct a path to the XML file. Some Swagger features (for example, schemata of input parameters or HTTP methods and response codes from the respective attributes) work without the use of an XML documentation file. For most features, namely method summaries and the descriptions of parameters and response codes, the use of an XML file is mandatory.

Adding triple-slash comments to an action enhances the Swagger UI by adding the description to the section header. Add a <summary> element above the Delete action:

The Swagger UI displays the inner text of the preceding code's <summary> element:

The UI is driven by the generated JSON schema:

Add a <remarks> element to the Create action method documentation. It supplements information specified in the <summary> element and provides a more robust Swagger UI. The <remarks> element content can consist of text, JSON, or XML.

Notice the UI enhancements with these additional comments:

Data annotations

Mark the model with attributes, found in the System.ComponentModel.DataAnnotations namespace, to help drive the Swagger UI components.

StudioVisual Studio Code Swagger

Add the [Required] attribute to the Name property of the TodoItem class:

The presence of this attribute changes the UI behavior and alters the underlying JSON schema:

Add the [Produces('application/json')] attribute to the API controller. Its purpose is to declare that the controller's actions support a response content type of application/json:

The Response Content Type drop-down selects this content type as the default for the controller's GET actions:

As the usage of data annotations in the web API increases, the UI and API help pages become more descriptive and useful.

Describe response types

Developers consuming a web API are most concerned with what's returned—specifically response types and error codes (if not standard). The response types and error codes are denoted in the XML comments and data annotations.

Cisco anyconnect mac os x

The Create action returns an HTTP 201 status code on success. An HTTP 400 status code is returned when the posted request body is null. Without proper documentation in the Swagger UI, the consumer lacks knowledge of these expected outcomes. Fix that problem by adding the highlighted lines in the following example:

The Swagger UI now clearly documents the expected HTTP response codes:

In ASP.NET Core 2.2 or later, conventions can be used as an alternative to explicitly decorating individual actions with [ProducesResponseType]. For more information, see Use web API conventions.

To support the [ProducesResponseType] decoration, the Swashbuckle.AspNetCore.Annotations package offers extensions to enable and enrich the response, schema, and parameter metadata.

Customize the UI

Install Swagger In Visual Studio Code

The default UI is both functional and presentable. However, API documentation pages should represent your brand or theme. Branding the Swashbuckle components requires adding the resources to serve static files and building the folder structure to host those files.

Visual studio code swagger code

If targeting .NET Framework or .NET Core 1.x, add the Microsoft.AspNetCore.StaticFiles NuGet package to the project:

Nullsoft winamp download. The preceding NuGet package is already installed if targeting .NET Core 2.x and using the metapackage.

Visual Studio Code Swagger Code

Enable Static File Middleware:

To inject additional CSS stylesheets, add them to the project's wwwroot folder and specify the relative path in the middleware options:

Visual Studio Code Swagger Viewer

Additional resources