Azure Function to call API and display information
In this post, will review on how to create an Azure Function to call an API to get the data and back the json data to requester. This is developed using Visual Studio in Windows environment.
Open Visual Studio and then click to create a new project. Search Azure Function Template and then click next. Put a meaningfull name and location of your project. Click next.
Once the project created, you will found the local.settings.json file. Replace the following code with the following one. We place environment/configuration variable in local.settings.json file under Values.
{
"IsEncrypted": false,
"Values": {
"AzureWebJobsStorage": "UseDevelopmentStorage=true",
"FUNCTIONS_WORKER_RUNTIME": "dotnet-isolated",
"APIURL": "https://www.alphavantage.co/",
"APIKEY": "ZMM6ZDHER7PFKY07"
}
}
Now, open the CS file your created for your HTTP trigger Azure function. Following SDK should be there.
using System;
using System.Net.Http;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.Http;
using Microsoft.Extensions.Logging;
using System.Collections.Generic;
using Microsoft.Azure.Functions.Worker;
using System.Collections;
Finally replace your class file with the following code:
public static class Stock
{
private static readonly HttpClient client = new HttpClient();
[Function("GetStockData")]
public static async Task<IActionResult> Run(
[HttpTrigger(AuthorizationLevel.Function, "get", "post", Route = null)] HttpRequest req,
ILogger log)
{
string symbol = req.Query["stock"];
if (string.IsNullOrEmpty(symbol))
{
return new BadRequestObjectResult("Please provide a stock symbol.");
}
// Replace with your actual API key
string apiKey = Environment.GetEnvironmentVariable("APIKEY");
string apiUrl = Environment.GetEnvironmentVariable("APIURL") + "query?function=TIME_SERIES_MONTHLY&symbol=" + symbol + "&apikey=" + apiKey;
HttpResponseMessage response = await client.GetAsync(apiUrl);
if (!response.IsSuccessStatusCode)
{
return new StatusCodeResult(500);
}
string jsonResponse = await response.Content.ReadAsStringAsync();
JObject data = JObject.Parse(jsonResponse);
return new ContentResult
{
Content = data.ToString(),
ContentType = "application/json",
StatusCode = 200
};
}
}
Run the project and then open the url to check. Please make sure to add ?stock= in query parameter.
For example, I'd like to test with with Micrsoft Stock price. MSFT is the stock code for Micrsoft.
Url would be something like http://localhost:7029/api/GetStockData?stock=MSFT
Comments
Post a Comment