Integration with WEB API

Hello, I’d like to know, how can I use the method GET to receive of an URL API and move the values for my tags.

Do you have any example of script showing how can I do this?

Thank you.

Hi Lucas,

Follow an example demonstrating how to get data from a URL API and assign it to a specific tag.

To do that, you can use the following code as a starting point, changing the and for your case:

using System.Net;

public void GetPrice() {
    string apiUrl = "<url>";

    using (WebClient client = new WebClient())
    {
        try
        {
            string responseData = client.DownloadString(apiUrl);
            
            Dictionary<string, object> dados = ParseJsonString(responseData);
            
            @Tag.price = Convert.ToDouble(dados["<key>"]);
        }
        catch (WebException ex)
        {
            Console.WriteLine("Erro: " + ex.Message);
        }
    }
}

Define the ParseJsonString function as the following to create a dictionary with the data of the string received from URL.

static Dictionary<string, object> ParseJsonString(string jsonString)
{
    Dictionary<string, object> result = new Dictionary<string, object>();
    jsonString = jsonString.Replace(" ", "").Replace("\r", "").Replace("\n", "").Replace("\t", "");
    
    if (jsonString.StartsWith("{") && jsonString.EndsWith("}"))
    {
        jsonString = jsonString.Substring(1, jsonString.Length - 2);
    }

    string[] pairs = jsonString.Split(',');
    foreach (var pair in pairs)
    {
        string[] parts = pair.Split(':');

        if (parts.Length == 2)
        {
            string key = parts[0].Trim('"');
            string value = parts[1].Trim('"');
            
            int integerValue;
            bool parsedSuccessfully = int.TryParse(value, out integerValue);

            if (parsedSuccessfully)
            {
                result[key] = integerValue;
            }
            else
            {
                result[key] = value;
            }
        }
    }

    return result;
}

Follow the link to the project example created for this demonstration: WEB API.tproj

These functions have been defined within the WEBAPI class, accessible through “Edit > Scripts > Classes”.

Hope it helps.

Bests,
Tatsoft Team.