Home > Mobile >  How to execute different REST API requests in parallel in C# .NetCore?
How to execute different REST API requests in parallel in C# .NetCore?

Time:01-16

Problem Statement

I need to send multiple API calls at one shot.

I have three different API end points as below and all these need to be called together almost as quickly as possible. It's all independent of each other.

public async Task<string> GetA(string a)
{
}

public async Task<string> GetB(int a)
{
}

public async Task<string> GetC(int a, string a)
{
}

What I tried

I was trying as below

public async Task CallMultipleAPIs()
{
await GetA("");
await GetB(1);
await GetC(1, "");
}

How to implement parallelism here?

CodePudding user response:

What you need is concurrency (not parallelism - i.e., multiple threads).

Concurrent asynchronous code is done by using Task.WhenAll:

public async Task CallMultipleAPIs()
{
  var taskA = GetA("");
  var taskB = GetB(1);
  var taskC = GetC(1, "");
  await Task.WhenAll(taskA, taskB, taskC);
}

CodePudding user response:

I use for test API - Postman. In Pre-requset you can call requests to diferent API. See How to set the request body via Postman's pre-request script?

  •  Tags:  
  • Related