Skip to main content

Posts tagged with 'advent'

Swashbuckle is a handy library to easily bring Swagger support to your ASP.NET Core (or ASP.NET) application. It is especially handy when developing an HTTP based API. It creates a form of interactive documentation based on the OpenAPI Specification.

Before diving into Swashbuckle: Merry Christmas! This blog is being posted on December 25th, 2017. It’s the final post of the very first C# Advent Calendar. Please check out the other 24 posts in the series! This event has gone so well, that I’m already planning on doing it again in 2018. Thank you, again, to everyone who participated (whether you are a writer or you’ve just been following along).

The full source code used in this example is available on Github.

ASP.NET Core HTTP API

I’m going to assume some level of familiarity with ASP.NET Core and creating a REST API. Here’s an example of a GET and a POST. These endpoints are reading/writing from a JSON text file (in a way that is probably not thread-safe and definitely not efficient, but it’s fine for this example).

public class ValuesController : Controller
{
    [HttpGet]
    [Route("api/teams")]
    public IActionResult GetTeams()
    {
        var jsonFile = System.IO.File.ReadAllText("jsonFile.json");
        var teams = JsonConvert.DeserializeObject<List<Team>>(jsonFile);
        return Ok(teams);
    }

    [HttpPost]
    [Route("api/team")]
    public IActionResult PostTeam([FromBody]Team team)
    {
        var jsonFile = System.IO.File.ReadAllText("jsonFile.json");
        var teams = JsonConvert.DeserializeObject<List<Team>>(jsonFile);
        teams.Add(team);
        System.IO.File.WriteAllText("jsonFile.json",JsonConvert.SerializeObject(teams));
        return Ok(team);
    }

    // etc...

To try out the GET endpoint, the simplest thing I can do is open a browser and view the results. But to try out the POST endpoint, I need something else. I could install Postman or Fiddler (and you should). Here’s how that would look.

Postman

Postman is great for interacting with endpoints, but Postman alone doesn’t really tell us anything about the endpoint or the system as a whole. This is where Swagger comes in.

Swagger

Swagger is a standard way to provide specifications for endpoints. Usually, that specification is automatically generated and then used to generate an interactive UI.

We could write the Swagger spec out by hand, but fortunately ASP.NET Core provides enough information to generate a spec for us. Look at the PostTeam action above. Just from reading that we know:

  • It expects a POST

  • The URL for it is /api/team

  • There’s a Team class that we can look at to see what kind of body is expected

From that, we could construct a Swagger spec like the following (I used JSON, you can also use YAML).

{
	"swagger": "2.0",
	"info": { "version": "v1", "title": "Sports API" },
	"basePath": "/",
	"paths": {
		"/api/team": {
			"post": {
				"consumes": ["application/json"],
				"parameters": [{
					"name": "team",
					"in": "body",
					"required": false,
					"schema": { "$ref": "#/definitions/Team" }
				}]
			}
		}
	},
	"definitions": {
		"Team": {
			"type": "object",
			"properties": {
				"name": { "type": "string" },
				"stadiumName": { "type": "string" },
				"sport": { "type": "string" }
			}
		}
	}
}

But why on earth would you want to type that out? Let’s bring in a .NET library to do the job. Install Swashbuckle.AspNetCore with NuGet (there’s a different package if you want to do this with ASP.NET).

You’ll need to add a few things to Startup.cs:

In the ConfigureServices method:

services.AddSwaggerGen(c =>
{
    c.SwaggerDoc("v1", new Info { Title = "Sports API", Version = "v1"});
});

In the Configure method:

app.UseSwagger();

Aside: With ASP.NET, NuGet actually does all this setup work for you.

Once you’ve done this, you can open a URL like http://localhost:9119/swagger/v1/swagger.json and see the generated JSON spec.

Swagger spec in JSON

Swagger UI with Swashbuckle

That spec is nice, but it would be even nicer if we could use the spec to generate a UI.

Back in the Configure method, add this:

app.UseSwaggerUI(c =>
{
    c.SwaggerEndpoint("/swagger/v1/swagger.json", "Sports API v1");
});

Now, open your site and go to /swagger:

Swagger UI generated by Swashbuckle

Some cool things to notice:

  • Expand/collapse by clicking the URL of an endpoint (note that you must use Route attributes for Swashbuckle to work with ASP.NET Core).

  • "Try it out!" buttons. You can execute GET/POST right from the browser

  • The "parameter" of the POST method. Not only can you paste in some content, but you get an example value that acts like a template (just click it).

Giving some swagger to your Swagger

Swagger and Swashbuckle have done a lot with just a little bit. It can do even more if we add a little more information in the code.

  • Response: The ProducesResponseType attribute will let Swagger know what the response will look like (this is especially useful if you are using IActionResult and/or an endpoint could return different types in different situations).

  • Comments: If you are using XML comments, you can have these included with the Swagger output.

services.AddSwaggerGen(c =>
{
    c.SwaggerDoc("v1", new Info { Title = "Sports API", Version = "v1" });
    var filePath = Path.Combine(PlatformServices.Default.Application.ApplicationBasePath, "swashbuckle-example.xml");
    c.IncludeXmlComments(filePath);
});

(Also make sure you XML Documentation output for your project enabled)

Here’s an example of a GetTeams method with both XML comments and ProducesResponseType:

/// <summary>
/// Gets all the teams stored in the file
/// </summary>
/// <remarks>Baseball is the best sport</remarks>
/// <response code="200">List returned succesfully</response>
/// <response code="500">Something went wrong</response>
[HttpGet]
[Route("api/teams2")]
[ProducesResponseType(typeof(Team), 200)]
public IActionResult GetTeams2()
{
    var jsonFile = System.IO.File.ReadAllText("jsonFile.json");
    var teams = JsonConvert.DeserializeObject<List<Team>>(jsonFile);
    return Ok(teams);
}
  • Customize your info: there’s more to the Info class than just Title and Version. You can specify a license, contact, etc.

services.AddSwaggerGen(c =>
{
    c.SwaggerDoc("v1", new Info
    {
        Title = "Sports API",
        Version = "v1",
        Description = "An API to list and add sports teams",
        TermsOfService = "This is just an example, not for production!",
        Contact = new Contact
        {
            Name = "Matthew Groves",
            Url = "https://crosscuttingconcerns.com"
        },
        License = new License
        {
            Name = "Apache 2.0",
            Url = "http://www.apache.org/licenses/LICENSE-2.0.html"
        }
    });
    var filePath = Path.Combine(PlatformServices.Default.Application.ApplicationBasePath, "swashbuckle-example.xml");
    c.IncludeXmlComments(filePath);
});

Here’s a screenshot of the UI that has all three of the above enhancements: response type, XML comments, and more customized info.

Swagger with more swagger

Summary

Working on HTTP-based APIs? Bring Swashbuckle and Swagger into your life!

More resources:

Thanks again for reading the 2017 C# Advent!

UPDATE: The calendar is full. You can sign up to be an alternate, in case someone drops out or fails to deliver. I can't give you a date though, so you'd essentially have to have a post ready to go as soon as December 1st. And please, don't let the lack of an advent date keep you from writing that C# blog post! Finally, due to the tremendous response, I will double up the slots next year (from 25 to 50), assuming this advent goes well :)

I heard about the F# Advent Calendar, a traditional that's been carried on since 2010 (2014 in English). I think this is a great idea, and there needs to be one for C# too!

(I asked Sergey Tihon for permission!)

So, I need you to write a C# blog post!

Here are the rules:

  1. Reserve a slot on Twitter (with hash tag #csadvent) or leave a comment on this post. You do not have to announce your topic until the day you reserve.
  2. Prepare a blog post (in English).
  3. Add a link in your blog post that links back to here, so that your readers may find the entire advent.
  4. Publish your blog post on the specified date. Your post must be related to C# in some way, but otherwise the content is completely up to you. I've posted a few ideas below to get your creativity flowing.
  5. Post the link to your post on Twitter with hashtags #csharp and #csadvent

Below are all the slots, and who has claimed each date. I chose to go with 25 total slots (yes I know some advent calendars are 24).

I will do my best to keep this up to date. The slots will be first come first serve. I have already claimed December 25th for myself, since I assume that will be the least desirable date. But I'm happy to swap if you really really want that day.

DateClaimed byBlog Post
Dec 1, 2017 Hilary Weaver-Robb Combining Integration and UI Automation in C#
Dec 2, 2017 Jamie Rees Open Source, 2 years retrospective
Dec 3, 2017 Lucas Lansky Analyzing unit-ness of white-box tests using OpenCover
Dec 4, 2017 Andrei Ignat AOP with Roslyn–part 3–custom code at beginning of each method
Dec 5, 2017 Baskar rao Dsn Quick Actions in Visual Studio 2017
Dec 6, 2017 Bill Sempf Coding for an encrypted service
Dec 7, 2017 Brant Burnett Who says C# interfaces can't have implementations?
Dec 8, 2017 Lee Englestone Creating Alexa Skills with Web-API and hosting on Microsoft Azure
Dec 9, 2017 James Hickey Deck the Halls With Strategy Pattern Implementations in C#: Basic to Advanced
Dec 10, 2017 Carl Layton Using C# dynamic Keyword To Replace Data Transfer Objects
Dec 11, 2017 James Curran An Exercise in Refactoring - Specification Pattern
Dec 12, 2017 Andrew Lock Creating a .NET Standard Roslyn Analyzer in Visual Studio 2017
Dec 13, 2017 Jonathan Danylko 5 More C# Extension Methods for the Stocking! (plus a bonus method for enums)
Dec 14, 2017 Gérald Barré (aka Meziantou) Interpolated strings: advanced usages
Dec 15, 2017 Baskar rao Dsn Using BenchMarkDotNet for Performance BenchMarking
Dec 16, 2017 Chris Bohatka Breaking Down Dependency Injection and Inversion of Control in C# with SimpleInjector
Dec 17, 2017 David Pine C# Special Edition
Dec 18, 2017 Barret Blake Using C# and Azure Cognitive Services Text Analytics to Identify and Relate Text Documents
Dec 19, 2017 Ed Charbeneau 5 .NET Standard Features You Shouldn’t Miss
Dec 20, 2017 Kevin Miller Things you Should do with Strings While You’re Coworkers are on Holiday and No One is Checking the Production Code Branch
Dec 21, 2017 Angus Kinsey What makes C# great?
Dec 22, 2017 Jim Wilcox Unloading the UI Thread in C# on Windows 10 + UWP
Dec 23, 2017 Duane Newman All I want for Christmas is a C# Build System
Dec 24, 2017 Calvin Allen Live Unit Testing in Visual Studio 2017
Dec 25, 2017 Matthew D. Groves Swashbuckle and Swagger with ASP.NET Core

Alternates:

  • Leave a comment or tweet with #csadvent to be put on this list!

Some ideas:

  1. Introduction to [your favorite NuGet package]
  2. X C# Tricks and Tips
  3. JSON (De)serialization
  4. Streams
  5. The newer C# 6 and 7 features
  6. Async/await

Thanks to everyone who is participating! I hope this goes well and it can become an annual tradition.

Matthew D. Groves

About the Author

Matthew D. Groves lives in Central Ohio. He works remotely, loves to code, and is a Microsoft MVP.

Latest Comments

Twitter