Advertisements

Web API documentation using Swagger & ASP.NET Core With Visual Studio 2019


Introduction

There are more challenges we are facing for consuming a Web API because it contains  various methods such as GET,POST,PUT,DELETE. All these methods  contain various types of parameters like model,string,int,etc. Exactly we don’t know what property we need to pass in the model parameter and what are the relevant ones. These are the major challenges for a developer and so we need a proper documentation to solve this problem. That’s why we choose Swagger also known as OpenAPI and It  will provide all such benefits like interactive documentation, client SDK generation, and API discoverability. In this article we are explaining a lit bit basic configurations of Swagger in ASP.NET Core application. We can add more additional features on the Web API using swagger for that just read the reference document that we have mentioned in the Reference section.

We have tested the swagger documentation application in the latest VS 2019. So please check the following steps to kick start the initial process of installation.

1) Open Visual Studio 2019 and Click on “Create a new project”


2) Click on ASP.NET Core Web Application


3) Provision your new project and give the appropriate name and the location to be saved.


4) Choose API and Click on the Create button on the right side.


5) Open “Tools -> Nuget Package Manager -> Manage Nuget Packages for Solution…” and click on Browse tab and search “Swashbuckle.AspNetCore” in the search bar and install it.

Model

We are going to create a Employee model for the demo purpose.

namespace SwaggerDocumentation.Model
{
    public class Employee
    {

        public int id { get; set; }
		
		public string Name { get; set; }
		
		public string Adress { get; set; }

		public string Department { get; set; }

    }
}

API Version Separation

In future if we are planning to release multiple versions of API, then, for the better readability purpose we can create a version folder for the API creation. This will help us to differentiate multiple versions in the API side and Swagger documentation. In the following screenshot we have created two folders one is “v1” ( Version 1 ) and another one is “v2” ( Version 2 ). obviously v2 will contain the latest version comparing to v1.

API Controller

We have created “EmployeeController” as the API controller in our application. Here we can see at the route level api path is set as “api/v1/[controller]” because when you hit the swagger it will first check the controller level then what will happen it will take two identical controller name as “Employee”. This will create ambiguous issue in the http request controller level, for that reason we have added two different request path for both versions v1 & v2.

using System.Collections.Generic;
using Microsoft.AspNetCore.Mvc;
using SwaggerDocumentation.Model;

namespace SwaggerDocumentation.Controllers.v1
{
    [Route("api/v1/[controller]")]
    [ApiController]
    public class EmployeeController : ControllerBase
    {
        // GET: api/v1/Employee
        [HttpGet]
        public List<Employee> EmployeesDetails()
        {
            List<Employee> employees = new List<Employee>
            {
               new Employee
               {
                   Name = "Rajeesh",
                   Department = "Development",
                   Adress = "Menoth Parambil"
               },

               new Employee
               {
                   Name = "Arokia",
                   Department = "R/D",
                   Adress = "Trichy Central"
               },

               new Employee
               {
                   Name = "Vijay",
                   Department = "Cloud",
                   Adress = "MP Gowliyar"
               },

            };

            return employees;
        }

        // GET: api/v1/Employee/5
        [HttpGet("{id}", Name = "Get")]
        public Employee EmployeeDetailsInformation(int id)
        {
            List<Employee> employees = new List<Employee>
            {
               new Employee
               {
                   id = 1,
                   Name = "Rajeesh",
                   Department = "Development",
                   Adress = "Menoth Parambil"
               },

               new Employee
               {
                   id = 2,
                   Name = "Arokia",
                   Department = "R/D",
                   Adress = "Trichy Central"
               },

               new Employee
               {
                   id = 3,
                   Name = "Vijay",
                   Department = "Cloud",
                   Adress = "MP Gowliyar"
               },

            };

            return employees.Find(x => x.id == id);
        }

        // POST: api/v1/Employee
        [HttpPost]
        [ApiExplorerSettings(GroupName = "v1")]
        public void Post([FromBody] string value)
        {
        }

        // PUT: api/v1/Employee/5
        [HttpPut("{id}")]
        public void Put(int id, [FromBody] string value)
        {
        }

        // DELETE: api/v1/ApiWithActions/5
        [HttpDelete("{id}")]
        public void Delete(int id)
        {
        }
    }
}

IControllerModelConvention

In the ASP.NET Core MVC we have application model and it will define convention abstractions that provide a simpler way to customize the behavior of the models without overriding the entire model. In simpler way we are modifying our app to follow different conventions from the default MVC behavior. The following method is clearly describing that it will take the last name of the “namespace” and it consider as the group name of the API Version. So in this case we can easily separate out versions when we  maintain multiple version of API’s in the application. The “GroupName”  can be declared as globally and locally, but in multiple API version case we can go with global scenario.

public class ApiExplorerVersionConvention : IControllerModelConvention
    {
        public void Apply(ControllerModel controller)
        {
            var controllerNamespace = controller.ControllerType.Namespace; // e.g. "Controllers.v1"
            var apiVersion = controllerNamespace.Split('.').Last().ToLower();

            controller.ApiExplorer.GroupName = apiVersion;
        }
    }

The following way we can declare group name  locally but in this scenario you need to add the following decorator for each API method .

 // POST: api/v1/Employee
        [HttpPost]
        [ApiExplorerSettings(GroupName = "v1")]
        public void Post([FromBody] string value)
        {
        }

Middleware

We need to inject swagger service in the ASP.NET Core application using the middleware in startup class. Then only we can access the entire swagger service in our application.

ConfigureServices ( Inside the Startup.cs )

ConfigureServices method gets called by the runtime so we can use this method to register the services to the container  in the application. First of all we need to add “ApiExplorerVersionConvention” convention in the MVC service like the following way.

services.AddMvc(x => x.Conventions.Add(new ApiExplorerVersionConvention()));

The following code will register the swagger in our Application. There are many properties we use in the following code like “v1” & “v2” consider as GroupName , Title is displayed as “Swagger Documentation” and “Version 1.0” & “Version 2.0” is the version separation.

// Register the Swagger generator, defining 1 or more Swagger documents
            services.AddSwaggerGen(c =>
            {
                c.SwaggerDoc("v1", new Info { Title = "Swagger Documentation", Version = "Version 1.0" });
                c.SwaggerDoc("v2", new Info { Title = "Swagger Documentation", Version = "Version 2.0" });
            });

Configure ( Inside the Startup.cs )

Configure method gets called by the runtime and use this method to configure the HTTP request pipeline. We are going to enable the generated Swagger as a JSON endpoint in the middleware and it will serve to the request.

app.UseSwagger();

The swagger UI and json endpoint we can mention in the following way.

app.UseSwaggerUI(c =>
            {
                c.SwaggerEndpoint("/swagger/v1/swagger.json", "My API V1");
                c.SwaggerEndpoint("/swagger/v2/swagger.json", "My API V2");
            });

launchSettings.json

In launchSettings.json we can setup swagger as the launch URL. This is not mandatory to give because for the demo purpose we have given launch URL as swagger. Otherwise In middleware we have SwaggerEndpoint  “/swagger/v1/swagger.json” so you can enter in the browser like “http://localhost:44392/api/swagger&#8221;.

{
  "$schema": "http://json.schemastore.org/launchsettings.json",
  "iisSettings": {
    "windowsAuthentication": false, 
    "anonymousAuthentication": true, 
    "iisExpress": {
      "applicationUrl": "http://localhost:62460",
      "sslPort": 44392
    }
  },
  "profiles": {
    "IIS Express": {
      "commandName": "IISExpress",
      "launchBrowser": true,
      "launchUrl": "swagger",
      "environmentVariables": {
        "ASPNETCORE_ENVIRONMENT": "Development"
      }
    },
    "SwaggerDocumentation": {
      "commandName": "Project",
      "launchBrowser": true,
      "launchUrl": "api/values",
      "applicationUrl": "https://localhost:5001;http://localhost:5000",
      "environmentVariables": {
        "ASPNETCORE_ENVIRONMENT": "Development"
      }
    }
  }
}

 

Output

Reference

Summary

From this article we have learned the Web API documentation using Swagger & ASP.NET Core With Visual Studio 2019. I hope this article is useful for all the ASP.NET Web API beginners.

Advertisements

Cognitive Services : Convert Text to Speech in multiple languages using Asp.Net Core & C#


Introduction

In this article, we are going to learn how to convert text to speech in multiple languages using one of the important Cognitive Services API called Microsoft Text to Speech Service API ( One of the API in Speech API ). The Text to Speech (TTS) API of the Speech service converts input text into natural-sounding speech (also called as speech synthesis). It supports text in multiple languages  and gender based voice(male or female)

You can also refer the following articles on Cognitive Service.

Prerequisites

  1. Subscription key ( Azure Portal ) or Trail Subscription Key
  2. Visual Studio 2015 or 2017

Convert Text to Speech API

First, we need to log into the Azure Portal with our Azure credentials. Then we need to create an Azure Speech Service API in the Azure portal.
So please click on the “Create a resource” on the left top menu and search “Speech” in the search bar on the right side window or top of Azure Marketplace.

Now we can see there are few speech related “AI + Machine Learning ” categories listed in the search result.

Click on the “create” button to create Speech Service API.

Provision a Speech Service API ( Text to Speech ) Subscription Key

After clicking the “Create”, It will open another window. There we need to provide the basic information about Speech API.

Name : Name of the Translator Text API ( Eg. TextToSpeechApp ).

Subscription : We can select our Azure subscription for Speech API creation.

Location : We can select  location of resource group. The best thing is we can choose a location closest to our customer.

Pricing tier : Select an appropriate pricing tier for our requirement.

Resource group : We can create a new resource group or choose from an existing one ( We created a new resource group as “SpeechResource” ).

Now click on the “TextToSpeechApp” in dashboard page and it will redirect to the detailed page of TextToSpeechApp ( “Overview” ). Here, we can see the “Keys” ( Subscription key details ) menu in the left side panel. Then click on the “Keys” menu and it will open the Subscription Keys details. We can use any of the subscription keys or regenerate the given key for text to speech conversion using Microsoft Speech Service API.

Authentication

A token ( bearer ) based authentication is required in the Text To Speech conversion using Speech Service API. So we need to create an authentication token using “TextToSpeechApp” subscription keys. The following “endPoint” will help to create an authentication token for Text to speech conversion. The each access token is valid for 10 minutes and after that we need to create a new one for the next process.

https://westus.api.cognitive.microsoft.com/sts/v1.0/issueToken&#8221;

Speech Synthesis Markup Language ( SSML )

The Speech Synthesis Markup Language (SSML) is an XML-based markup language that provides a way to control the pronunciation and rhythm of text-to-speech. More about SSML ..

SSML Format :

<speak version='1.0' xml:lang='en-US'><voice xml:lang='ta-IN' xml:gender='Female' name='Microsoft Server Speech Text to Speech Voice (ta-IN, Valluvar)'>
        நன்றி
</voice></speak>

How to make a request

This is very simple process,  HTTP request is made in POST method. So that means we need to pass secure data in the request body and that will be a plain text or a SSML document. As per the documentation,it is clearly mentioned in most cases that we need to use SSML body as request. The maximum length of the HTTP request body is 1024 characters and the following is the endPoint for our http Post method.

https://westus.tts.speech.microsoft.com/cognitiveservices/v1&#8221;

The following are the HTTP headers required in the request body.

Pic source : https://docs.microsoft.com/en-us/azure/cognitive-services/speech-service/how-to-text-to-speech

Index.html

The following html contains the binding methodology that we have used in our application by using the  latest Tag helpers of ASP.Net Core.

Model

The following model contains the Speech Model information.

using Microsoft.AspNetCore.Mvc.Rendering;
using System.Collections.Generic;
using System.ComponentModel;

namespace TextToSpeechApp.Models
{
    public class SpeechModel
    {
        public string Content { get; set; }

        public string SubscriptionKey { get; set; } = "< Subscription Key >";

        [DisplayName("Language Selection :")]
        public string LanguageCode { get; set; } = "NA";

        public List<SelectListItem> LanguagePreference { get; set; } = new List<SelectListItem>
        {
        new SelectListItem { Value = "NA", Text = "-Select-" },
        new SelectListItem { Value = "en-US", Text = "English (United States)"  },
        new SelectListItem { Value = "en-IN", Text = "English (India)"  },
        new SelectListItem { Value = "ta-IN", Text = "Tamil (India)"  },
        new SelectListItem { Value = "hi-IN", Text = "Hindi (India)"  },
        new SelectListItem { Value = "te-IN", Text = "Telugu (India)"  }
        };
    }
}

Interface

The “ITextToSpeech” contains one signature for converting text to speech based on the given input. So we have injected this interface in the ASP.NET Core “Startup.cs” class as a “AddTransient”.

using System.Threading.Tasks;

namespace TextToSpeechApp.BusinessLayer.Interface
{
    public interface ITextToSpeech
    {
        Task<byte[]> TranslateText(string token, string key, string content, string lang);
    }
}

Text to Speech API Service

We can add the valid Speech API Subscription key and authentication token into the following code.

/// 

<summary>
        /// Translate text to speech
        /// </summary>


        /// <param name="token">Authentication token</param>
        /// <param name="key">Azure subscription key</param>
        /// <param name="content">Text content for speech</param>
        /// <param name="lang">Speech conversion language</param>
        /// <returns></returns>
        public async Task<byte[]> TranslateText(string token, string key, string content, string lang)
        {
            //Request url for the speech api.
            string uri = "https://westus.tts.speech.microsoft.com/cognitiveservices/v1";
            //Generate Speech Synthesis Markup Language (SSML) 
            var requestBody = this.GenerateSsml(lang, "Female", this.ServiceName(lang), content);

            using (var client = new HttpClient())
            using (var request = new HttpRequestMessage())
            {
                request.Method = HttpMethod.Post;
                request.RequestUri = new Uri(uri);
                request.Headers.Add("Ocp-Apim-Subscription-Key", key);
                request.Headers.Authorization = new AuthenticationHeaderValue("Bearer", token);
                request.Headers.Add("X-Microsoft-OutputFormat", "audio-16khz-64kbitrate-mono-mp3");
                request.Content = new StringContent(requestBody, Encoding.UTF8, "text/plain");
                request.Content.Headers.Remove("Content-Type");
                request.Content.Headers.Add("Content-Type", "application/ssml+xml");
                request.Headers.Add("User-Agent", "TexttoSpeech");
                var response = await client.SendAsync(request);
                var httpStream = await response.Content.ReadAsStreamAsync().ConfigureAwait(false);
                Stream receiveStream = httpStream;
                byte[] buffer = new byte[32768];

                using (Stream stream = httpStream)
                {
                    using (MemoryStream ms = new MemoryStream())
                    {
                        byte[] waveBytes = null;
                        int count = 0;
                        do
                        {
                            byte[] buf = new byte[1024];
                            count = stream.Read(buf, 0, 1024);
                            ms.Write(buf, 0, count);
                        } while (stream.CanRead && count > 0);

                        waveBytes = ms.ToArray();

                        return waveBytes;
                    }
                }
            }
        }

Download

Demo

Output

The given text is converted into speech in desired  language listed in a drop-down list using Microsoft Speech API.

Reference

See Also

You can download other source codes from MSDN Code, using the link, mentioned below.

Summary

From this article we have learned how to convert text to speech in multiple languages using Asp.Net Core & C# as per the API documentation using one of the important Cognitive Services API ( Text to Speech API is a part of Speech API ). I hope this article is useful for all Azure Cognitive Services API beginners.

Cognitive Services : Translate Text into multiple languages using Asp.Net Core & C#


Introduction

In this article, we are going to learn how to translate text into multiple languages using one of the important Cognitive Services API called Microsoft Translate Text API ( One of the API in Language API ). It’s a simple cloud-based machine translation service and obviously we can test through simple Rest API call. Microsoft is using a new standard for high-quality AI-powered machine translations known as Neural Machine Translation (NMT).

Pic source : https://www.microsoft.com/en-us/translator/business/machine-translation/#whatmachine

You can also refer the following articles on Cognitive Service.

Prerequisites

  1. Subscription key ( Azure Portal ).
  2. Visual Studio 2015 or 2017

Translator Text API

First, we need to log into the Azure Portal with our Azure credentials. Then we need to create an Azure Translator Text API in the Azure portal. So please click on the “Create a resource” on the left top menu and search “Translator Text” in the search bar on the right side window or top of Azure Marketplace.

Click on the “create” button to create Translator Text API.

Provision a Translator Text Subscription Key

After clicking the “Create”, It will open another window. There we need to provide the basic information about Translator Text API.

Name : Name of the Translator Text API ( Eg. TranslatorTextApp ).

Subscription : We can select our Azure subscription for Translator Text  API creation.

Location : We can select our location of resource group. The best thing is we can choose a location closest to our customer.

Pricing tier : Select an appropriate pricing tier for our requirement.

Resource group : We can create a new resource group or choose from an existing one.

Now click on the “TranslatorTextApp” in dashboard page and it will redirect to the detailed page of  TranslatorTextApp ( “Overview” ). Here, we can see the “Keys” ( Subscription key details ) menu in the left side panel. Then click on the “Keys” menu and it will open the Subscription Keys details. We can use any of the subscription keys or regenerate the given key for text translation using Microsoft Translator Text API.

Language Request URL

The following request url gets the set of languages currently supported by other operations of the Microsoft Translator Text API.

https://api.cognitive.microsofttranslator.com/languages?api-version=3.0

Endpoint

The version of the API requested by the client and the Value must be 3.0 and also we can include query parameters and request header in the following endPoint used in our application.

https://api.cognitive.microsofttranslator.com/translate?api-version=3.0

Mandatory required parameters in the query string are “api-version” and “to” . The “api-version” value must be “3.0” as per the current documentation. “to” is the language code parameter used for translating the entered text into the desired language.

The mandatory request headers are “authorization header” and “Content-Type”. We can pass our subscription key into the “authorization header” and the simplest way is to pass our Azure secret key to the Translator service using request header “Ocp-Apim-Subscription-Key”.

 Index.html

The following html contains the binding methodology that we have used in our application by using the  latest Tag helpers of ASP.Net Core.

site.js

The following ajax call will trigger for each drop-down index change in the language selection using drop-down list.

// Write your JavaScript code.
$(function () {
    $(document)
        .on('change', '#ddlLangCode', function () {
            var languageCode = $(this).val();
            var enterText = $("#enterText").val();
            if (1 <= $("#enterText").val().trim().length && languageCode != "NA") {

                $('#enterText').removeClass('redBorder');

                var url = '/Home/Index';
                var dataToSend = { "LanguageCode": languageCode, "Text": enterText };
                dataType: "json",
                    $.ajax({
                        url: url,
                        data: dataToSend,
                        type: 'POST',
                        success: function (response) {
                            //update control on View
                            var result = JSON.parse(response);
                            var translatedText = result[0].translations[0].text;
                            $('#translatedText').val(translatedText);
                        }
                    })
            }
            else {
                $('#enterText').addClass('redBorder');
                $('#translatedText').val("");
            }
        });
});

Interface

The “ITranslateText” contains one signature for translating text content based on the given input. So we have injected this interface in the ASP.NET Core “Startup.cs” class as a “AddTransient”.

using System.Threading.Tasks;

namespace TranslateTextApp.Business_Layer.Interface
{
    interface ITranslateText
    {
        Task<string> Translate(string uri, string text, string key);
    }
}

Translator Text API Service

We can add the valid Translator Text API Subscription Key into the following code.

using Newtonsoft.Json;
using System;
using System.Net.Http;
using System.Text;
using System.Threading.Tasks;
using TranslateTextApp.Business_Layer.Interface;

namespace TranslateTextApp.Business_Layer
{
    public class TranslateTextService : ITranslateText
    {
        /// 
<summary>
        /// Translate the given text in to selected language.
        /// </summary>

        /// <param name="uri">Request uri</param>
        /// <param name="text">The text is given for translation</param>
        /// <param name="key">Subscription key</param>
        /// <returns></returns>
        public async Task<string> Translate(string uri, string text, string key)
        {
            System.Object[] body = new System.Object[] { new { Text = text } };
            var requestBody = JsonConvert.SerializeObject(body);
            
            using (var client = new HttpClient())
            using (var request = new HttpRequestMessage())
            {
                request.Method = HttpMethod.Post;
                request.RequestUri = new Uri(uri);
                request.Content = new StringContent(requestBody, Encoding.UTF8, "application/json");
                request.Headers.Add("Ocp-Apim-Subscription-Key", key);

                var response = await client.SendAsync(request);
                var responseBody = await response.Content.ReadAsStringAsync();
                dynamic result = JsonConvert.SerializeObject(JsonConvert.DeserializeObject(responseBody), Formatting.Indented);
                
                return result;
            }
        }
    }
}

API Response – Based on the given text

The successful json response.

[
  {
    "detectedLanguage": {
      "language": "en",
      "score": 1.0
    },
    "translations": [
      {
        "text": "सफलता का कोई शार्टकट नहीं होता",
        "to": "hi"
      }
    ]
  }
]

Download

Output

The given text is translated into desired  language listed in a drop-down list using Microsoft Translator API.

 

Reference

See Also

You can download other source codes from MSDN Code, using the link, mentioned below.

Summary

From this article we have learned translate a text(typed in english) in to different languages as per the API documentation using one of the important Cognitive Services API ( Translator Text API is a part of Language API ). I hope this article is useful for all Azure Cognitive Services API beginners.

%d bloggers like this: