Search code examples
azureazure-functionsazure-function-appazure-functions-core-toolsazure-function-async

How to call an API using time trigger Azure function


I have to write an azure function using a time trigger that will hit an API every weekend and fetch the data from that API and store that data to my Azure SQL database.

So, I am not getting how to call an API from time trigger azure function to fetch data and how to store that data into my azure SQL database.


Solution

  • You can follow this link to get started Azure Function timer trigger.

    You have to use HTTPClient to call Api.

    static HttpClient client = new HttpClient();
    // Update port # in the following line.
    client.BaseAddress = new Uri("http://localhost:64195/");
    client.DefaultRequestHeaders.Accept.Clear();
    client.DefaultRequestHeaders.Accept.Add(
        new MediaTypeWithQualityHeaderValue("application/json"));
    
    Product product = null;
    HttpResponseMessage response = await client.GetAsync(path);
    if (response.IsSuccessStatusCode)
    {
        product = await response.Content.ReadAsAsync<Product>();
    }
    return product;
    

    Note: If you have to call lots of API's/endpoints, you may get port exhaustion error. HttpClientFactory is recommended for that scenario.