Skip to content Skip to main navigation Skip to footer

3. Example C#

I will use the two methods, getToken and getCompanies to demonstrate how a C# program can be used to access UBIDOGY with API’s.

The code below will write Bearer to console application and it will return a jsonobject with company information:

    using System;
using System.Net.Http;
using System.Net.Http.Headers;
using System.Text;
using System.Text.Json;
using System.Threading.Tasks;

namespace UbidogyApp
{
class Program
{
private static readonly HttpClient client = new HttpClient();

static async Task Main(string[] args)
    {
        string tokenUrl = "https://api.ubidogy.com/api/getToken";
        string companiesUrl = "https://api.ubidogy.com/api/v1/Company/GetCompanies";

        var tokenRequestBody = new
        {
            username = "<YOUR USERNAME>",
            apiKey = "<YOUR API KEY>"
        };

        try
        {
            // Get the token
            string token = await GetBearerTokenAsync(tokenUrl, tokenRequestBody);
            Console.WriteLine("Token retrieved: " + token);

            // Get the companies
            var companies = await GetCompaniesAsync(companiesUrl, token);
            Console.WriteLine("Companies retrieved: " + companies);
        }
        catch (Exception ex)
        {
            Console.WriteLine("An error occurred: " + ex.Message);
        }
    }

    private static async Task<string> GetBearerTokenAsync(string url, object requestBody)
    {
        var jsonContent = new StringContent(JsonSerializer.Serialize(requestBody), Encoding.UTF8, "application/json");
        var response = await client.PostAsync(url, jsonContent);

        response.EnsureSuccessStatusCode();

        var responseContent = await response.Content.ReadAsStringAsync();
        var jsonDocument = JsonDocument.Parse(responseContent);
        var token = jsonDocument.RootElement.GetProperty("token").GetString();

        return token;
    }

    private static async Task<string> GetCompaniesAsync(string url, string token)
    {
        client.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Bearer", token);

        var response = await client.GetAsync(url);

        response.EnsureSuccessStatusCode();

        var responseContent = await response.Content.ReadAsStringAsync();
        return responseContent;
    }
}
}

Was This Article Helpful?

0
0 Comments

There are no comments yet

Leave a comment

Your email address will not be published. Required fields are marked *