Header Ads Widget

Top Picks

6/recent/ticker-posts

REST API in Business Central | NLP Translation API in Business central to translate the word and sentences

Multi-purpose Buttons

Introduction


Hi, in this post I am going to see you how I have used NLP translation API in Business Central to translate a word or sentence. I have planned the below topics to discuss. 

  1. Introduction to REST API
  2. RadipAPI 
  3. Overview
  4. Table in BC 
  5. Page in BC 
  6. Codeunit to configure the API
  7. Demo Video
  8. Key Takeaways


Introduction to REST API


Imagine you're at a pizza restaurant, and you want to order a pizza using the restaurant's website. When you place your order, you're actually using an API!


In this case, the website is the client that sends a request to the server (the pizza restaurant). After processing the request, the server replies to the client with its findings. Here's an example of how this could look in a REST API:


Request


GET /api/pizza/pepperoni HTTP/1.1

 

This is the client's request to the server, asking for a pepperoni pizza. The GET method is used to retrieve data, and the /api/pizza/pepperoni is the endpoint or URL that identifies the specific resource being requested.


Response


HTTP/1.1 200 OK

Content-Type: application/json

{

  "name": "Pepperoni Pizza",

  "toppings": ["pepperoni", "cheese"],

  "price": 10.99

}

This is the server's response to the client's request, indicating that the pizza is available and providing the details of the pizza. The 200 OK status code means the request was successful, and the response is in JSON format.


In summary, a REST API allows clients (like websites or mobile apps) to make requests to a server to retrieve or manipulate data using a specific set of endpoints or URLs. The server then responds to those requests with the requested data or an error message.


REST (Representational State Transfer) is a software architectural style for building web services, and a REST API (Application Programming Interface) is an interface that conforms to the principles of REST.


A REST API uses HTTP requests to interact with data resources over the web. It relies on a client-server model, where the client makes requests and the server provides responses. The communication between the client and server is stateless, meaning that each request contains all the information necessary for the server to understand and fulfill it. This allows for the scalability and reliability of the API.


The key principles of REST include using a uniform interface, separating concerns between client and server, and providing a layered system architecture. The API should be designed to be self-descriptive, using standard HTTP methods such as GET, POST, PUT, DELETE, and PATCH to represent different actions on resources. Resources should be identified using unique URLs, and responses should be in a standard data format such as JSON or XML.


In summary, a REST API is a way of building web services that follow a set of architectural principles to enable communication between client and server over the web.

 

RapidAPI


RapidAPI Hub is a platform that connects developers to a wide range of APIs from various providers. It provides a marketplace for developers to discover, test, and connect to APIs that can be used in their applications. The platform offers a unified interface to interact with different APIs, making it easier to manage and use multiple APIs. RapidAPI Hub provides both free and paid APIs, and developers can choose the API that best suits their needs. It also offers tools for API testing, monitoring, and analytics. In summary, RapidAPI Hub simplifies the process of finding, testing, and connecting to APIs, making it easier for developers to build applications with the functionality they need.


RapidAPI

Overview


  1. Sign up for RapidAPI: Go to the RapidAPI website and create an account by providing your email address and creating a password.
  2. Choose an API: Browse the marketplace to find an API that provides translation services. Once you've found an API you want to use, click on it to see its documentation, pricing, and endpoints.
  3. Subscribe to the API: Before you can start using the API, you need to subscribe to it. Some APIs have a free plan, while others require payment. Choose a subscription plan that fits your needs and budget, and follow the instructions to subscribe to the API.
  4. Create a table in Business Central AL programming: In order to store the original text and translated text, you'll need to create a table in Business Central using AL programming. The table should have fields for the original text and translated text.
  5. Create a page in Business Central AL programming: Once you have your table set up, create a page in Business Central using AL programming that displays the original text and translated text from the table. You can use the Page Designer in Business Central to create the page.
  6. Create a codeunit in AL programming: Finally, create a codeunit in AL programming that will handle the logic for retrieving the original text from the table, sending it to the translation API, and storing the translated text back in the table. Be sure to follow the API's documentation for making API requests and parsing the responses.

In summary, signing up for RapidAPI, choosing a translation API, subscribing to the API, creating a table in Business Central AL programming, creating a page in Business Central AL programming, and creating a codeunit in AL programming are the basic steps involved in using an API to translate text in Business Central.


Sign up for RapidAPI


  1. Go to the RapidAPI website at https://rapidapi.com/
  2. Click the "Join" button situated in the upper right corner of the page.
  3. You should enter your email address and make a secret key.
  4. Click the "Create Account" button.
  5. To validate your email address, you'll receive a confirmation email. Follow the directions in the email to complete the verification process.
  6. Once you've verified your email address, you'll be taken to the RapidAPI dashboard, where you can browse the API marketplace and manage your subscriptions.
  7. Note that some APIs may require additional registration steps or verification of your identity before you can use them. Make sure to check the API's documentation for any additional requirements.

Choose an API


  1. Go to the RapidAPI website at https://rapidapi.com/ and sign in to your account.
  2. Click on the "APIs" tab in the top menu to access the API Marketplace.
  3. Browse the categories or use the search bar to find the API that meets your needs. You can filter by pricing, popularity, and other criteria to help narrow down your search.
  4. Click on an API to see its documentation, pricing, and endpoints.
  5. If you're interested in using the API, click the "Subscribe" button to select a plan and complete the subscription process.
  6. Once you've subscribed to an API, you'll be able to access its endpoints and start making API calls from your application.

Note that some APIs may require additional configuration or authentication steps before you can start using them. Be sure to follow the API's documentation to set up your API keys or other authentication tokens.


Subscribe to the API


Table in BC

Check my code to create a table in BC


table 50107 transalte
{

    DataClassification = ToBeClassified;


    fields
    {
        field(1; OrigText; Text[100])
        {
            Caption = 'Original Text';
            DataClassification = ToBeClassified;
            trigger OnValidate()
            var
                apicall: Codeunit APITranslate;
            begin
                apicall.APICall(OrigText, TranslatedText);
            end;

        }
        field(2; TranslatedText; Text[100])
        {
            Caption = 'Translated Text';
            DataClassification = ToBeClassified;

        }
        field(3; Transcode; Code[2])
        {
            Caption = 'Translated Code';
            DataClassification = ToBeClassified;

        }
    }

    keys
    {
        key(PK; Transcode)
        {
            Clustered = true;
        }
    }

   
}


  • The line "DataClassification = ToBeClassified;" sets the data classification for the entire table to "ToBeClassified", which is a default data classification that indicates the data needs to be classified based on its sensitivity.

  • The "fields" section defines the fields (columns) of the table. There are three fields in this situation:

    1. OrigText: a text field with a maximum length of 100 characters that holds the original text to be translated. It has a "Caption" of "Original Text" and a "DataClassification" of "ToBeClassified". There is also an "OnValidate" trigger that calls a codeunit called "APITranslate" to perform the translation and store the result in the "TranslatedText" field.
    2. TranslatedText: a text field with a maximum length of 100 characters that holds the translated text. It has a "Caption" of "Translated Text" and a "DataClassification" of "ToBeClassified".
    3. Transcode: a code field with a maximum length of 2 characters that holds a code for the language of the translated text. It has a "Caption" of "Translated Code" and a "DataClassification" of "ToBeClassified".

  • The "keys" section defines the primary key for the table, which is a clustered index on the "Transcode" field. 

Page in BC

page 50107 "Translated List"
{
    PageType = List;
    ApplicationArea = All;
    UsageCategory = Administration;
    SourceTable = transalte;
    InsertAllowed = true;
    DeleteAllowed = true;
    ModifyAllowed = true;
    //CardPageId=

    layout
    {
        area(Content)
        {
            group(GroupName)
            {
                field("Code"; Rec.Transcode)
                {
                    Caption = 'Trans Code';
                    ApplicationArea = All;

                }

                field("Original Text"; Rec.OrigText)
                {
                    Caption = 'Original Text';
                    ApplicationArea = All;

                }
                field("Translated Text"; Rec.TranslatedText)
                {
                    Caption = 'Translated Text';
                    ApplicationArea = All;

                }
            }
        }
    }

    actions
    {
        area(Processing)
        {
            action(ActionName)
            {
                ApplicationArea = All;

                trigger OnAction()
                begin

                end;
            }
        }
    }

 }

  • The "PageType" property is set to "List", which means this page displays a list of records.
  • The "ApplicationArea" property is set to "All", which means the page can be used in any application area.
  • The "UsageCategory" property is set to "Administration", which means the page is part of the administration functionality.
  • The "SourceTable" property is set to "transalte", which specifies that this page displays records from the "transalte" table.
  • The "InsertAllowed", "DeleteAllowed", and "ModifyAllowed" properties are set to "true", which means the user can insert, delete, and modify records from this page.
  • The "layout" section defines the layout of the page. In this case, there is one "area" called "Content" that contains one "group" called "GroupName". The group contains three "fields" that display the "Trans Code", "Original Text", and "Translated Text" values from the "transalte" table. The "Caption" property of each field specifies the label that appears next to the field on the page.
  • The "actions" section defines any actions that can be performed on the page. In this case, there is one "area" called "Processing" that contains one "action" called "ActionName". The action is currently empty and does not do anything when triggered.

 

Codeunit to configure the API

codeunit 50107 APITranslate
{
    procedure APICall(Input: Text; var output: Text)
    var
        client: HttpClient;
        responsse: HttpResponseMessage;
        request: HttpRequestMessage;
        url: Text;
        result: Text;
        header: HttpHeaders;
        authenticationkey: Text;
        hoskey: Text;
        outurl: Text;
        jsonobjectt: JsonObject;
        newjsonobject: JsonObject;
        jsontokenn: JsonToken;
        newjsontoken: JsonToken;
        newresult: Text;


    begin
        header := client.DefaultRequestHeaders;
        authenticationkey := '3679e3bed7msh788170dfb20cde6p10bb45jsn5d49fdf5d70d';
        hoskey := 'nlp-translation.p.rapidapi.com';
        header.Add('X-RapidAPI-Key', authenticationkey);
        header.Add('X-RapidAPI-Host', hoskey);
        url := 'https://nlp-translation.p.rapidapi.com/v1/translate/?text=';
        request.SetRequestUri(url + Input + '&' + 'to=es');
        outurl := request.GetRequestUri();
        Message(outurl);
        request.Method('Get');
        client.Send(request, responsse);


        if responsse.IsSuccessStatusCode then begin
            responsse.Content.ReadAs(result);
            jsonobjectt.ReadFrom(result);
            jsonobjectt.Get('translated_text', jsontokenn);
            jsontokenn.WriteTo(newresult);
            newjsonobject.ReadFrom(newresult);
            newjsonobject.Get('es', newjsontoken);
            output := newjsontoken.AsValue().AsText();
        end
        else
            Message('Failed: %1, %2', responsse.HttpStatusCode, responsse.ReasonPhrase);
    end;
}

This is a codeunit with a procedure named "APICall". The procedure is responsible for making an API call to the RapidAPI translation service and obtaining the translated text.


The procedure takes two parameters, an input text to be translated and an output text that will hold the translated text. It creates an instance of the HttpClient class, sets the headers for authentication, and sets the URL for the API endpoint.


The code then creates an instance of the HttpRequestMessage class, sets its method to "Get" and sends the request to the API endpoint using the Send method of the HttpClient class.


If the API call is successful, the translated text is extracted from the JSON response using the Newtonsoft.Json library, and the output parameter is updated with the translated text. If the API call is not successful, an error message is displayed.


Demo Video


You can see the complete instruction here 





Key Takeaways

  • Different software programmes can connect with one another via an API (Application Programming Interface), which is a set of guidelines and protocols.
  • REST (Representational State Transfer) is an architectural style for building web services that use HTTP to make requests and receive responses.
  • RapidAPI is a platform that offers a wide range of APIs that developers can integrate into their software applications.
  • To use RapidAPI, you need to sign up for an account and subscribe to the APIs that you want to use.
  • In the context of translating text using an API, you can create a table in Business Central AL programming to store the original and translated text, a page to display the translated text, and a codeunit to handle the logic of making API calls and updating the table with the translated text.
  • The code for the table (50107 Transalte) defines the fields and keys for storing the original and translated text and includes a trigger that calls a function in the APITranslate codeunit to make an API call and update the table with the translated text.
  • The code for the page (50107 Translated List) defines the layout for displaying the translated text and includes actions for inserting, deleting, and modifying records.
  • The code for the APITranslate codeunit defines a procedure for making an API call to translate text using RapidAPI's NLP Translation API and includes code for handling the response and updating the table with the translated text.


Will see you in the next post.


Take care.


Bye

Post a Comment

0 Comments

Youtube Channel Image
goms tech talks Subscribe To watch more Tech Tutorials
Subscribe