Tuesday, 3 May 2016

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

This is the second of two blog posts on using Swagger with C#, and gives a step-by-step guide to quickly creating a C# web-client from a web-API using the Swashbuckle open-source package.

The previous blog entry covered setting up a trivial web-API in C#.



What's NSwag?

NSwag is an open-source toolset for turning Swagger markup into a C# client for a web-API, curated and developed by Rico Suter, who is very responsive on any issues.

NSwag Studio is a component of the toolset which provides a straightforward user-interface to the the client creation process.  The application has an installer for Windows (or a zip if you prefer) and can notify you on start-up if there is a newer version. The latter is very useful because the NSwag project is active and enhancements and fixes are released as soon as they are coded and tested.



Let's Make a Client.

We're going to make a quick client application to call an existing web-API. If you haven't a simple web-API to practice against, you can make yourself one following the previous blog entry.


Step 1 - Install NSwag.

  • Visit the NSwag Studio page.
  • Download and run the MSI to install the application.
  • Then run it.


Step 2 - Get the Specification.

  • On the input pane (left), choose the Swagger Specification tab.
    • I like this best, as it's application-neutral.
  • Find the URL for your specification and paste it into the input box.
    • For the example it is <your-site>/swagger/docs/v1
  • If you only have the Swagger text, paste it into the JSON area.
  • Click Load.




Step 3 - Generate the Client Code.

  • On the output pane (right), choose the CSharp Client tab.
  • Choose a namespace.
  • Tick Generate Client Classes.
  • Tick Generate Client Interfaces.
  • Click Generate Outputs.



Step 4 - Integrate.

  • Copy the code from the bottom box on the right-hand pane.
  • Create a simple application (I made a Windows form with one button).
  • Paste the copied code into a file like SampleWebApi.Generated.cs.
    • Ending in .Generate.cs suppresses Resharper whinges.
  • Call the client from your code (example below).




No comments:

Post a Comment