Introduction
Developing never stays in one place. New technologies are increasingly emerging to implement better software solutions. If you want to create a multi-functional, clearly-described system now, you should pay attention to APIs. Today we will take a look at the API principles, specifically for RESTful APIs. We will also consider an example of using ready APIs from the RapidAPI marketplace via C# and .NET Core.
What is a RESTful API?
Let’s explain what an API is before everything else. API stands for an application programming interface. In short, it’s a way to create a system with great usability and robustness. This system is based on requests that are dedicated to some exact endpoints. You could understand this principle like a conversation between user and program. The user asks something by a predefined standard, the program returns a feasible and informative response.
The main advantages of this approach can be formulated as follows:
- easy-to-understand – a good API has comprehensive information about every possible request, so developers won’t have too many problems with it;
- server-independence – the receiving side (i.e. server) doesn’t care about states and types of clients. APIs are good for a bigger part of the tools and applications: web/browser apps, mobile projects, desktop systems, etc.
- fast workload – requests are processed rapidly, that’s why final scripts could be very efficient;
- security – best practices of creating the API illustrate this expression. API supports various tools to make good and encrypted interaction services. Bright example: authorization, especially OAuth 2.0.
Now let’s clarify the RESTful part. There are many different concepts, you can explore this topic more here. We will describe and investigate REST API, as it is more widespread and popular right now.
REST stands for representational state transfer – a standard that ensures both feasibility (API will return correct data if the question is correct) and visibility. Data should be ready to use and well-prepared. Of course, there is some wordplay, because you can rest with a REST API – all the ‘dirty’ job is done without your participation. However, this standard has some important required features. If you want to create RESTful API, it should consist of some basic criteria:
- Client-server architecture – areas of responsibility are distributed directly. The client sends requests (questions), the server returns responses (answers). Such architecture allows making independent systems with separate sides of development.
- Statelessness – the server doesn’t need to remember any previous questions. This principle creates an opportunity to reduce data storage sizes and improve security.
- Cacheability – the client, instead of the receiving side, has some useful practices in the temporal data storing. It may be a very strong upgrade of productivity and computing for the system.
- Layered system – step-by-step separation of some different parts in the query->response chain. Each link in the chain only knows about its neighboring parts. This helps make more secure and portable systems. If some part of the interaction is broken, you don’t need to fix all parts.
- Uniform interface – as the client represents a start-point of the API, there must be an endpoint. That’s why, to prevent any misunderstanding, each possible interaction should have a direct and unique alias.
At this stage it is not necessary to take care of RESTful API creation, we will focus on the API calls. Let’s move to a practical example. It will be divided into two parts. First of all, there will be a simple guide on a basic API calling via a C# console application. Secondary, we will implement some sort of web app via ASP.NET Core.
How to call an API in C#
Prerequisites
As the tech stack, it is required to have a .NET package. We will use .NET Core, which is portable, lightweight and supportable for many different OS. On the link above, you could see and install this package. For the installation checking, you could type the next command in the terminal: dotnet
.
The output should look like this:
Usage: dotnet [options] Usage: dotnet [path-to-application] Options: -h|--help Display help. --info Display .NET Core information. --list-sdks Display the installed SDKs. --list-runtimes Display the installed runtimes. path-to-application: The path to an application .dll file to execute.
This command allows us to create different types of applications, install any possible libraries and build our projects. So any further manipulations with the code will be done via dotnet usage.
Now it’s time to do some outside API research!
And there is no better place on the internet, than RapidAPI, if you want to make some API calls. This portal supports a very big amount of different APIs: from enterprise to the custom ‘hello-world!’ interfaces. You don’t need to take care of any storing problems, any API is ready for your queries. Anytime, any day.
Find the search bar and let’s search for ‘microsoft text translation’. In the drop-down box, you can choose our subject today – translation tool from the C# creators. Let’s take a look at the basic view of the API and explain some key features.
First of all, pay attention, that this API is on the Freemium plan. It means, that you need to subscribe to this page if you want to use this API. Don’t worry, on the basic plan, it will be absolutely free. After subscribing, your screen should look something like this:
On the top, we can see a piece of brief information about the API. There are creator credentials, the popularity score, etc. Next line – 4 tabs about different edges of the project.
- Endpoints are the most interesting, so we will explore it further.
- API Details – a short description of the product from the creator.
- Discussions – some trends and issues within the RapidAPI community about the API.
- Pricing – listing of the usage cost.
Now let’s take a look at the Endpoints. Here we can see the conditional division of the screen into three parts.
- Left side – endpoints. Here is the possibility to switch between any created endpoints. Also, you could search for some of them. In this exact case, there are 6 endpoints.
- Translate – basic endpoint. Here we will point languages of translation and actual text. The response should have the translated text.
Speak – returns a wave or mp3 stream of the passed-in text being spoken in the desired language. - Get Translate Supported Languages – obtain a list of language codes representing languages that are supported by the Translation Service.
- Get Speak Supported Languages – retrieves the languages available for speech synthesis.
- Detect Language – use the Detect method to identify the language of a selected piece of text.
- Break sentences – breaks a piece of text into sentences and returns an array containing the lengths in each sentence.
- Translate – basic endpoint. Here we will point languages of translation and actual text. The response should have the translated text.
- Center – detail endpoint view. Here you can see all the required and possible parameters of the query. Take a look at the X-RapidAPI-Host and X-RapidAPI-Key. A former is a unique identifier of the API inside of the RapidAPI hub. Latter is your own unique identifier. This is it, no other registrations or tokens.
- Right side – testing part. Code snippets on any supportable programming language may help with the developing. Also, there are some hints in the installing. But the most interesting thing is testing in the browser. You could make requests right from here, with no discrete scripts.
Choose in the Code snippet part C#->Unirest. And press the button Install SDK.
Here it is, dotnet CLI component. Looks like this is what we are looking for.
Creating a project with all the required libraries
Now open a terminal and paste the next lines:
dotnet new console -o myApp cd myApp
Here we created a new console application. Open myApp folder and look at the directory structure. It should have folders bin and obj, .csproj description file and Program.cs. We will work inside of the last, but not now. Don’t forget about the requests’ library. RapidAPI recommends a very popular library, called Unirest. It has implementations for many programming languages and is also very easy to use. So let’s take a bit of advice and install it for this project.
dotnet add package Unirest-API --version 1.0.7.6
This is it! Now your .csproj file should have the next content:
<Project Sdk="Microsoft.NET.Sdk"> <PropertyGroup> <OutputType>Exe</OutputType> <TargetFramework>netcoreapp3.0</TargetFramework> <RootNamespace>myApp</RootNamespace> </PropertyGroup> <ItemGroup> <PackageReference Include="Unirest-API" Version="1.0.7.6" /> </ItemGroup> </Project>
So, our project is created with all the required libraries. Let’s finally make some code!
Making an API Call
Now our task is to implement Unirest and handle some response from the translation API. First of all, don’t forget to include Unirest via the next line in the using-section (top of the file). Paste next line in the Program.cs:
using unirest_net.http;
Now we can return to the site and take a look at the snippet for the C#. Paste the next lines in the main section of the file:
HttpResponse<string> response = Unirest.get("https://microsoft-azure-translation-v1.p.rapidapi.com/translate?from=en&to=es&text=Hello%2C+world!") .header("X-RapidAPI-Host", "microsoft-azure-translation-v1.p.rapidapi.com") .header("X-RapidAPI-Key", "<YOUR_RAPID_API_KEY>") .header("Accept", "application/json") .asJson<string>(); Console.WriteLine(response.Body.ToString());
This simple code creates a variable, that handles GET request to the translate endpoint. Here we wrote, that we would like to translate “Hello world!” from the English to Spanish. Save changes and run this project via a simple dotnet run command in the terminal.
<string xmlns="http://schemas.microsoft.com/2003/10/Serialization/">¡Hola mundo!</string>
Not so pretty, but the result is correct! Now we know how to say hello in Spanish and that we need to improve response processing.
Process the response and test the other endpoint
As you may notice, this API returns data in the XML format. It is widespread in Microsoft developing, so it’s not a big problem. All we need to do is this magic line in the using section:
using System.Xml;
There are some modules for simpler and faster XML processing. Now add these lines to the code:
XmlDocument doc = new XmlDocument(); doc.LoadXml(response.Body.ToString()); Console.WriteLine(doc.DocumentElement.FirstChild.InnerText);
Here we rewrite the response body string to the XmlDocument object, that can parse and prettify our data. As we have only one single node (with the translation result), we can just take it directly. Run and test the output:
¡Hola mundo!
So now we can make any possible API calls. Let’s test it on some other endpoint. For example, we can get all supported languages. Paste this snippet after previous in the Program.cs:
response = Unirest.get("https://microsoft-azure-translation-v1.p.rapidapi.com/GetLanguagesForTranslate") .header("X-RapidAPI-Host", "microsoft-azure-translation-v1.p.rapidapi.com") .header("X-RapidAPI-Key", "<YOUR_RAPID_API_KEY>") .asJson<string>(); doc.LoadXml(response.Body.ToString()); foreach(XmlNode node in doc.DocumentElement.ChildNodes){ Console.WriteLine(node.InnerText); }
Almost everything is the same, except for the XML processing. As there are many languages, we can just move step-by-step (via for each operator) on each node. Let’s take a look at the running results:
¡Hola mundo! af ar bn bs-Latn bg ca zh-CHS zh-CHT yue hr cs da nl en et fj fil fi fr de el ht he hi mww hu is id it ja sw tlh tlh-Qaak ko lv lt mg ms mt yua no otq fa pl pt ro ru sm sr-Cyrl sr-Latn sk sl es sv ty ta te th to tr uk ur vi cy
After a previously called translation (that part of code should still be in the file), we have had a pretty processed language list. You may be surprised, but we don’t need anything more to do some really interesting application.
Related: Top Translation APIs
Example: web translator
The idea of the application is as follows: we will propose to the potential user a translation form. There will be two drop-down boxes with any possible languages and special text input. Then, we will send this data to the translation endpoint and return the result. What are we waiting for?
Create a new project. It will be the ASP.NET Core application. This is a part of the .NET platform, that allows creating web applications on a C#. It is some sort of lightweight ASP.NET project, which is bigger and more advanced. As right now we need a simple and easy app, .NET Core version will be fitted perfectly.
Now create a new application via the next command line in the CLI:
dotnet new asp_rapid -o asp_rapid --no-https cd asp_rapid
The directory structure is more difficult, that in the console example. If you want some more detailed information about it, visit this page. At this point, we are interested only in 2 files: Index.cshtml and Index.cshtml.cs. Both of them are responsible for the Index view (basic view of the web app). Former is used for the visualization (view), latter – data preparing (controller). As our app is very simple and light, we don’t need models. But they may be required in more advanced projects.
Don’t forget to install Unirest:
dotnet add package Unirest-API --version 1.0.7.6
You can check the success of the installation in the .csproj file.
<Project Sdk="Microsoft.NET.Sdk.Web"> <PropertyGroup> <TargetFramework>netcoreapp3.0</TargetFramework> </PropertyGroup> <ItemGroup> </ItemGroup> <ItemGroup> <PackageReference Include="Unirest-API" Version="1.0.7.6" /> </ItemGroup> </Project>
Now we will modify both files. Let’s start from the Index.cshtml.cs file. Add these familiar lines to the using-section:
using System.Xml; using unirest_net.http;
So right now we can handle signals from the view and prepare data. Replace IndexModel class with the next code:
public class IndexModel : PageModel { private string host = "https://microsoft-azure-translation-v1.p.rapidapi.com/"; private string x_rapid_api_host = "microsoft-azure-translation-v1.p.rapidapi.com"; private string x_rapid_api_key = "<YOUR_RAPID_API_KEY>"; private readonly ILogger<IndexModel> _logger; public IndexModel(ILogger<IndexModel> logger) { _logger = logger; } public void OnGet() { string endpoint = "GetLanguagesForTranslate"; HttpResponse<string> response = Unirest.get(host + endpoint) .header("X-RapidAPI-Host", x_rapid_api_host) .header("X-RapidAPI-Key", x_rapid_api_key) .asJson<string>(); XmlDocument doc = new XmlDocument(); doc.LoadXml(response.Body.ToString()); List<string> languages = new List<string>(); foreach(XmlNode node in doc.DocumentElement.ChildNodes){ languages.Add(node.InnerText); } ViewData["languages"] = languages; } public void OnPost(){ var from = Request.Form["from"]; var to = Request.Form["to"]; var text = Request.Form["text"]; Console.WriteLine("________" + from); string endpoint = "translate"; string fields = "?from=" + from + "&to=" + to + "&text=" + text; HttpResponse<string> response = Unirest.get(host + endpoint + fields) .header("X-RapidAPI-Host", x_rapid_api_host) .header("X-RapidAPI-Key", x_rapid_api_key) .header("Accept", "application/json") .asJson<string>(); XmlDocument doc = new XmlDocument(); doc.LoadXml(response.Body.ToString()); ViewData["translation"] = doc.DocumentElement.FirstChild.InnerText; Console.WriteLine(doc.DocumentElement.FirstChild.InnerText); } }
Class PageModel is a base class for a simple view. Here we implement two basic requests via OnGet() and OnPost() respectively. Pay attention, that each handler works only in case of the correct HTTP method. If there will be a GET request (basic page opening), it should return the translation form. So we need to request all acceptable languages and save them into the ViewData dictionary – special connecting object between view and controller.
But if the request will be a POST (there are some text and languages), it should return translated text. So we need to request the translation and save it to the ViewData.
Now we need to add some handlers inside of the Index.cshtml:
@page @model IndexModel @{ ViewData["Title"] = "Home page"; } <div class="text-center"> <h1>Translator on C#</h1> <p>The time on the server is @DateTime.Now</p> @if (ViewData["translation"] != null){ <h4 style="color:red">@ViewData["translation"]</h4> <form action="/"> <input type="submit" value="Make more translations!" /> </form> } else { <form method="post"> <label>From:</label> <select id="from" name="from"> @foreach (var language in ViewData["languages"] as List<string>) { <option value=@language> @language </option> } </select> <br> <label>To:</label> <select id="to" name="to"> @foreach (var language in ViewData["languages"] as List<string>) { <option value=@language> @language </option> } </select> <br> <input type="text" name="text" placeholder="Input your text here" style="margin: .4rem 0" required="true"/> <br> <input type="submit" value="Translate!"> </form> } </div>
Basically, we have some conditions. If there is some value for the key Translation – it is the translation response. So we just represent it with a red color and ability to create a new conversion. But if there isn’t anything – we just show a translation form. Pay attention to the method parameter of the tag form. Here we point out that the results of the form should be sent by POST method, and (by default) in itself. Take a look at a @ operators – it’s the way to use some C# code inside of the markdown. This is how we add all language options in the drop-down box.
Now let’s test our application. Run it via console and open http://localhost:5000/.
It looks like it’s running. The GET request (when we just visit the page) is good, representation even better. Basic markdown (fonts, header, and footer) are given by default in the project’s code. You could check or change it in the _shared folder. But let’s try some translation. Choose any desired languages and text.
This is ”RapidAPI is the best API hub in the world!” in Italian. Press Make more translations! Button, and it should return to the translation form. If it is, our web translator with the C# + ASP.NET Core + RapidAPI + Microsoft Text Translation is ready!
Conclusion
In this article, you have learned what is the RESTful API and how you could call them via RapidAPI. Also, there were some code snippets about C# API interaction. First, it was a basic console application. But, in the end, we did the web application for a text translation. As you may notice, there is nothing difficult.
RESTful APIs allow making a powerful application faster and easier. Especially if the user doesn’t need to worry about endpoints stability, tokens and code snippets.
Leave a Reply