ASP Net Rest API – Swagger

Now let’s focus on how we can set up communication between client and server.

To begin we as so often start with the basic Blazor Webassembly template, but this time ignore the Frontend part.

dotnet new blazorwasm -o tryout_blazor_api --hosted

As well as changing the ports to run on to 8443 for SSL and 8080 for pure HTTP.

"applicationUrl": "https://localhost:8443;http://localhost:8080",
"applicationUrl": "https://localhost:8443;http://localhost:8080",

The resulting code should be like: https://github.com/sukapx/tryout_blazor_api/tree/76fed6f2e3fe1c963aa3bb8c8ff68528e8139a6d

Swagger

For now, if we wanted to know, what API calls we support, we’d need to look through the code and by eye find all controllers defining some endpoints. For testing we’d need to write our own console scripts or use Unittests directly. (where the Unittests would actually keep us on the track of TDD 😉 )

But there is help in form of Swagger. Swagger automaticly searches through the codebase and creates a page that lists our API and it also allows easy fiddling with our API.

Adding Swagger

To add Swagger, open a console in Server Project directory and add necessary packages.

cd Server
dotnet add package Swashbuckle.AspNetCore.Swagger
dotnet add package Swashbuckle.AspNetCore.SwaggerGen
dotnet add package Swashbuckle.AspNetCore.SwaggerUI

To load Swagger into application, Program.cs of Server project is extended by

@@ -1,18 +1,28 @@
using Microsoft.AspNetCore.ResponseCompression;
using Microsoft.OpenApi.Models;

var builder = WebApplication.CreateBuilder(args);

// Add services to the container.

builder.Services.AddControllersWithViews();
builder.Services.AddRazorPages();

+ builder.Services.AddSwaggerGen(c =>
+    {
+        c.SwaggerDoc("v1", new OpenApiInfo { Title = "My API", Version = "v1" });                
+    });
var app = builder.Build();

// Configure the HTTP request pipeline.
if (app.Environment.IsDevelopment())
{
    app.UseWebAssemblyDebugging();

    app.UseSwagger();
+    app.UseSwaggerUI(c =>
+    {
+        c.SwaggerEndpoint("/swagger/v1/swagger.json", "My API V1");
+    });
}
else
{

When running the App and navigating to /swagger now, the Swagger API Overview is shown

Thanks to the Blazor Wasm template a simple API is already existing.
By clicking on the API endpoint, we get more information about it, an example return and the possibility to “Try it out”

A way better and deeper how to is created by CodeMaze:
https://code-maze.com/swagger-ui-asp-net-core-web-api/

Leave a Reply

Your email address will not be published. Required fields are marked *