10
votes

I have an Azure Function that runs on a timer trigger once a week. This works great and as expected, but about once or twice a month, a user needs this function to run upon request, so I need to do a post to the function to trigger it - much like you can do from the Azure portal.

Looking at the Azure portal, a http post request is being done to the function like:

https://{funcapp}.azurewebsites.net/admin/functions/{func}

However, if I do this from Postman, I get a Http 401 response. How would I go about to do this request?

One option I have a to rather change the trigger to a queue and have a second function run on the weekly basis that would add a message to the queue, but this seems a bit excessive to me.

2

2 Answers

6
votes

What if you share business logic between functions by using the fact that a single function app can be composed of multiple functions? Then you can have one function.json trigger based off of an HTTP request and the other trigger based off of a timer.

Your function app architecture could look like:

MyFunctionApp
|     host.json
|____ shared
|     |____ businessLogic.js
|____ function1
|     |____ index.js
|     |____ function.json
|____ function2
      |____ index.js
      |____ function.json

In "function1/index.js" and "function2/index.js"

var logic = require("../shared/businessLogic");

module.exports = logic;

The function.json of function1 and function2 can be configured to different triggers (timer and HTTP or queue... whatever you want!).

In "shared/businessLogic.js

module.exports = function (context, req) {
    // This is where shared code goes. As an example, for an HTTP trigger:
    context.res = {
        body: "<b>Hello World</b>",
        status: 201,
        headers: {
            'content-type': "text/html"
        }
    };     
    context.done();
};

(This is a JavaScript example, but same holds for other languages!)

12
votes

If you want to call admin API to trigger your timer function, you need to add your function master key in your request or you'll get 401 Unauthorized.

Find it on Function app settings panel >Host Keys (All functions)> _master.

Add it in your request header x-functions-key:<masterkey>.

Note that in this post request to admin API, you need to send a application/json type body(contain at least an empty json{}), this format is required or you may get 415 Unsupported Media Type.

If this post request are executed by users and you don't expect master key exposing to them, I do recommend you to use solutions provided by @Marie, have a try and you may find it's not so excessive as you thought.