5

I am trying to develop following scenario using Azure functions.

I have developed Asp.Net Web API which handles the Database related operation. Now, I want to implement a scheduler like functionality which will run once a day and will clean up junk data from database. I've created an endpoint for that in my Web API but I want to execute it on regular basis so I think to implement scheduler using Azure function's TimerTrigger function, is there any way to call my web api's endpoint in TimerTrigger function.

How to handle my api's authentication in Azure function?

Thanks

Update:

Based on mikhail's answer, finally I got the token using following code:

var client = new HttpClient();
client.BaseAddress = new Uri(apirooturl);

var grant_type = "password";
var username = "username";
var password = "password";

var formContent = new FormUrlEncodedContent(new[]
{
    new KeyValuePair<string, string>("grant_type", grant_type),
    new KeyValuePair<string, string>("username", username),
    new KeyValuePair<string, string>("password", password)
});

var token = client.PostAsync("token", formContent).Result.Content.ReadAsAsync<AuthenticationToken>().Result;

client.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue(token.token_type, token.access_token);

var response = await client.GetAsync(apiendpoint);
var content = await response.Content.ReadAsStringAsync();
Ian Kemp
  • 28,293
  • 19
  • 112
  • 138
Rinkesh
  • 132
  • 1
  • 1
  • 11
  • How/What did you add references so you could use `AuthenticationToken`? Thanks. – Skorunka František Oct 30 '17 at 12:36
  • @SkorunkaFrantišek i added `using System.Net.Http;` as it's a part of `DefaultRequestHeaders` property of `HttpClient` class and we can find `HttpClient` under `System.Net.Http` namespace. – Rinkesh Oct 31 '17 at 16:58

2 Answers2

5

Azure Function is running in a normal Web App, so you can do pretty much anything there. Assuming you are on C#, the function body might looks something like

var client = new HttpClient();
client.DefaultRequestHeaders.Authorization = 
    new AuthenticationHeaderValue("Bearer", token);

var response = await client.GetAsync(url);
var content = await response.Content.ReadAsStringAsync();
Mikhail Shilkov
  • 34,128
  • 3
  • 68
  • 107
  • Thanks for quick answer. I am just wondering how to get token, as my api will be on different url. Also, I tried to call my token endpoint but it is not returning the token. – Rinkesh Mar 10 '17 at 17:15
  • I gave Bearer authentication as just an example. It depends on what you configured for your API. If you have authentication working somewhere, you'll be able to copy it to Function App. – Mikhail Shilkov Mar 10 '17 at 17:36
  • I'll take a look. Thanks a lot. – Rinkesh Mar 10 '17 at 18:01
0

You may be better off putting the entire database cleanup logic in the function and making it timer triggered, that way you keep your API out of it altogether.

Rob King
  • 1,131
  • 14
  • 20