Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Can I get data from web api in .net core with another api or api key?

I wrote a controller. I wrote it according to the web api I will use here. But how should I make my own created api? Do I need to have my own created api where I write with HttpPost? I might be wrong as I am new to this.

public class GoldPriceDetailController : Controller
{
    string Baseurl = "https://apigw.bank.com.tr:8003/";
    public async Task<ActionResult> GetGoldPrice()
    {
        List<GoldPrice> goldPriceList = new List<GoldPrice>();
        using (var client = new HttpClient())
        {
            //Passing service base url  
            client.BaseAddress = new Uri(Baseurl);
            client.DefaultRequestHeaders.Clear();
            client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));

            //Sending request to find web api REST service resource GetDepartments using HttpClient  
            HttpResponseMessage Res = await client.GetAsync("getGoldPrices");
            Console.WriteLine(Res.Content);

            //Checking the response is successful or not which is sent using HttpClient  
            if (Res.IsSuccessStatusCode)
            {
                var ObjResponse = Res.Content.ReadAsStringAsync().Result;
                goldPriceList = JsonConvert.DeserializeObject<List<GoldPrice>>(ObjResponse);
            }

            //returning the student list to view  
            return View(goldPriceList);
        }
    } 
    
     [HttpPost]
     public async Task<IActionResult> GetReservation(int id)
     {
         GoldPrice reservation = new GoldPrice();
         using (var httpClient = new HttpClient())
         {
             using (var response = await httpClient.GetAsync("https://apigw.bank.com.tr:8443/getGoldPrices" + id))
             {
                 if (response.StatusCode == System.Net.HttpStatusCode.OK)
                 {
                     string apiResponse = await response.Content.ReadAsStringAsync();
                     reservation = JsonConvert.DeserializeObject<GoldPrice>(apiResponse);
                 }
                 else
                     ViewBag.StatusCode = response.StatusCode;
             }
         }

         return View(reservation);
    }
}
like image 370
Aysenur Avatar asked Nov 25 '25 07:11

Aysenur


1 Answers

Basically you need these steps:

  • HttpClient for local API.
  • HttpClient for external API.
  • Local API controller.
  • Inject external client into the local API.
  • Then inject the local API client into the razor page/controller.

HttpClient for Local API

public class LocalApiClient : ILocalHttpClient
{
    private readonly HttpClient _client;

    public LocalAPiClient(HttpClient client)
    {
        _client = client;
        _client.BaseAddress(new Uri("https://localapi.com"));
    }

    [HttpGet]
    public async Task<string> GetGoldPrices(int id)
    {
        // logic to get prices from local api
        var response = await _client.GetAsync($"GetGoldPrices?id={id}");

        // deserialize or other logic
    }
}

HttpClient for External API

public class ExternalApiClient : IExternalHttpClient
{
    private readonly HttpClient _client;

    public ExternalAPiClient(HttpClient client)
    {
        _client = client;
        _client.BaseAddress(new Uri("https://externalApi.com"));

        // ...

    }

    [HttpGet]
    public async Task<string> GetGoldPrices(int id)
    {
        // logic to get prices from external api
        var response = await _client.GetAsync("getGoldPrices?id=" + id))

    }
}

Register your clients in startup

services.AddHttpClient<ILocalHttpClient, LocalHttpClient>();
services.AddHttpClient<IExternalHttpClient, ExternalHttpClient>();

Create Local API Controller

and inject the external http client into it

[ApiController]
public class LocalAPIController : Controller
{
    private readonly IExternalHttpClient _externalClient;

    public LocalAPIController(IExternalHttpClient externalClient)
    {
        _externalClient = externalClient;
    }

    [HttpGet]
    public async Task<string> GetGoldPrices(int id)
    {
        var resoponse = await _externalClient.GetGoldPrices(id);
        // ...
    }
}

Inject the local client into razor page/controller

public class HomeController : Controller
{
    private readonly ILocalHttpClient _localClient;

    public HomeController(ILocalHttpClient localClient)
    {
        _localClient = localClient;
    }

    public async Task<IActionResult> Index(int id)
    {
        var response = await _localClient.GetGoldPrices(id);
        // ...
    }
}
like image 119
LazZiya Avatar answered Nov 27 '25 14:11

LazZiya



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!