CodexBloom - Programming Q&A Platform

Using Azure Functions for Scheduled Tasks with Third-Party API Integration

👀 Views: 448 💬 Answers: 1 📅 Created: 2025-10-17
azure-functions api-integration timer-trigger C#

I'm trying to figure out Currently developing a background service that needs to call a third-party API on a schedule using Azure Functions. The goal is to fetch data every hour and process it for client reporting. I've set up my Azure Function with a timer trigger, but I'm not sure how to handle authentication with the third-party API. The API requires an API key sent in the headers. Here's what my current function looks like: ```csharp using System; using System.Net.Http; using System.Threading.Tasks; using Microsoft.Azure.WebJobs; using Microsoft.Extensions.Logging; public static class ScheduledFunction { private static readonly HttpClient httpClient = new HttpClient(); [FunctionName("FetchDataFunction")] public static async Task Run([TimerTrigger("0 */60 * * * *")] TimerInfo myTimer, ILogger log) { string apiUrl = "https://api.thirdparty.com/data"; string apiKey = Environment.GetEnvironmentVariable("THIRD_PARTY_API_KEY"); httpClient.DefaultRequestHeaders.Add("Authorization", apiKey); HttpResponseMessage response = await httpClient.GetAsync(apiUrl); if (response.IsSuccessStatusCode) { string content = await response.Content.ReadAsStringAsync(); log.LogInformation($"Data fetched successfully: {content}"); } else { log.LogError($"Failed to fetch data: {response.StatusCode}"); } } } ``` I made sure to store the API key in application settings for security, but still wondering if this is the best practice for managing sensitive information. I'm also considering adding error handling to manage failures when calling the API. Any best practices for handling retries or logging failed attempts? Additionally, is there a recommended approach for testing this function locally? I've been using the Azure Functions Core Tools, but would love to hear any tips from those who’ve integrated similar functionality in production environments. Any help would be greatly appreciated!