Monday, 9 July 2018

MICROSOFT AZURE + SWAGGER: THE STEP BY STEP GUIDE

Microsoft has transitioned from Azure Mobile Services to Azure Mobile Apps. While Azure Mobile Apps offer a wide range of new features, they miss a really useful one. Azure Mobile Services offered a demo client to test your APIs and unfortunately, Azure Mobile Apps don’t offer this feature out of the box. To replace this feature, you can add Swaggerto your Azure Mobile App and here are the instructions step by step on how to do it.
Swagger is an open-source framework that helps you test your RESTful Windows Azure APIs without writing complex C# scripts. So, if you are developing an Azure-based REST service, Swagger is here to help you speed the development and testing process.

The default Azure Mobile Services test client (the old way)

Login to the Azure Portal and launch your mobile service using your favorite browser.
Mobile Services Try It Out
Click “Try it out” and you should see a list of the APIs you implemented:
List Of Apis
You can click any API to test it. For example, click on “GET tables/ToDoItem” and then “try this out”.
Api Information
You can click “Send” to send the request to your service:
Send Request
Since it requires authentication, you’ll get a “401/Unauthorized” response.
Unauthorized Response

Adding Swagger to your Azure Mobile App

First, open your Azure Mobile App project using Visual Studio.
Visual Studio Start Screen
Right click on the project and select “Manage NuGet Packages”.
Manage Nuget Packages
Search for “Swashbuckle” under nuget.org and click “Install”.
Search NuGet for Swashbuckle
A “Preview” windows will pop up to let you know which packages will be installed. Click “OK” to continue with the installation.
Preview Popup for Swashbuckle Installation
A “License Acceptance” will pop up to inform you about terms and conditions. Click “View License” to read the terms and then click “I Accept”.
License Acceptance for Swashbuckle
Check the Output from Package Manager to make sure that Swashbuckle was successfully installed.
Successful Installation of Swashbuckle
Right click the project and add a new folder.
Visual Studio Add Folder
Name the new folder “Swagger“.
Visual Studio Rename Folder
Right click the “Swagger” folder and add a new C# class.
Visual Studio Add New Class
Name the new class “SwaggerHeaderParameters.cs“.
Visual Studio Name Class
The new class should look like this:
Visual Studio New Empty Class
Change SwaggerHeaderParameters to implement interface IOperationFilter and import “Swashbuckle.Swagger.IOperationFilter”.
public class SwaggerHeaderParameters : IOperationFilter
Then, add the string properties “Description”, “Key”, “Name” and “DefaultValue”.
public string Description { get; set; }
public string Key { get; set; }
public string Name { get; set; }
public string DefaultValue { get; set; }
Add the void method “Apply” with parameter of type SwaggerDocsConfig and import “Swashbuckle.Application.SwaggerDocsConfig”. Then add “Description”, “Key”, “Name” in config header and set this as OperationFilter.
public void Apply(SwaggerDocsConfig c)
{
      c.ApiKey(Key).Name(Name).Description(Description).In("header");
      c.OperationFilter(() => this);
}
Implement the Apply method declared at the IOperationFilter interface and import “System.Web.Http.ApiDescription”. Add operation parameters for the header, as shown below.
public void Apply(Operation operation, SchemaRegistry registry, ApiDescription description)
{
      operation.parameters = operation.parameters ?? new List<Parameter>();
      operation.parameters.Add(new Parameter
      {
           name = Name,
           description = Description,
           @in = "header",
           required = true,
           type = "string",
           @default = DefaultValue
      });
}
Opening folder “App_Start”, you will notice that a class named “SwaggerConfig.cs” was automatically created. We will include Swagger Configuration in “Startup.MobileApp.cs”, so right click on “SwaggerConfig.cs” and click “Delete”.
Delete Auto-created Config
Then, click “OK” at the informational popup window.
delete-popup
If you want to add XML documentation to your project, right click the project and open its Properties. Select the “Build” tab and check “XML documentation file”.
Project Properties Add XML
Open “Startup.MobileApp.cs” (in the “App_Start” folder) and after
Database.SetInitializer(new MobileServiceInitializer());
…add the swagger header for Azure Mobile Apps and import “TodoSwagger.Swagger.SwaggerHeaderParameters”:
// Swagger
var zumoApiHeader = new SwaggerHeaderParameters
{
     Description = "The default header for app services defining their version",
     Key = "ZUMO-API-VERSION",
     Name = "ZUMO-API-VERSION",
     DefaultValue = "2.0.0"
};
In case you added authorization to any of your controllers, add also the authorization header below.
// If your controller has the [Authorize] attribute...
var authHeader = new SwaggerHeaderParameters
{
     Description = "The authorization header",
     Key = "x-zumo-auth",
     Name = "x-zumo-auth",
     DefaultValue = "the authentication token needed"
};
Then, set your base path to the app’s base directory. Enable Swagger and import “Swashbuckle.Application.HttpConfigurationExtentions.EnableSwagger”.
If you don’t have controllers with the [Authorize] attribute, don’t add the “authHeader.Apply(x)”. Same for “IncludeXmlComments”, if you didn’t check the “XML documentation file” option.
var basePath = AppDomain.CurrentDomain.BaseDirectory;
config.EnableSwagger(x =>
{
   x.SingleApiVersion("v1", "ToDoSwagger");
   zumoApiHeader.Apply(x);
   authHeader.Apply(x);
   x.IncludeXmlComments(basePath + "\\bin\\ToDoSwagger.XML");
}).EnableSwaggerUi();
Save your changes and rebuild the solution.
Rebuild Solution
If there are no errors, run the project and you should see something similar to the picture below:
Run Mobile App Locally
Add “/swagger” to the url of your running project and hit Enter.
Mobile App With Swagger
Now, you should see the list of your APIs. By default, Swagger creates your api path both under “/tables” and under “/api”. Your table controllers should be accessible under the “/tables” path and your API controllers under the “/api” path. In any other case, you get a “404-not found” error.
Swagger List Apis
To try it, click “GET /tables/TodoItem” and then “Try it out!”.
You don’t need to add an authentication token in “x-zumo-auth” since “TodoItemController.cs” doesn’t have the [Authorize] attribute.
Swagger Get Api

Response Message properties

The following data are included in the response message. This is incredibly useful when testing and debugging your code!

CURL COMMAND

Swagger Curl

REQUEST URL

Swagger Request Url

RESPONSE BODY

Swagger Response Body

RESPONSE CODE

Swagger Response Code

RESPONSE HEADERS

Swagger Response Headers
After that, all you have to do is publish your Azure Mobile App and add “/swagger” to the published url. Your test web client is up and running!

Important notice

If you checked the “XML documentation file” under the project Properties, be sure that you check it also when in “Release” Solution Configuration. Otherwise, when you publish your Azure Mobile App and add “/swagger”, you will get a “500 -internal server error”.

Summary

In this guide, you’ve learnt how to add a Swagger to your Azure Mobile App. To recap, here are the steps you need to follow:
  1. Add Swashbuckle package to your project
  2. Create SwaggerHeaderParameters.cs
  3. Delete automatically created SwaggerConfig.cs
  4. Enable Swagger in your Startup.MobileApp.cs
  5. Publish your Azure Mobile App
Enjoy your Cloud adventures!

No comments:

Post a Comment