Your profile

One profile for every MSDEVBUILD site. Only you can see it, and the site owner if you write in.

Lesson 23 of 28
❮Prev Next❯

Azure Functions: Serverless APIs with Triggers and Bindings

Module 3: Messaging & Functions ⏱ 11 min read Updated

Your note

My notes for this lesson

Select any text in the lesson to highlight it or add a note. Saved in this browser.

    No highlights yet. Select a sentence in the lesson, then pick a colour or add a note.

    All my bookmarks and notes

    Reading settings

    For every lesson, saved in this browser.

    Text size
    Line spacing
    Font

    With IaaS you rent the virtual machine. Microsoft looks after the building, power and hardware; you patch the operating system.

    30-second answer

    An Azure Function is a small piece of code that runs when its trigger fires: an HTTP request, a Service Bus message, an Event Grid event, a timer or a Cosmos DB change. Each function has exactly one trigger. Bindings connect inputs and outputs without client code, so an HTTP API can drop a message on a queue through an output binding. In the Python v2 programming model you write everything in function_app.py with decorators on func.FunctionApp(), such as @app.route, @app.service_bus_queue_trigger and @app.service_bus_queue_output.

    Simulate it » No Azure account needed

    Exam objective: 3.2.1 Build serverless APIs, including implementing triggers and bindings. (Skills measured as of October 7, 2026)

    Simulations

    Feel it before you read it. No account needed, nothing leaves this page.

    Azure portal: Create a Flex Consumption function app and an HTTP function Create a function app and an HTTP-triggered function.
    </> Embed

    Embed this simulation

    Free for trainers, teachers and bloggers. Paste this into your page:

    Loading the portal…

    Open <strong>Function App</strong> and select <strong>+ Create</strong>.

    👆 Click the glowing item in the portal to continue

    Read the steps as text
    1. Open Function App and select + Create.
    2. Choose the hosting option. Flex Consumption scales to zero, scales out fast and supports VNet integration.
    3. Pick the runtime stack, version and instance size (memory per instance).
    4. On Authentication, choose Managed identity so the app reaches its storage and Application Insights without keys.
    5. Review and Create. It also creates a storage account and Application Insights.
    6. On the Functions tab select + Create.
    7. Pick HTTP trigger. Authorization level Function means callers need a function key.
    8. The trigger is the @app.route decorator. Select Test/Run and send a body.

    🧪 Simulation for learning. Screens are simplified versions of the Azure portal; names, prices and IDs are examples. Nothing here touches real Azure.

    😟 THE PROBLEM

    A tiny API needs a whole web server just to queue a job.

    😊 THE SOLUTION

    An HTTP-triggered function with a Service Bus output binding.

    • Boilerplate client code✓ Bindings
    • Server idle all night✓ Pay per execution
    • React to messages✓ Service Bus trigger
    🛠️ Solved with: Triggers and bindings

    Start with a question

    Do you really need a whole server just to run 20 lines of code when a file arrives?

    Think of the motion-sensor light in a corridor. It doesn’t burn all night. Someone walks in, it switches on, does its job, and switches off. You pay for the minutes it was on.

    Azure Functions works like that light. You write a small function, say which event switches it on (the trigger), and Azure runs it only when that happens. Bindings are the wiring to other services, so your function can write to a queue or read a blob without you writing connection code.

    Explain it like I’m 10

    Visual: triggers and bindings in motion

    Watch an HTTP request wake a function, a binding drop a message on a queue, and the app scale out and back to zero.

    ▶ Explainer video See it in motion 7 steps · 1 min 39 sec

    An animation of an Azure Functions app: five trigger types wait, an HTTP trigger wakes a Python v2 function decorated with @app.route, an input binding reads a blob, a Service Bus output binding writes a queue message with no client code, the function returns 202 Accepted, then instances scale out under load and back to zero when idle on the Flex Consumption plan.
    Read the video script
    1. Nothing runs until a trigger firesA function sits idle until its trigger fires. That can be an HTTP request, a Service Bus message, a timer, an Event Grid event or a change in Cosmos DB.
    2. One trigger per functionEach function gets exactly one trigger. In the Python v2 model, the decorator says which. Here it's at app dot route, so an HTTP request wakes it up.
    3. An input binding reads dataNeed a file too? Add an input binding, like blob input. The blob arrives as a parameter before your code starts, so you don't write any Storage client code.
    4. Output binding sends the messageNow the output binding. Declare the queue in a decorator, take a func dot Out parameter, and call set. The Functions host drops the message on the queue for you. No Service Bus client code at all.
    5. Reply 202 straight awayThen it returns 202 Accepted right away. The slow model call happens later, in a worker that the queue triggers, so the caller isn't left waiting on an open connection.
    6. More work, more instancesWhen a rush of requests comes in, Azure adds more instances to keep up. In this example it goes from one to eight. You don't pick servers or set up a load balancer.
    7. No work? Back to zeroAnd when it goes quiet, the Flex Consumption plan scales back in, all the way to zero instances, unless you've asked for some to stay ready. Like a corridor light, it's only on when someone walks in.

    The technical explanation

    A function app is the unit you deploy and scale. Inside it you write one or more functions. Each function has:

    • exactly one trigger, which starts it and usually passes in the data (the request, the message, the event);
    • zero or more input bindings, which read extra data (a blob, a Cosmos DB item);
    • zero or more output bindings, which write results (a queue message, a blob, a Cosmos DB document).

    The Python v2 programming model

    In the v2 model there’s no function.json. You create one FunctionApp object in function_app.py and decorate plain Python functions:

    import json, logging
    import azure.functions as func
    
    app = func.FunctionApp(http_auth_level=func.AuthLevel.FUNCTION)
    
    # 1. HTTP API that queues work through an output binding
    @app.route(route="summarise", methods=["POST"])
    @app.service_bus_queue_output(arg_name="job", queue_name="summarise-jobs",
                                  connection="ServiceBusConnection")
    def summarise(req: func.HttpRequest, job: func.Out[str]) -> func.HttpResponse:
        body = req.get_json()
        job.set(json.dumps({"docId": body["docId"], "blob": body["blob"]}))
        return func.HttpResponse(json.dumps({"status": "accepted"}), status_code=202,
                                 mimetype="application/json")
    
    # 2. Worker triggered by each queue message
    @app.service_bus_queue_trigger(arg_name="msg", queue_name="summarise-jobs",
                                   connection="ServiceBusConnection")
    def worker(msg: func.ServiceBusMessage):
        job = json.loads(msg.get_body().decode("utf-8"))
        logging.info("Summarising %s (delivery %s)", job["docId"], msg.delivery_count)
        summarise_document(job["blob"])      # raise to retry, return to complete

    connection="ServiceBusConnection" is the name of an app setting, not the secret itself. In Azure that setting can be a connection string, or you can use identity-based connections (covered in the deploy lesson).

    Common triggers and bindings

    DecoratorFires when / doesNotes
    @app.routeAn HTTP request arrives at /api/<route>Returns func.HttpResponse. Auth levels below.
    @app.service_bus_queue_trigger / @app.service_bus_topic_triggerA message arrives on a queue or subscriptionPeek-lock: completed on success, abandoned on exception.
    @app.event_grid_triggerEvent Grid pushes an eventReceives func.EventGridEvent. The validation handshake is handled for you.
    @app.timer_triggerA schedule is dueSix-field NCRONTAB, seconds first: 0 */15 * * * *.
    @app.cosmos_db_triggerItems are inserted or updated in a containerReads the change feed and needs a lease container.
    @app.blob_triggerA blob is added or updatedFor high volume, Event Grid-based blob triggers are faster.
    @app.service_bus_queue_output / @app.queue_outputWrites a message to Service Bus / Storage queueParameter type func.Out[str], then .set().
    @app.blob_input, @app.cosmos_db_inputReads a blob or item before the function runsValue arrives as a parameter.

    Two more you’ll see often:

    @app.event_grid_trigger(arg_name="event")
    def on_blob(event: func.EventGridEvent):
        data = event.get_json()
        logging.info("%s on %s", event.event_type, event.subject)
    
    @app.timer_trigger(schedule="0 0 2 * * *", arg_name="timer", run_on_startup=False)
    def nightly_reindex(timer: func.TimerRequest):
        if timer.past_due:
            logging.warning("Running late")
        rebuild_index()

    You can split a big app into files with func.Blueprint() and register it with app.register_functions(bp).

    HTTP authorization levels

    LevelCaller needs
    ANONYMOUSNothing. Anyone with the URL can call it.
    FUNCTIONA function key or host key, in the x-functions-key header or ?code= query string. This is the default.
    ADMINThe master key. Keep it for admin tools only.

    Keys aren’t checked when you run locally with Core Tools. Keys prove “this caller has the key”, not who the user is. For user identity, add built-in authentication with Microsoft Entra ID or put Azure API Management in front.

    1. 1 Call

      A client POSTs to /api/summarise with a function key.

    2. 2 Bind out

      The output binding writes a message to summarise-jobs. The API returns 202.

    3. 3 Trigger

      The Service Bus trigger hands the message to the worker function.

    4. 4 Settle

      Success completes the message. An exception abandons it for another try.

    An HTTP call turned into background work
    Architect level Retries, timeouts and long AI work

    A Service Bus-triggered function gets Service Bus’s own retry: abandon on failure, dead-letter after max delivery count. Event Grid has its own retry policy too. For other triggers you can add a function-level retry policy (fixed delay or exponential backoff) in some cases, but don’t stack retries on top of the broker’s retries without thinking about the total.

    HTTP functions behind the Azure load balancer must respond within about 230 seconds, whatever the function timeout. That’s why the pattern above returns 202 straight away and lets a queue-triggered function do the slow model call. For multi-step workflows with waits and fan-out, Durable Functions (orchestrator and activity functions) keeps state for you.

    Real-world business scenario

    Retail

    Wide World Importers (fictional)

    The problem
    Product descriptions for 40,000 items needed regenerating with a language model whenever a supplier sent new specs, and an old VM script ran all day even when nothing changed.
    What they used
    A Python v2 function app with an Event Grid trigger on the specs container, a Service Bus output binding that queues one job per product, a Service Bus-triggered worker that calls the model and a Cosmos DB output binding that saves the new description. A nightly timer trigger re-queues anything that failed.
    Why that choice
    Each step runs only when there's work, bindings removed most of the SDK code, and failed products end up in the dead-letter queue instead of vanishing.
    The result
    The VM was switched off, new specs show up on the site within minutes, and the team edits one function_app.py file instead of three scripts.

    When to use it and when not to

    ✓ Use it when…

    • Small units of code that should run in response to HTTP calls, messages, events or schedules.
    • Glue between services where bindings remove most of the client code.
    • Spiky workloads that sit idle a lot and should scale to zero.

    ✕ Think twice when…

    • Long-running processes or servers that need to stay up and hold connections. Use Container Apps or App Service.
    • A big web app with many routes and its own framework. App Service or Container Apps fits better.
    • Work that must answer an HTTP caller after several minutes. Queue it and reply 202 instead.

    ↔ Alternatives to consider

    • Azure Container Apps for containerised APIs and workers with KEDA scaling.
    • Durable Functions for stateful, multi-step workflows.
    • Azure Logic Apps for low-code workflows with connectors.
    Ready for more?The full lesson adds the technical explanation, when to use it, interview questions and revision notes.

    Test yourself with exercises

    5 original practice questions in the AI-200 style. Pick your answers, then check them. You will see why each option is right or wrong. Score 75% or more and this topic is marked complete.

    Question 1

    Question 1 of 5

    You are developing an Azure Function in Python by using the v2 programming model. The function must run each time a message arrives in an Azure Service Bus queue named jobs. Which decorator should you use?

    Question 2

    Question 2 of 5

    An HTTP-triggered Python function has the decorator @app.service_bus_queue_output(arg_name="job", queue_name="jobs", connection="ServiceBusConnection") and a parameter named job of type func.Out[str].

    How should the function send a message to the queue?

    Question 3

    Question 3 of 5

    A Python function is triggered by an Azure Service Bus queue and uses the default trigger settings. The function raises an unhandled exception for a message. What happens to the message?

    Question 4

    Question 4 of 5

    An HTTP-triggered function must be callable only by clients that supply a key specific to that function. The function must not require the host master key. Which authorization level should you set?

    Question 5

    Question 5 of 5

    A function must rebuild a search index at 02:00 every day. Which trigger configuration should you use?

    Interview preparation

    Say your answer out loud first, then open the model answer. Interviewers care more about your reasoning than the exact words.

    Beginner What's the difference between a trigger and a binding?

    Model answer

    The trigger is why the function runs: an HTTP call, a message, a timer. A function has exactly one. Bindings are optional extra connections for data in or out, like writing to a queue or reading a blob, and a function can have several. The trigger is itself a kind of input binding.

    Intermediate How do you write a Service Bus message from an HTTP function in Python without the Service Bus SDK?

    Model answer

    I add @app.service_bus_queue_output with arg_name, queue_name and connection, then add a parameter of type func.Out[str] with that name. Inside the function I call msg.set(json_text). The Functions host sends it to the queue when the function finishes.

    Experienced developer What happens to a Service Bus message if your queue-triggered function throws an exception?

    Model answer

    The trigger uses peek-lock. If the function succeeds, the host completes the message. If it throws, the host abandons it, so it's delivered again. After the queue's max delivery count, 10 by default, Service Bus dead-letters it. So my function should be idempotent and only throw for errors worth retrying.

    Scenario You need a public endpoint for a partner to request summaries, but only partners with a key should get in. How would you set up the function?

    Model answer

    An HTTP trigger with auth_level FUNCTION, so callers pass a function key in the x-functions-key header or the code query string. I'd give the partner their own key so I can revoke it alone. For real user identity I'd add App Service authentication with Microsoft Entra ID or put API Management in front.

    Quick revision

    Key points

    • One trigger per function. Bindings (input and output) are optional and can be many.
    • Python v2 - function_app.py, app = func.FunctionApp(), decorators per function. No function.json.
    • HTTP - @app.route with auth levels ANONYMOUS, FUNCTION, ADMIN.
    • Service Bus trigger completes on success and abandons on exception. Output bindings use func.Out[...] and .set().
    • The connection argument names an app setting, not the connection string itself.

    Important terminology

    Trigger
    What starts a function run, such as an HTTP request or a queue message. Every function has exactly one.
    Binding
    A declared connection to another service that passes data in (input) or out (output) without writing SDK code.
    Python v2 programming model
    The decorator-based way to write Python functions in function_app.py, with no function.json files.
    func.FunctionApp
    The object in function_app.py that functions are registered on with decorators.
    Authorization level
    Whether an HTTP function needs a key - ANONYMOUS (none), FUNCTION (a function or host key) or ADMIN (the master key).
    Connection setting
    The name of an app setting that tells a trigger or binding how to reach a service, by connection string or by identity.
    NCRONTAB
    The six-field schedule format used by the timer trigger, with seconds first, such as 0 */5 * * * *.

    Common mistakes

    • Putting the connection string straight into the decorator instead of an app setting name.
    • Expecting a Service Bus-triggered function to retry forever. After max delivery count the message is dead-lettered.
    • Writing six-field NCRONTAB as five-field cron.

    Exam tips

    • "Start when a message lands in a queue" = Service Bus queue trigger.
    • "Write to a queue without SDK code" = output binding.
    • "Run every 15 minutes" = timer trigger, 0 */15 * * * *.

    Five quick revision questions

    1. 1.How many triggers can a function have?Show

      Exactly one.

    2. 2.Which file holds Python v2 functions?Show

      function_app.py.

    3. 3.Which decorator defines an HTTP-triggered function?Show

      @app.route.

    4. 4.Which auth level needs no key?Show

      ANONYMOUS.

    5. 5.How do you set an output binding value in Python?Show

      Call .set() on the func.Out parameter.

    Official references

    Finished this lesson? Tick it off. Your progress is saved in this browser.

    Next up: Configure and Deploy Function Apps

    Studying with a friend? Send them this lesson

    It's free and needs no sign-up. Their progress saves in their own browser.

    Lesson done? Make it stick with a quick gameSort It, Match the Pairs, Lightning Round and Who Am I? Earn XP and badges. Play ❯

    Install MSDEVBUILD Azure

    Free · no account · works offline

    Save the whole course for offline ›

    Hi, I’m your Nimbus

    Your study buddy. Pick what we do next.

    MSDEVBUILD · Multi-Stack Dev Build

    Sign in to MSDEVBUILD

    One account for Azure certifications and the blog: sign in here and you are signed in on both. Your XP, streak, practice deck and certificate stay in sync on every device. Optional: everything works without an account.