OpenAPISpec + Productivity
- 2 minsIntroduction
This blog talks about how to use Swashbuckle to enable using swagger.json creation and swagger UI creation in .NET Core 3.1 services. NOTE:
- OpenAPISpec/Swagger can be used interchangibly, though OpenAPISpec is preferred.
OpenAPI Specification
- In 2015, under the OpenAPI Initiative, OpenAPI Specification was donated to Linux Foundation
- With this specification, a RESTful interface for the developed APIs is created which can be easily consumed. This is created by effectively mapping resources and operations.
Benefits of adding swagger/OpenApiSpecs
- With several tools created to enable swagger creation at development time, this becomes a visual representation of the API development and progress.
- One can have a look at the swagger/openAPISpecs file which is created and have a clear understanding on what’s the API structure looks like. This is highly beneficial when collaborating with remote teams wtc., where a frequent review is needed.
- Once the swagger files are created and are validated to be free from invalid syntaxes, this can be used in client generation and eventually create powerful SDKs on top of it across several languages (C#, Python, Java, TypeScript, Go, Ruby and even Powershell) using several tools like
Working demo:
- Repo that contains swagger file creation and UI enabled in a .NET Core 3.1 service - Refer
- Clone the repo.
- Run
dotnet build SwaggerDummy.csproj
Steps:
- Install
Swashbuckle.AspNetCore
(use > 5.0.0 since it supports OpenApi) - In
Startup.cs
enable swagger by adding following inConfigureServices
services.AddSwaggerGen(setupAction => { setupAction.SwaggerDoc("<PathToHostSwagger>", new Microsoft.OpenApi.Models.OpenApiInfo { Title = "Your preferred title.", Version = "1.0", }); });
- In
Startup.cs
also add following toConfigure
afterapp.UseHttpsRedirection()
app.UseSwagger(c => { c.SerializeAsV2 = true; // Can use when intention is to create OpenAPISpec 2.0 });
- With above code, you are enabling swagger file creation for your service and to be hosted at ‘
/swagger/ /swagger.json`. - The title and version is that for the swagger file that would be created.
- Enable Swagger UI by adding following in
Configure
function after the above added snippet.app.UseSwaggerUI(setupAction=> { setupAction.SwaggerEndpoint("/swagger/"<PathToHostSwagger>/swagger.json", "<DfinitionName>"); });
- Note: the SwaggerEndpoint defined above is same where the swagger.json file got hosted on creation i.e.,
/swagger/"<PathToHostSwagger>/swagger.json
- The UI looks like