Swagger is a very powerful tool that I highly recommend to integrate into your API projects. It will simplify and speed-up both the development and QA processes. This tutorial is going to demonstrate that. Just keep reading.
For this tutorial I assume that you should have a basic understanding of ASP.NET Core Web API and Xamarin.Forms. If you want to follow this tutorial while checking the source code you are welcome to clone this tutorial’s repo.
In this post we will create a simple ASP.NET Core API with Swagger, we will generate the API consumer code using NSwag and finally we will integrate it to our Xamarin.Forms application.
Let’s start with the API. Add a new ASP.NET Core Web API project:
Now we will take care of our Android emulator and iOS simulator by explicitly setting the API URL (more details can be found in my previous post:
I though that it might be easier to follow this tutorial if we will use a real world example, so I decided that our API will serve a blog. Lets create a model:
Next step is to create a controller to expose few simple endpoints:
- Please note that the code is simplified and in real world you would use a database instead of a static List.
As you see we created 3 API endpoints:
/api/blog/add
- POST method that accepts a new BlogPost/api/blog
- GET method that returns a list of all the BlogPosts/api/blog/id
- GET method that returns a specific BlogPost by id
Last step on the API side is to integrate Swagger. We will have to add a NuGet package `Swashbuckle.AspNetCore\ and add few lines of code in our Startup.cs:
At this point you should be able to navigate to http://localhost:5000/swagger to see the next picture:
Now to the most interesting part of this tutorial. What if I tell you that we don’t have to write a single line of code in order to consume our API? That can be easily achieved using third party libraries like NSwag. Since I am an OSX user I will show how to do it on Mac.
In order to generate the consumer code we need to download a document that describes our blogging API. It can be found on the next url:
http://localhost:5000/swagger/v1/swagger.json
Now lets clone NSwag repo locally and execute the next command:
dotnet dotnet-nswag.dll swagger2csclient /input:swagger.json /classname:BlogService /namespace:BlogReader /output:BlogService.cs
The output of this command will be an auto generated BlogService.cs that will cover all the API endpoints:
In order to use BlogService.cs we will have to add a NuGet package Newtonsoft.Json
and initialize it with a baseUrl:
The consumption is pretty straightforward:
Just keep in mind that this technique might be good for prototypes and POCs. In production you may want to implement your own BlogService, however, autogenerated code can give you a good starting point.
As I mentioned earlier the source code can be found on github.