Call external API from Azure function c#

Above, we discussed How To Create REST API With Azure Functions. Here, we will discussĀ How to call the External API from the Azure Function.

Call external API from Azure function c#

I will show this with the help of an example. If you will see the below example, I have an external API named WaveProductAPI. There, I am validating whether the WaveProductID provided is valid and returning the response True or False.

using System;
using System.Threading.Tasks;
using Microsoft.Azure.WebJobs;
using Microsoft.Azure.WebJobs.Extensions.Http;
using Microsoft.Extensions.Logging;
using Newtonsoft.Json;
using System.Net.Http;
using System.Net;


namespace ExternalAPICall
{
    public static class WaveProductAPIFunctionClass
    {
        [FunctionName("WaveProductAPIFunction")]
        public static async Task<HttpResponseMessage> Run([HttpTrigger(AuthorizationLevel.Anonymous, "get", "post", Route = null)]HttpRequestMessage req, ILogger log)
        {
            log.LogInformation("Calling my External API");


            try
            {

                var mycontent = req.Content;
                string jsonContent = mycontent.ReadAsStringAsync().Result;
                dynamic actualparm = JsonConvert.DeserializeObject<WaveProductModel>(jsonContent);


                if (string.IsNullOrEmpty(actualparm.WaveProductID))
                {
                    return req.CreateResponse(HttpStatusCode.OK, "Please enter a valid Wave Product Id!");
                }
           
                HttpClient client = new HttpClient();
                HttpRequestMessage myRequest = new HttpRequestMessage(HttpMethod.Get, string.Format("YourWaveProductAPIURL?waveproductId={0}", actualparm.WaveProductID));

               
                HttpResponseMessage httpresponse = await client.SendAsync(myRequest);
                bool isValidWaveProduct = await httpresponse.Content.ReadAsAsync<bool>();


              
                return req.CreateResponse(HttpStatusCode.OK, new WaveProductResponseModel { isValidWaveProductID = isValidWaveProduct });
            }
            catch (Exception ex)
            {

                return req.CreateResponse(HttpStatusCode.OK, "Wave API product ID is not valid !!! Reason: {0}", string.Format(ex.Message));
            }
        }
    }


    public class WaveProductModel
    {
        public string WaveProductID { get; set; }
    }


    public class WaveProductResponseModel
    {
        public bool isValidWaveProductID { get; set; }
    }
    
}

This is what the format for the WaveProductAPI is like below

{
    "WaveProductID": "abc346"
}

You may also like following the articles below

Wrapping Up

This Azure article discussed calling external API from Azure function using c#. Thanks for reading this article !!!