Tuesday, 3 May 2016

Swagger based Web API with C# (1/2) : Swashbuckle

This is the first of two blog posts on using Swagger with C#, and gives a step-by-step quick-start for creating a trivial web-API using Swashbuckle open-source package, to get something up and running.

A follow-up blog entry covers client code-generation for a C# client platform.


What's Swagger?

Web-APIs are trending at the moment and everyone wants one.

Swagger is the defacto leading industry standard - at least, for the time being - and is a well-supported markup language for specifying web-APIs.

There are plentiful toolsets out there for generating Swagger markup from web-API code, and generating client code from Swagger markup.


What's Swashbuckle?

Swashbuckle is an open-source toolset for generating Swagger markup from your C# web-API.  You get a documentation portal and test-harness for free, both of which can be accessed by your API users (and their integration tools).


Quick Start Guide


Step 1 - Create a Web API project.

  • Create a new VS2015 project.
  • It should be an ASP.NET Web Application.
  • Choose Empty Project but tick Add folders and core references for Web API.

  • Add a class, SampleController and derive it from ApiController.
  • Add a Get method like the one below.


  • View the Web properties for your project.
  • Paste the Project URL into the Start URL field.
  • Then add api/ followed by your controller name.

  • Run the application and see that the controller Get method works.


Step 2 - Add Swashbuckle

  • Add the Swashbuckle package from Nuget in Visual Studio.

  • Edit the Swagger.Config file created by Nuget in App_Start.
  • Modify the configuration to read as below.
  • Note that we filled in a path for the XML comments file.
 

  • Set the project build properties to create the XML comments file.

  • View the Web properties for your project.
  • Set the Start URL now to be the documentation URL.
 

  • Add a route attribute to your method.
  • Also add some XML method documentation.

  • Run up your project and view the API documentation portal.
  • Click on the text Sample to see the Get method.
  • Note that our XML comment propagated to the portal.

  • Click on the Get method to see its definition.
  • If the method took arguments, they would be displayed here.
  • Click on the Try it out! button to make a call to the API.


Next?

Now you have a basic web-API setup: now you can make the return type more complex, add parameters, add more methods, add more controllers...

Remember to comment the parameters, methods and controllers for a rich, self-documenting API.

There are plenty of code-generators for generating clients in various languages from a Swagger specification.  If you want to create one in C# you could skim my next post, on NSwag.

No comments:

Post a Comment