Date:

Share:

How to customize Swagger UI with custom CSS in .NET 7

Related Articles

Get ready, Christmas is coming! 🎅

If you want to add a more festive look to the Swagger UI, it’s just a matter of creating a CSS file and injecting it.

You need to create custom CSS for your Swagger endpointsEspecially if you expose them outside your company: if your company has a Color palette for identificationUsing it on your Swagger pages can make your brand stand out.

In this article, we’ll learn how to inject a CSS file into a Swagger UI created using .NET’s minimal APIs.

How to add Swagger in the .NET Minimal APIs

There are many tutorials on how to add Swagger to your APIs. I also wrote a few where I explained how each configuration affects what you see in the user interface.

This article targets older dotNET versions No minimal APIs. Now everything is easier.

When you create your API project, Visual Studio asks you if you want to Add OpenAPI support (aka Swagger). By adding it, you’ll have everything in place to get started with Swagger.

Your minimal APIs will look like this:

public static void Main(string[] args)
{
    var builder = WebApplication.CreateBuilder(args);

    builder.Services.AddEndpointsApiExplorer();
    builder.Services.AddSwaggerGen();

    var app = builder.Build();

    app.UseSwagger();
    app.UseSwaggerUI();


    app.MapGet("/weatherforecast", (HttpContext httpContext) =>
    {
        
    })
    .WithName("GetWeatherForecast")
    .WithOpenApi();

    app.Run();
}

The key parts are builder.Services.AddEndpointsApiExplorer(), builder.Services.AddSwaggerGen(), app.UseSwagger(), app.UseSwaggerUI() and WithOpenApi(). Do you know these methods do? If so, write a comment below! 📩

Now, if we run our application, we will see a user interface similar to the one below.


This is a basic user interface. Pretty boring, huh? Let’s add some style

Create the CSS file for Swagger themes

All static assets must be stored in the wwwroot folder. It doesn’t exist by default, so you need to create it manually. Click on the API project, add a new folder and name it “wwwroot”. Since this is a special folder, by default Visual Studio will display it with a special icon (it’s a kind of blue world, similar to 🌐).

You can now add all the necessary static folders and resources.

I created a single CSS file under /wwwroot/assets/css/xmas-style.css. Of course, give it whatever you want – as long as it’s inside the wwwroot folder, it’s fine.

My CSS file is pretty minimal:

body {
    background-image: url("../images/snowflakes.webp");
}

div.topbar {
    background-color: #34A65F !important;
}

h2, h3 {
    color: #F5624D !important;
}

.opblock-summary-get > button > span.opblock-summary-method {
    background-color: #235E6F !important;
}

.opblock-summary-post > button > span.opblock-summary-method {
    background-color: #0F8A5F !important;
}

.opblock-summary-delete > button > span.opblock-summary-method {
    background-color: #CC231E !important;
}

Pay attention to 3 main things:

  1. The element selectors are taken directly from the Swagger UI – you’ll need some reverse engineering skills: just open the browser terminal and find the elements you want to update;
  2. Unless the component already has the rule you want to apply, you must add the !important CSS operator. Otherwise, your code will not affect the user interface;
  3. You can add assets from other folders: I added background-image: url("../images/snowflakes.webp"); goddess body style. This image is, as you can imagine, under the wwwroot folder we created earlier.

Just to summarize, here is my project structure:


Static property files

Of course, that’s not enough: we need to tell Swagger to consider this file

How to insert CSS file in Swagger UI

This part is pretty simple: you need to update the UseSwaggerUI Command in the Main method:

app.UseSwaggerUI(c =>
+   c.InjectStylesheet("/assets/css/xmas-style.css")
);

Notice how this path begins: no wwwrootNo ~No .. It starts with /assets.

Last step: we need to tell dotNET to consider static files when building and running the application.

You just need to add UseStaticFiles()

to another builder.Build():

var app = builder.Build();
+ app.UseStaticFiles();

app.UseSwagger();
app.UseSwaggerUI(c =>
    c.InjectStylesheet("/assets/css/xmas-style.css")
);

Now we can run our APIs to admire our wonderful Christmas style interface 🎅


Christmas style Swagger UI

Additional readings

This article is part of the 2022 .NET Advent, created by Dustin Morris 🐤:

🔗 C# Advent Calendar 2022

CSS isn’t the only part you can customize, there’s a lot more. Here’s an article I wrote about incorporating Swagger into .NET Core 3 APIs, but it’s still relevant (I hope! 😁)

🔗 Understanding Swagger Integration in .NET Core | Code4IT

This article first appeared on Code4IT

finishing

Themes are often not considered an important part of API development. This is generally true: why should I bother adding some fancy colors to APIs that aren’t likely to have a UI?

This makes sense if you are working on private APIs. In fact, theme design is often useful for improvement brand recognition For public-facing APIs.

You should also consider using theme design when Deploying APIs to different environments: Maybe blue for development, yellow for directing and green for production. This way your developers can easily understand what environment they are exploring.

Happy coding! 🐧

.

Source

Popular Articles