Search code examples
azureazure-api-appsazure-function-app

How to call two rest APIs in a Azure Function?


I'm trying to call two rest APIs (Azure Web Service APIs) in a Azure Function. I have written the below code but When I try to run it, the first API is only getting executed but the second one isn't. The Logic should be like if the first API gets a response status as 200 Ok then only, it should proceed to call the next API.

namespace FunctionChainingApp
{
    public static class FunctionChaining
    {

        [FunctionName("FunctionChaining")]
        public static async Task<HttpResponseMessage> Run([HttpTrigger(AuthorizationLevel.Anonymous, "get", "post", Route = null)]HttpRequestMessage req, ILogger log)
        {
            log.LogInformation("C# HTTP trigger function processed a request.");


            try
            {
                // Call Your  API
                HttpClient abcdeClient = new HttpClient();
                HttpRequestMessage abcdeRequest = new HttpRequestMessage(HttpMethod.Get, string.Format("https://abcde.azurewebsites.net/api/abcde/GetabcdeDetails"));

                //Read Server Response
                HttpResponseMessage abcdeResponse = await abcdeClient.SendAsync(abcdeRequest);
                bool abcdeStatusCode200 = await abcdeResponse.Content.ReadAsAsync<bool>();

                if (abcdeStatusCode200 == true)
                {
                    // Call Your  API
                    HttpClient vwxyzClient = new HttpClient();
                    HttpRequestMessage vwxyzRequest = new HttpRequestMessage(HttpMethod.Get, string.Format("https://vwxyz.azurewebsites.net/api/vwxyz/GetvwxyzDefaultDetails"));

                    //Read Server Response
                    HttpResponseMessage vwxyzResponse = await vwxyzClient.SendAsync(vwxyzRequest);
                    bool vwxyzStatusCode200 = await vwxyzResponse.Content.ReadAsAsync<bool>();
                }
                else
                {
                    // Call Your  API
                    abcdeRequest = new HttpRequestMessage(HttpMethod.Get, string.Format("https://abcde.azurewebsites.net/api/abcde/GetabcdeDetails"));
                }
                return req.CreateResponse(HttpStatusCode.OK);

            }
            catch (Exception ex)
            {
                return req.CreateResponse(HttpStatusCode.OK, "The Called Scheduler Failed : {0}", string.Format(ex.Message));
            }
        }
    }

    public class ResponseModel
    {
        public bool abcdeStatusCode200 { get; set; }
        public bool vwxyzStatusCode200 { get; set; }
    }
}


Solution

  • You need to separate these two functions and call them within DurableOrchestrationClient


     var output = new List<string>();
    
     output.Add(await context.CallActivityAsync<string>("CallAPI1", "test2019"));
    
     output.Add(await context.CallActivityAsync<string>("CallAPI2", "test2"));
    

    EXAMPLE