Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Calling a Web api from another Web api

Is it somehow possible to make a Web api that calls another web api?

I am using the code below to access a web api from my web api, but it never return from the call. If I use the code from a console app, it is working fine.

public void DoStuff(){
    RunAsync().Wait();
}

public static async Task RunAsync(){
using (var client = new HttpClient())
{
    client.BaseAddress = new Uri("http://localhost:53452/");
    client.DefaultRequestHeaders.Accept.Clear();
    client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));

    // HTTP GET
    HttpResponseMessage response = await client.GetAsync("umbraco/api/Member/Get?username=test");
    if (response.IsSuccessStatusCode)
    {
        string user = await response.Content.ReadAsAsync<string>();
    }

}
like image 639
PNR Avatar asked Jun 17 '15 12:06

PNR


People also ask

Can I call an API from another API?

In many cases, the availability of your product depends on a sequence of API calls (to both external and internal APIs). Information retrieved from one API may be a critical input for your subsequent call to a different API. If the first call fails, the second can't return a valid result.

How do you call one Web API from another Web API in net core?

You could use . Net classes like HttpClient, WebClient or WebRequest to call one service from another.

How APIs talk to each other?

APIs communicate through a set of rules that define how computers, applications or machines can talk to each other. The API acts as a middleman between any two machines that want to connect with each other for a specified task.


1 Answers

I also went through the same problem, after much research I discovered that the await operator does not stop the work if the HttpClient returns error 500.
To work around the problem I used Task.Wait().

var response = client.GetAsync ("umbraco/api/Member/Get?username=test");
response.Wait ();

I hope this helps others.

like image 184
Propeus Avatar answered Oct 11 '22 14:10

Propeus