In this post we are going to cover triggers and bindings in practice. These are 7 real Azure Functions interview questions for data engineers, asked the way they come up on a real project, and the last one is a scenario: an order API must save each order and notify the warehouse without losing any, and you have to build it with Functions.
A trigger is what starts a function, and bindings move data in and out without client code. That sounds simple, and it is, until a timer runs in the wrong time zone, a message lands in a poison queue or two outputs disagree. Interviewers ask about triggers and bindings because these small details decide whether a pipeline loses data.
Part 2 of the Real Time Azure Functions Interview Questions and Answers series on TechBrothersIT.
- The short answer
- Let's set up the project
- Question 1: A teammate needs a job that runs every night at two. How does the timer trigger work?
- Question 2: Someone asks how an HTTP trigger works and how callers authenticate. What do you tell them?
- Question 3: A pipeline must process every message dropped on a storage queue. How does the queue trigger work?
- Question 4: A teammate asks how input and output bindings save code. When do you use them, and when do you use the SDK instead?
- Question 5: Someone asks how one function can write to several destinations. How do multiple output bindings work?
- Question 6: A teammate asks how binding expressions like {id} or {name} work. What can they do?
- Scenario 7: An order API must save each order and notify the warehouse without losing any. How do you build it with Functions?
- The full script
The short answer
Timers use a six-field NCRONTAB schedule in UTC; keys are not authentication; the queue trigger tries five times, then the poison queue. Bindings save code, but output-binding errors can't be caught and outputs are not one transaction: use the SDK for control, and make every step idempotent.
Let's set up the project
Everything below runs on the real Azure Functions host running locally with Core Tools, with Azurite, Microsoft's open-source storage emulator, for blobs, queues and tables. Each step writes a small Python function app and its client scripts, and fhost runs func start in the background and prints the cleaned host log. What only Azure can show, such as key checks on a real endpoint, is shown as code.
Question 1: A teammate needs a job that runs every night at two. How does the timer trigger work?
The timer trigger runs a function on an NCRONTAB schedule with six fields, seconds first. Every night at two is 0 0 2 * * *, in UTC.
Let's read the six fields:
| second | minute | hour | day | month | day of week |
|---|---|---|---|---|---|
| 0 | 0 | 2 | * | * | * |
Five-field cron is accepted too, but we always write the seconds. UTC is the default. WEBSITE_TIME_ZONE changes it on Windows and on Linux Premium or Dedicated, not on Flex Consumption or Linux Consumption: there, write the UTC time and plan for daylight saving.
Now let's run it. We start the host, read the schedule status the host keeps in storage with python next_run.py, then run the timer now through the admin API with python run_now.py nightly_load.
import logging
import azure.functions as func
app = func.FunctionApp()
@app.timer_trigger(schedule="0 0 2 * * *", arg_name="timer",
run_on_startup=False, use_monitor=True)
def nightly_load(timer: func.TimerRequest) -> None:
if timer.past_due: # a missed run, started late
logging.warning("nightly_load is running late")
logging.info("nightly_load: load yesterday's orders, past_due=%s",
timer.past_due){
"version": "2.0",
"logging": {
"logLevel": {
"default": "Warning",
"Function": "Information",
"Azure.Core": "Error",
"Host.Function.Console": "Information"
}
},
"extensions": {
"queues": {
"batchSize": 1,
"newBatchThreshold": 0,
"maxPollingInterval": "00:00:01"
}
},
"extensionBundle": {
"id": "Microsoft.Azure.Functions.ExtensionBundle",
"version": "[4.*, 5.0.0)"
}
}{
"IsEncrypted": false,
"Values": {
"FUNCTIONS_WORKER_RUNTIME": "python",
"AzureWebJobsStorage": "UseDevelopmentStorage=true"
}
}azure-functionsimport json, os
from datetime import datetime
from azure.storage.blob import ContainerClient
hosts = ContainerClient.from_connection_string(
os.environ["AZURE_STORAGE_CONNECTION_STRING"],
"azure-webjobs-hosts") # the host's own container
for blob in hosts.list_blobs(name_starts_with="timers/"):
status = json.loads(hosts.download_blob(blob.name).readall())
nxt = datetime.fromisoformat(status["Next"])
print(blob.name)
print(" next run:", nxt.strftime("%H:%M:%S"), nxt.tzname())import sys
import requests
# Local host: no key needed here (in Azure: the master key)
name = sys.argv[1]
r = requests.post(f"http://localhost:7071/admin/functions/{name}",
json={"input": ""})
print("run", name, "now:", r.status_code)$ cd nightly_app && fhost start
host started, functions:
nightly_load: timerTrigger
$ python next_run.py
timers/tbit-fn-demo/Host.Functions.nightly_load/status
next run: 02:00:00 UTC
$ python run_now.py nightly_load
run nightly_load now: 202
$ cd nightly_app && fhost wait "Executed 'Functions.nightly_load'" 30
$ cd nightly_app && fhost log
Executing 'Functions.nightly_load' (Reason='This function was programmatically called via the host
APIs.')
nightly_load: load yesterday's orders, past_due=False
Executed 'Functions.nightly_load' (Succeeded)
$ cd nightly_app && fhost stop
host stoppedThe status blob timers/tbit-fn-demo/Host.Functions.nightly_load/status says next run: 02:00:00 UTC. The admin call returns 202, which in Azure needs the master key, and the run logs past_due=False.
use_monitor=True keeps that status across restarts. If the host was down at two, the missed run starts late with past_due true, so we log it.
Never set run_on_startup=True in production: it runs on every restart and scale-out. And a failed run waits for the next schedule unless you add a retry policy, which timers support.
Question 2: Someone asks how an HTTP trigger works and how callers authenticate. What do you tell them?
An HTTP trigger makes the function an endpoint. The decorator sets the route and methods, route parameters arrive as strings, and you return an HttpResponse.
Authorization levels decide what a caller sends. We always set it explicitly.
| auth_level | Caller sends |
|---|---|
| ANONYMOUS | no key |
| FUNCTION | function key or host key: ?code= or x-functions-key |
| ADMIN | the master key |
Let's try it. Our app has get_order with FUNCTION level and health with ANONYMOUS. We run python call_api.py, which calls both, once with a wrong key and once with the wrong method, then lists the keys.
import json
import azure.functions as func
app = func.FunctionApp(http_auth_level=func.AuthLevel.FUNCTION)
@app.route(route="orders/{order_id}", methods=["GET"],
auth_level=func.AuthLevel.FUNCTION) # key required
def get_order(req: func.HttpRequest) -> func.HttpResponse:
order_id = req.route_params["order_id"] # a string
body = {"id": order_id, "status": "shipped"}
return func.HttpResponse(json.dumps(body),
mimetype="application/json")
@app.route(route="health", methods=["GET"],
auth_level=func.AuthLevel.ANONYMOUS) # no key
def health(req: func.HttpRequest) -> func.HttpResponse:
return func.HttpResponse("ok"){
"version": "2.0",
"logging": {
"logLevel": {
"default": "Warning",
"Function": "Information",
"Azure.Core": "Error",
"Host.Function.Console": "Information"
}
},
"extensions": {
"queues": {
"batchSize": 1,
"newBatchThreshold": 0,
"maxPollingInterval": "00:00:01"
}
},
"extensionBundle": {
"id": "Microsoft.Azure.Functions.ExtensionBundle",
"version": "[4.*, 5.0.0)"
}
}{
"IsEncrypted": false,
"Values": {
"FUNCTIONS_WORKER_RUNTIME": "python",
"AzureWebJobsStorage": "UseDevelopmentStorage=true"
}
}azure-functionsimport requests
API = "http://localhost:7071"
calls = [("GET", "/api/health", None),
("GET", "/api/orders/o-1001", None),
("GET", "/api/orders/o-1001", "wrong"),
("POST", "/api/orders/o-1001", None)]
for method, path, key in calls:
headers = {"x-functions-key": key} if key else {}
r = requests.request(method, API + path, headers=headers)
tag = key or "-"
print(f"{method:4} {path:19} key={tag:5}", r.status_code, r.text)
keys = requests.get(API + "/admin/functions/get_order/keys").json()
print("get_order keys:", [k["name"] for k in keys["keys"]])$ cd api_app && fhost start
host started, functions:
get_order: [GET] http://localhost:7071/api/orders/{order_id}
health: [GET] http://localhost:7071/api/health
$ python call_api.py
GET /api/health key=- 200 ok
GET /api/orders/o-1001 key=- 200 {"id": "o-1001", "status": "shipped"}
GET /api/orders/o-1001 key=wrong 200 {"id": "o-1001", "status": "shipped"}
POST /api/orders/o-1001 key=- 404
get_order keys: ['default']
$ cd api_app && fhost stop
host stoppedThe local host doesn't enforce keys: /api/orders/o-1001 returns 200 with no key and with key=wrong. The POST gets 404, since the route only allows GET. The key exists, named default. In Azure, no valid key means 401:
# In Azure, keys are enforced (not run here)
URL=https://fn-orders-prod.azurewebsites.net/api/orders/o-1001
curl -s -o /dev/null -w "%{http_code}\n" "$URL"
# 401
curl -s -o /dev/null -w "%{http_code}\n" \
-H "x-functions-key: $FUNCTION_KEY" "$URL"
# 200But a key is a shared secret, not an identity: anyone who has it gets in, and you rotate it yourself. For a real API, put one of these in front:
- App Service built-in authentication: with Microsoft Entra ID
- API Management: in front of the function app
No HTTP response can take longer than 230 seconds, on any plan. For long work, put it on a queue and return 202 right away.
Question 3: A pipeline must process every message dropped on a storage queue. How does the queue trigger work?
The host polls the queue and runs the function once per message. On success the message is deleted. On an exception it is retried, 5 attempts including the first, then it moves to the poison queue, orders-poison.
By default the trigger expects base64 messages, so the sender uses a base64 encode policy. Let's send three orders that way and a fourth from a client that sends plain text, with python send_mixed.py, then check both queues with python queues.py.
import json, logging
import azure.functions as func
app = func.FunctionApp()
@app.queue_trigger(arg_name="msg", queue_name="orders",
connection="AzureWebJobsStorage")
def load_order(msg: func.QueueMessage) -> None:
order = json.loads(msg.get_body())
logging.info("load %s, attempt %s", order["id"],
msg.dequeue_count){
"version": "2.0",
"logging": {
"logLevel": {
"default": "Warning",
"Function": "Information",
"Azure.Core": "Error",
"Host.Function.Console": "Information"
}
},
"extensions": {
"queues": {
"batchSize": 1,
"newBatchThreshold": 0,
"maxPollingInterval": "00:00:01"
}
},
"extensionBundle": {
"id": "Microsoft.Azure.Functions.ExtensionBundle",
"version": "[4.*, 5.0.0)"
}
}{
"IsEncrypted": false,
"Values": {
"FUNCTIONS_WORKER_RUNTIME": "python",
"AzureWebJobsStorage": "UseDevelopmentStorage=true"
}
}azure-functionsimport json, os
from azure.storage.queue import QueueClient, TextBase64EncodePolicy
CONN = os.environ["AZURE_STORAGE_CONNECTION_STRING"]
b64 = QueueClient.from_connection_string( # what Functions expects
CONN, "orders", message_encode_policy=TextBase64EncodePolicy())
b64.create_queue()
for oid in ["o-1001", "o-1002", "o-1003"]:
b64.send_message(json.dumps({"id": oid}))
plain = QueueClient.from_connection_string(CONN, "orders") # plain
plain.send_message(json.dumps({"id": "o-1004"}))
print("sent 3 base64 orders and 1 plain-text order")import os
from azure.storage.queue import QueueServiceClient
svc = QueueServiceClient.from_connection_string(
os.environ["AZURE_STORAGE_CONNECTION_STRING"])
for name in ["orders", "orders-poison"]:
q = svc.get_queue_client(name)
count = q.get_queue_properties().approximate_message_count
peek = [m.content for m in q.peek_messages(max_messages=5)]
print(f"{name}: {count} messages {peek}")$ cd queue_app && fhost start
host started, functions:
load_order: queueTrigger
$ python send_mixed.py
sent 3 base64 orders and 1 plain-text order
$ cd queue_app && fhost wait "Executed 'Functions.load_order'" 60 3
$ cd queue_app && fhost wait "Moving message to queue" 60
$ cd queue_app && fhost log
Executing 'Functions.load_order' (Reason='New queue message detected on 'orders'.')
load o-1001, attempt 1
Executed 'Functions.load_order' (Succeeded)
Executing 'Functions.load_order' (Reason='New queue message detected on 'orders'.')
load o-1002, attempt 1
Executed 'Functions.load_order' (Succeeded)
Executing 'Functions.load_order' (Reason='New queue message detected on 'orders'.')
load o-1003, attempt 1
Executed 'Functions.load_order' (Succeeded)
Message decoding has failed! Check MessageEncoding settings. Message.
Message has reached MaxDequeueCount of 5. Moving message to queue 'orders-poison'.
$ python queues.py
orders: 0 messages []
orders-poison: 1 messages ['{"id": "o-1004"}']
$ cd queue_app && fhost stop
host stoppedThe three orders run in order, o-1001, o-1002 and o-1003, each on attempt 1. Batch size 1 keeps our log in order. By default the host takes 16 messages at a time, so there is no ordering guarantee.
The plain-text order never runs. We get Message decoding has failed! Check MessageEncoding settings., and it goes straight to orders-poison, whatever the next log line says about MaxDequeueCount. In the end orders has 0 messages and orders-poison holds {"id": "o-1004"}. A classic incident: the function looks idle while orders pile up in poison.
A message is 64 KB at most, so send a blob path, not the data. And delivery is at least once, so make the function safe to run twice.
Question 4: A teammate asks how input and output bindings save code. When do you use them, and when do you use the SDK instead?
Bindings move data without client code: the host connects, reads and writes for you. The SDK gives you full control over upserts, conditions, listing and errors.
Let's compare them:
| Binding | SDK client | |
|---|---|---|
| code | a decorator and a parameter | a client, created once, and calls |
| errors | output errors come after your code returns: not catchable | yours to catch and handle |
| operations | what the binding does (table output: new entities only) | upsert, conditional writes, listing, batches |
Now let's see the trade. A table output binding saves customer c-1. We post Ana, then a corrected name, Ana Lee, for the same row key.
import json
import azure.functions as func
from customers_sdk import bp as sdk_bp
app = func.FunctionApp(http_auth_level=func.AuthLevel.FUNCTION)
app.register_functions(sdk_bp)
@app.route(route="customers", methods=["POST"])
@app.table_output(arg_name="row", table_name="Customers",
connection="AzureWebJobsStorage")
def add_customer(req: func.HttpRequest,
row: func.Out[str]) -> func.HttpResponse:
c = req.get_json()
row.set(json.dumps({"PartitionKey": "shop", "RowKey": c["id"],
"name": c["name"]})) # binding: an insert
return func.HttpResponse(f"saved {c['id']}"){
"version": "2.0",
"logging": {
"logLevel": {
"default": "Warning",
"Function": "Information",
"Azure.Core": "Error",
"Host.Function.Console": "Information"
}
},
"extensions": {
"queues": {
"batchSize": 1,
"newBatchThreshold": 0,
"maxPollingInterval": "00:00:01"
}
},
"extensionBundle": {
"id": "Microsoft.Azure.Functions.ExtensionBundle",
"version": "[4.*, 5.0.0)"
}
}{
"IsEncrypted": false,
"Values": {
"FUNCTIONS_WORKER_RUNTIME": "python",
"AzureWebJobsStorage": "UseDevelopmentStorage=true"
}
}azure-functionsimport logging, os
import azure.functions as func
from azure.core.exceptions import HttpResponseError
from azure.data.tables import TableServiceClient
bp = func.Blueprint()
logging.getLogger("azure").setLevel(logging.WARNING) # quiet SDK logs
tables = TableServiceClient.from_connection_string(
os.environ["AzureWebJobsStorage"]) # one client, reused
customers = tables.get_table_client("Customers") # no I/O at import
@bp.route(route="customers/upsert", methods=["POST"],
auth_level=func.AuthLevel.FUNCTION)
def upsert_customer(req: func.HttpRequest) -> func.HttpResponse:
c = req.get_json()
row = {"PartitionKey": "shop", "RowKey": c["id"],
"name": c["name"]}
try:
customers.upsert_entity(row) # insert or merge
except HttpResponseError as e: # your own handling
return func.HttpResponse(f"retry later ({e.status_code})",
status_code=503)
return func.HttpResponse(f"upserted {c['id']}")import sys
import requests
path = sys.argv[1] # customers or customers/upsert
for name in sys.argv[2:]:
r = requests.post(f"http://localhost:7071/api/{path}",
json={"id": "c-1", "name": name})
print(f"POST /api/{path} {name!r} -> {r.status_code} {r.text}")import os
from azure.data.tables import TableClient
table = TableClient.from_connection_string(
os.environ["AZURE_STORAGE_CONNECTION_STRING"], "Customers")
for e in table.list_entities():
print("Customers row:", e["RowKey"], e["name"])$ cd bind_app && fhost start
host started, functions:
add_customer: [POST] http://localhost:7071/api/customers
upsert_customer: [POST] http://localhost:7071/api/customers/upsert
$ python call_customers.py customers Ana "Ana Lee"
POST /api/customers 'Ana' -> 200 saved c-1
POST /api/customers 'Ana Lee' -> 500
$ cd bind_app && fhost wait "Executed 'Functions.add_customer'" 30 2
$ cd bind_app && fhost log | grep -E "^Executed|_binder|^ErrorCode" | fold -s -w 80
Executed 'Functions.add_customer' (Succeeded)
Executed 'Functions.add_customer' (Failed)
System.Private.CoreLib: Exception while executing function:
Functions.add_customer. Microsoft.Azure.WebJobs.Host: Error while handling
parameter _binder after function returned:. Azure.Data.Tables: 0:The specified
entity already exists.
ErrorCode: EntityAlreadyExistsThe first save returns 200 saved c-1. The second gets 500, with ErrorCode: EntityAlreadyExists. The docs say this binding only creates new entities, in Azure too. And look where it failed: Error while handling parameter _binder after function returned. Errors from an output binding happen outside your code, so you can't catch them. You can only validate the data first.
The SDK version uses one table client, created at module level. It upserts and handles errors itself. We post Ana Lee to customers/upsert and list the table with python rows.py.
$ python call_customers.py customers/upsert "Ana Lee"
POST /api/customers/upsert 'Ana Lee' -> 200 upserted c-1
$ cd bind_app && fhost wait "Executed 'Functions.upsert_customer'" 30
$ python rows.py
Customers row: c-1 Ana Lee
$ cd bind_app && fhost stop
host stoppedIt returns 200 upserted c-1, and the table has one row: c-1 Ana Lee.
| Use | When |
|---|---|
| bindings | the simple path: a read, or writing a new item |
| the SDK | upserts, conditional writes, listing, your own error handling |
| either way | reuse SDK clients; for blobs, SDK type bindings hand you a BlobClient |
Bindings for the simple path, the SDK for upserts, conditional writes, listing or your own error handling. Reuse SDK clients, and for blobs, SDK type bindings hand you a ready client.
Question 5: Someone asks how one function can write to several destinations. How do multiple output bindings work?
Stack one output decorator per destination, each with its own parameter typed func.Out. The function sets each one, and the HTTP response is one more output: the return value.
Our order API writes three things:
- orders/{id}.json: blob output, the ID comes from the body
- warehouse: queue output
- Orders: table output
Let's post a good order and one with no amount, check all three with python check.py, then resend o-1001 with a new amount and check again.
import json
import azure.functions as func
app = func.FunctionApp(http_auth_level=func.AuthLevel.FUNCTION)
C = "AzureWebJobsStorage"
@app.route(route="orders", methods=["POST"])
@app.blob_output(arg_name="doc", path="orders/{id}.json",
connection=C)
@app.queue_output(arg_name="msg", queue_name="warehouse",
connection=C)
@app.table_output(arg_name="row", table_name="Orders", connection=C)
def save_order(req: func.HttpRequest, doc: func.Out[str],
msg: func.Out[str],
row: func.Out[str]) -> func.HttpResponse:
order = req.get_json()
doc.set(json.dumps(order)) # 1. blob
msg.set(json.dumps({"orderId": order["id"]})) # 2. queue
row.set(json.dumps({"PartitionKey": "orders", # 3. table
"RowKey": order["id"],
"amount": order["amount"]}))
return func.HttpResponse(f"saved {order['id']}", status_code=201){
"version": "2.0",
"logging": {
"logLevel": {
"default": "Warning",
"Function": "Information",
"Azure.Core": "Error",
"Host.Function.Console": "Information"
}
},
"extensions": {
"queues": {
"batchSize": 1,
"newBatchThreshold": 0,
"maxPollingInterval": "00:00:01"
}
},
"extensionBundle": {
"id": "Microsoft.Azure.Functions.ExtensionBundle",
"version": "[4.*, 5.0.0)"
}
}{
"IsEncrypted": false,
"Values": {
"FUNCTIONS_WORKER_RUNTIME": "python",
"AzureWebJobsStorage": "UseDevelopmentStorage=true"
}
}azure-functionsimport json, sys
import requests
for body in sys.argv[1:]:
r = requests.post("http://localhost:7071/api/orders", data=body)
print("POST", body, "->", r.status_code, r.text)import json, os
from azure.data.tables import TableClient
from azure.storage.blob import ContainerClient
from azure.storage.queue import QueueClient, TextBase64DecodePolicy
CONN = os.environ["AZURE_STORAGE_CONNECTION_STRING"]
blobs = ContainerClient.from_connection_string(CONN, "orders")
queue = QueueClient.from_connection_string(
CONN, "warehouse", message_decode_policy=TextBase64DecodePolicy())
table = TableClient.from_connection_string(CONN, "Orders")
blob_text = {b.name: blobs.download_blob(b.name).readall().decode()
for b in blobs.list_blobs()}
messages = [json.loads(m.content)["orderId"]
for m in queue.peek_messages(32)]
print("blob orders/ :", blob_text)
print("queue warehouse:", messages)
print("table Orders :",
[(e["RowKey"], e["amount"]) for e in table.list_entities()])$ cd orders_app && fhost start
host started, functions:
save_order: [POST] http://localhost:7071/api/orders
$ python post_orders.py '{"id": "o-1001", "amount": 25.5}' '{"id": "o-1002"}'
POST {"id": "o-1001", "amount": 25.5} -> 201 saved o-1001
POST {"id": "o-1002"} -> 500
$ python check.py
blob orders/ : {'o-1001.json': '{"id": "o-1001", "amount": 25.5}'}
queue warehouse: ['o-1001']
table Orders : [('o-1001', 25.5)]
$ python post_orders.py '{"id": "o-1001", "amount": 30.0}'
POST {"id": "o-1001", "amount": 30.0} -> 500
$ python check.py
blob orders/ : {'o-1001.json': ''}
queue warehouse: ['o-1001', 'o-1001']
table Orders : [('o-1001', 25.5)]
$ cd orders_app && fhost stop
host stoppedOrder o-1001 returns 201 saved o-1001, and all three destinations have it. Order o-1002 has no amount, so the function throws with 500, and nothing from that call is written.
But it isn't one transaction. The resent o-1001 with amount 30.0 gets 500: the table insert fails and the row stays at 25.5. Yet a second warehouse message went out, ['o-1001', 'o-1001'], and the order blob ended up empty, ''. Outputs are written after the function returns, one by one, with no rollback.
Key each destination on the order ID, or save once and fan out from there. For many messages from one call, type the output as func.Out[typing.List[str]].
Question 6: A teammate asks how binding expressions like {id} or {name} work. What can they do?
Binding expressions are placeholders in binding properties that the host fills in at run time, so names and paths need no code.
Let's look at the four kinds we use:
| Expression | Filled from | Example here |
|---|---|---|
| %PICK_QUEUE% | an app setting | pick-requests |
| {orderId} | the trigger: a property of the message JSON | orders/o-1001.json |
| {DequeueCount} | trigger metadata | picks/o-1001-try1.txt |
| {name} | the blob trigger path | raw/{name}.csv: name without .csv |
First, percent signs read an app setting: %PICK_QUEUE% is set to pick-requests. Then curly braces read the trigger: {orderId} comes from the message JSON, and the input binding loads that order's blob. Trigger metadata works too: {DequeueCount} goes into the output name.
For a blob trigger, {name} captures the blob name. With .csv in the path, it excludes the extension. We run python seed.py, which queues o-1001 and uploads raw/sales_1030.csv and raw/notes.txt, then list picks and curated.
import csv, io, json, logging
import azure.functions as func
app = func.FunctionApp()
C = "AzureWebJobsStorage"
@app.queue_trigger(arg_name="msg", queue_name="%PICK_QUEUE%",
connection=C) # an app setting
@app.blob_input(arg_name="order", path="orders/{orderId}.json",
connection=C) # from the message
@app.blob_output(arg_name="pick", connection=C,
path="picks/{orderId}-try{DequeueCount}.txt")
def make_pick(msg: func.QueueMessage, order: str,
pick: func.Out[str]) -> None:
pick.set(f"pick list for {json.loads(order)['id']}")
@app.blob_trigger(arg_name="src", path="raw/{name}.csv",
connection=C) # name: no .csv
@app.blob_output(arg_name="dst", path="curated/{name}.json",
connection=C)
def csv_to_json(src: func.InputStream, dst: func.Out[str]) -> None:
rows = list(csv.DictReader(io.StringIO(src.read().decode())))
dst.set(json.dumps(rows))
logging.info("csv_to_json %s: %d rows", src.name, len(rows)){
"version": "2.0",
"logging": {
"logLevel": {
"default": "Warning",
"Function": "Information",
"Azure.Core": "Error",
"Host.Function.Console": "Information"
}
},
"extensions": {
"queues": {
"batchSize": 1,
"newBatchThreshold": 0,
"maxPollingInterval": "00:00:01"
}
},
"extensionBundle": {
"id": "Microsoft.Azure.Functions.ExtensionBundle",
"version": "[4.*, 5.0.0)"
}
}{
"IsEncrypted": false,
"Values": {
"FUNCTIONS_WORKER_RUNTIME": "python",
"AzureWebJobsStorage": "UseDevelopmentStorage=true",
"PICK_QUEUE": "pick-requests"
}
}azure-functionsimport json, os
from azure.storage.blob import BlobServiceClient
from azure.storage.queue import QueueClient, TextBase64EncodePolicy
CONN = os.environ["AZURE_STORAGE_CONNECTION_STRING"]
blobs = BlobServiceClient.from_connection_string(CONN)
def container(name):
box = blobs.get_container_client(name)
if not box.exists():
box.create_container()
return box
container("orders").upload_blob("o-1001.json", json.dumps(
{"id": "o-1001", "amount": 25.5}), overwrite=True)
picks = QueueClient.from_connection_string(
CONN, "pick-requests",
message_encode_policy=TextBase64EncodePolicy())
picks.create_queue()
picks.send_message(json.dumps({"orderId": "o-1001"}))
raw = container("raw")
raw.upload_blob("sales_1030.csv", "id,amount\n1,20.5\n2,7\n")
raw.upload_blob("notes.txt", "not a csv file")
print("queued o-1001; uploaded raw/sales_1030.csv and raw/notes.txt")import os, sys
from azure.storage.blob import BlobServiceClient
svc = BlobServiceClient.from_connection_string(
os.environ["AZURE_STORAGE_CONNECTION_STRING"])
for name in sys.argv[1:]:
box = svc.get_container_client(name)
for blob in box.list_blobs():
text = box.download_blob(blob.name).readall().decode()
print(f"{name}/{blob.name}: {text}")$ cd expr_app && fhost start
host started, functions:
csv_to_json: blobTrigger
make_pick: queueTrigger
$ python seed.py
queued o-1001; uploaded raw/sales_1030.csv and raw/notes.txt
$ cd expr_app && fhost wait "Executed 'Functions.(make_pick|csv_to_json)'" 60 2
$ cd expr_app && fhost log | grep "^Executed" | sort
Executed 'Functions.csv_to_json' (Succeeded)
Executed 'Functions.make_pick' (Succeeded)
$ python list.py picks curated
picks/o-1001-try1.txt: pick list for o-1001
curated/sales_1030.json: [{"id": "1", "amount": "20.5"}, {"id": "2", "amount": "7"}]
$ cd expr_app && fhost stop
host stoppedThe pick file is picks/o-1001-try1.txt. The sales file became curated/sales_1030.json with two rows, and notes.txt was ignored. On Flex Consumption, blob triggers need the Event Grid source.
{rand-guid}, {DateTime} and {DequeueCount} change per run, so a retry writes a second file. A name from the business key overwrites, so it is rerun-safe.
Scenario 7: An order API must save each order and notify the warehouse without losing any. How do you build it with Functions?
The API validates the order, saves it to a blob, queues a message for the warehouse and returns 202. A queue-triggered function does the warehouse work, so a slow warehouse never blocks orders.
Here is the flow, step by step:
- Shop: calls
POST /api/orders - place_order: validates first, so a bad order gets
400and writes nothing, then savesorders/{id}.jsonand puts a message onshipping - ship_order: writes
shipments/{orderId}.json, idempotent on the order ID; it needs only the message, since the blob may land after it
Let's run python shop.py. It sends o-1001 and o-1002, then o-1001 again like a client retry, and an invalid o-1003.
import json
import azure.functions as func
from warehouse import bp as warehouse_bp
app = func.FunctionApp(http_auth_level=func.AuthLevel.FUNCTION)
app.register_functions(warehouse_bp)
C = "AzureWebJobsStorage"
@app.route(route="orders", methods=["POST"])
@app.blob_output(arg_name="doc", path="orders/{id}.json",
connection=C)
@app.queue_output(arg_name="ship", queue_name="shipping",
connection=C)
def place_order(req: func.HttpRequest, doc: func.Out[str],
ship: func.Out[str]) -> func.HttpResponse:
order = req.get_json()
if order.get("amount", 0) <= 0: # validate first
return func.HttpResponse("invalid order", status_code=400)
doc.set(json.dumps(order)) # save the order
ship.set(json.dumps({"orderId": order["id"]})) # notify warehouse
return func.HttpResponse(f"accepted {order['id']}",
status_code=202){
"version": "2.0",
"logging": {
"logLevel": {
"default": "Warning",
"Function": "Information",
"Azure.Core": "Error",
"Host.Function.Console": "Information"
}
},
"extensions": {
"queues": {
"batchSize": 1,
"newBatchThreshold": 0,
"maxPollingInterval": "00:00:01"
}
},
"extensionBundle": {
"id": "Microsoft.Azure.Functions.ExtensionBundle",
"version": "[4.*, 5.0.0)"
}
}{
"IsEncrypted": false,
"Values": {
"FUNCTIONS_WORKER_RUNTIME": "python",
"AzureWebJobsStorage": "UseDevelopmentStorage=true"
}
}azure-functionsimport json, logging
import azure.functions as func
bp = func.Blueprint()
C = "AzureWebJobsStorage"
@bp.queue_trigger(arg_name="msg", queue_name="shipping", connection=C)
@bp.blob_output(arg_name="shipment", path="shipments/{orderId}.json",
connection=C) # same name on every rerun
def ship_order(msg: func.QueueMessage,
shipment: func.Out[str]) -> None:
oid = msg.get_json()["orderId"] # the message, not the blob
shipment.set(json.dumps({"orderId": oid, "status": "packed"}))
logging.info("shipped %s, attempt %s", oid, msg.dequeue_count)import requests
orders = [{"id": "o-1001", "amount": 25.5},
{"id": "o-1002", "amount": 14.0},
{"id": "o-1001", "amount": 25.5}, # a client retry
{"id": "o-1003", "amount": 0}] # invalid
for order in orders:
r = requests.post("http://localhost:7071/api/orders", json=order)
print(order["id"], r.status_code, r.text)import os, sys
from azure.storage.blob import BlobServiceClient
svc = BlobServiceClient.from_connection_string(
os.environ["AZURE_STORAGE_CONNECTION_STRING"])
for name in sys.argv[1:]:
box = svc.get_container_client(name)
for blob in box.list_blobs():
text = box.download_blob(blob.name).readall().decode()
print(f"{name}/{blob.name}: {text}")$ cd shop_app && fhost start
host started, functions:
place_order: [POST] http://localhost:7071/api/orders
ship_order: queueTrigger
$ python shop.py
o-1001 202 accepted o-1001
o-1002 202 accepted o-1002
o-1001 202 accepted o-1001
o-1003 400 invalid order
$ cd shop_app && fhost wait "Executed 'Functions.ship_order'" 60 3
$ cd shop_app && fhost log | grep shipped
shipped o-1001, attempt 1
shipped o-1002, attempt 1
shipped o-1001, attempt 1
$ python list.py orders shipments
orders/o-1001.json: {"id": "o-1001", "amount": 25.5}
orders/o-1002.json: {"id": "o-1002", "amount": 14.0}
shipments/o-1001.json: {"orderId": "o-1001", "status": "packed"}
shipments/o-1002.json: {"orderId": "o-1002", "status": "packed"}
$ cd shop_app && fhost stop
host stoppedThe three valid calls return 202 and o-1003 gets 400 invalid order. The warehouse function logs shipped three times, yet shipments holds two files, o-1001.json and o-1002.json, because each is named by the order ID.
Queues deliver at least once, so every step is idempotent on the order ID. A message that keeps failing lands in the poison queue instead of vanishing, so alert on it.
If the save and the message must be one atomic step, bindings can't promise that. Then order and message commit in one database transaction, and a relay sends the message on.
Key points to remember
- Timer: six-field NCRONTAB in UTC; no time zone setting on Flex; never run_on_startup in production
- HTTP: auth levels pick the key; keys are not authentication: Entra ID or API Management
- Queue: base64 by default, 5 attempts, then <queue>-poison; at least once
- Output-binding errors can't be caught, and outputs are not one transaction: the SDK for control
- Binding expressions fill names at run time; business-key names keep reruns idempotent
The full script
Here is a Python script that writes every file and runs every command in order with Core Tools and Azurite; run pip install azure-functions azure-functions-durable azure-storage-blob azure-storage-queue azure-data-tables first.
Show the full script that writes the files and runs every step
# ========================================================================
# Azure Functions Interview Q&A #2 - Triggers and bindings in practice
# TechBrothersIT. Names and sample data are invented for teaching.
# Every step below was run with Azure Functions Core Tools 4.16.0 (Functions host 4.x, Python 3.13 worker,
# programming model v2, extension bundle 4.x) and Azurite 3.37.0; the outputs in the video and the blog post are the real outputs.
# To run it yourself (Linux or macOS shell, or WSL on Windows):
# 1. Install Azure Functions Core Tools 4 and Azurite (npm install -g azurite), then start Azurite:
# azurite --skipApiVersionCheck --location ./azurite-data (blob 10000, queue 10001, table 10002)
# 2. pip install azure-functions azure-functions-durable azure-storage-blob azure-storage-queue azure-data-tables
# 3. Set AZURE_STORAGE_CONNECTION_STRING to "UseDevelopmentStorage=true", then run python Functions_Interview_QA_02_Code.py.
# "fhost" in the commands is a small helper written by Step 0 (fhost.py): it runs `func start` in the background,
# waits until the functions are loaded, and prints the host log lines without timestamps and invocation ids.
# Run it in an empty folder and on a freshly started emulator: it creates its files (and any local data
# files) there, and a second run on old data gives different output.
# Steps that restart the emulator say so in a comment: stop and start it by hand at that point.
# ========================================================================
import os, subprocess, time
def write(path, text):
if text is None:
if os.path.exists(path): os.remove(path)
return
os.makedirs(os.path.dirname(path) or ".", exist_ok=True)
with open(path, "w", encoding="utf-8") as f:
f.write(text.strip("\n") + "\n")
def run(cmd, expect_error=False, allow_error=False, env=None):
print("\n$ " + cmd, flush=True)
rc = subprocess.run(cmd, shell=True, env=dict(os.environ, **(env or {}))).returncode
if rc != 0 and not (expect_error or allow_error):
raise SystemExit("stopped: this command was expected to succeed")
# Step 0: the fhost helper and the starting files
write("fhost.py", '"""fhost: run the Azure Functions host (func start) in the background of the current folder, for scripted demos.\n fhost start [port] [-- extra func args] start `func start`, wait until the functions are indexed, print them\n (and any indexing errors)\n fhost wait PATTERN [secs] [count] wait until `count` (default 1) NEW host log lines (not yet shown by\n `fhost log`) match the regex PATTERN (default timeout 60 s)\n fhost log [--all] [--details] [--since-start]\n print the host log lines written since the last `fhost log` (function logs,\n Executing / Executed lines, exceptions); --details also keeps the\n "Trigger Details" lines, --all keeps every line, --since-start starts at the\n first line after the function list. Timestamps, invocation ids, durations and\n other per-run values are removed.\n fhost stop stop the host\nThe log is kept in .fhost.log in the current folder (one host per folder)."""\nimport os, re, signal, subprocess, sys, time\nLOG, PID, OFF, START = \'.fhost.log\', \'.fhost.pid\', \'.fhost.off\', \'.fhost.start\'\nTS = re.compile(r\'\\[\\d{4}-\\d\\d-\\d\\dT[\\d:.]+Z\\] \')\n# host messages to hide (anchored at the start of the cleaned line, so user log lines that merely contain these words stay)\nNOISE = re.compile(r\'^(Worker process started|Host lock lease|Found Python version|Azure Functions Core Tools|Core Tools Version|\'\n r\'Function Runtime Version|For detailed output|Using cached version|When you have network connectivity|\'\n r\'Warning: Unable to download extension|Host started|Job host started|Host initialized|Loading functions metadata|\'\n r\'Reading functions metadata|Starting Host|Initializing Warmup|Generating \\d+ job function|Functions:$|\'\n r\'Debugger listening|Host Status|Starting worker process|Worker failed to load|Retrieving function|\'\n r\'\\d+ functions? (found|loaded)|Successfully (found|loaded|registered)|Application Insights|WARNING: )\')\nDETAILS = re.compile(r\'^Trigger Details:\')\n\ndef clean(l):\n l = TS.sub(\'\', l.rstrip(\'\\n\'))\n l = re.sub(r\', Id=[0-9a-f-]{36}\', \'\', l)\n l = re.sub(r\'Id=[0-9a-f-]{36}\', \'\', l)\n l = re.sub(r\', Duration=\\d+ms\', \'\', l)\n l = re.sub(r\'\\b[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}\\b\', \'<id>\', l)\n l = re.sub(r\'\\b[0-9a-f]{32}\\b\', \'<instance-id>\', l)\n l = re.sub(r\'\\d{4}-\\d\\d-\\d\\dT\\d\\d:\\d\\d:\\d\\d(\\.\\d+)?(Z|[+-]\\d\\d:\\d\\d)?\', \'<time>\', l)\n l = re.sub(r\'"?0x[0-9A-F]{15,16}"?\', \'<etag>\', l)\n l = re.sub(r\'([?&]code=)[^&\\s"]+\', r\'\\1<key>\', l)\n l = re.sub(r\'Threadpool id: \\d+\', \'Threadpool id: <n>\', l)\n l = re.sub(r\'(processUptime\\W+)\\d+\', r\'\\1<n>\', l)\n return l.replace(\' ()\', \'\').rstrip()\n\ndef read_from(off):\n """complete lines from byte offset `off`; returns (lines, new_offset). A glued line ([ts] a [ts] b) is split."""\n if not os.path.exists(LOG): return [], off\n with open(LOG, \'rb\') as f:\n f.seek(off); data = f.read()\n end = data.rfind(b\'\\n\')\n if end < 0: return [], off\n chunk = data[:end + 1].decode(\'utf-8\', \'replace\')\n out = []\n for l in chunk.split(\'\\n\')[:-1]:\n parts = [p for p in re.split(r\'(?=\\[\\d{4}-\\d\\d-\\d\\dT[\\d:.]+Z\\] )\', l) if p.strip()] or [\'\']\n out += parts\n return out, off + end + 1\n\ndef get(f, d=0):\n return int(open(f).read()) if os.path.exists(f) else d\n\ndef filtered(lines, all_=False, details=False):\n out, in_stack, last_exc = [], False, None\n for l in lines:\n raw = TS.sub(\'\', l)\n if in_stack:\n if raw.startswith((\' \', \'\\t\')): continue\n in_stack = False\n c = clean(l)\n if not c: continue\n if c.startswith(\'Stack:\') and not all_: in_stack = True; continue\n if not all_ and (c in (\'Type:\', \'.\') or c == last_exc): continue\n if c.startswith(\'Exception: \'): last_exc = c[len(\'Exception: \'):]\n if all_ or (details and DETAILS.search(c)): out.append(c); continue\n if NOISE.search(c) or DETAILS.search(c): continue\n out.append(c)\n return out\n\ndef start(*args):\n port, extra = \'7071\', []\n if args and args[0] != \'--\': port = args[0]; args = args[1:]\n if args and args[0] == \'--\': extra = list(args[1:])\n if os.path.exists(PID): stop(quiet=True)\n for f in (LOG, OFF, START):\n if os.path.exists(f): os.remove(f)\n out = open(LOG, \'w\')\n p = subprocess.Popen([\'func\', \'start\', \'--port\', port] + extra, stdout=out, stderr=subprocess.STDOUT,\n stdin=subprocess.DEVNULL, start_new_session=True)\n open(PID, \'w\').write(str(p.pid))\n t0 = time.time()\n while time.time() - t0 < 120:\n txt = open(LOG, encoding=\'utf-8\', errors=\'replace\').read()\n if p.poll() is not None:\n print(\'\\n\'.join(filtered(txt.split(\'\\n\'), all_=True)[-30:])); sys.exit(\'host exited\')\n m = re.search(r\'\\nFunctions:\\n(.*?)\\n(For detailed output[^\\n]*\\n)\', txt, re.S)\n if m and \'Worker process started and initialized\' in txt:\n errs = [clean(l) for l in txt[:m.start()].split(\'\\n\')\n if re.search(r\'in error|failed indexing|Error indexing|will be disabled\', l)]\n names = [clean(l).strip() for l in m.group(1).split(\'\\n\') if l.strip()]\n boundary = len(txt[:m.end()].encode(\'utf-8\'))\n open(START, \'w\').write(str(boundary)); open(OFF, \'w\').write(str(boundary))\n time.sleep(1.5) # let triggers start listening\n for e in errs: print(e)\n print(\'host started, functions:\')\n for n in names: print(\' \' + re.sub(r\'http://localhost:\\d+\', \'http://localhost:\' + port, n))\n return\n if not m and re.search(r\'\\n\\[[^\\]]*\\] (Job host started|Host started)\', txt) and \'Worker process started and initialized\' in txt:\n time.sleep(1.5)\n boundary = len(txt.encode(\'utf-8\')); open(START, \'w\').write(str(boundary)); open(OFF, \'w\').write(str(boundary))\n for l in txt.split(\'\\n\'):\n if re.search(r\'in error|failed indexing|is disabled\', l): print(clean(l))\n print(\'host started, no enabled functions listed\'); return\n if re.search(r\'No job functions found|A host error has occurred\', txt):\n time.sleep(1); print(\'\\n\'.join(filtered(txt.split(\'\\n\'), all_=True)[-30:])); stop(quiet=True); sys.exit(\'host error\')\n time.sleep(0.3)\n print(\'\\n\'.join(filtered(open(LOG).read().split(\'\\n\'), all_=True)[-30:])); stop(quiet=True)\n sys.exit(\'host did not start in 120 s\')\n\ndef wait(pat, secs=\'60\', count=\'1\'):\n rx, t0, need = re.compile(pat), time.time(), int(count)\n while time.time() - t0 < float(secs):\n lines, _ = read_from(get(OFF))\n if sum(1 for l in lines if rx.search(clean(l))) >= need: return\n time.sleep(0.2)\n lines, _ = read_from(get(OFF))\n print(\'\\n\'.join(filtered(lines)[-20:])); sys.exit(\'timed out waiting for %r\' % pat)\n\ndef log(all_=False, details=False, since_start=False):\n off = get(START) if since_start else get(OFF)\n lines, new = read_from(off)\n if not since_start or new > get(OFF): open(OFF, \'w\').write(str(new))\n for c in filtered(lines, all_, details): print(c)\n\ndef stop(quiet=False):\n if not os.path.exists(PID): return\n pid = int(open(PID).read())\n for sig in (signal.SIGTERM, signal.SIGKILL):\n try: os.killpg(pid, sig)\n except Exception: break\n for _ in range(50):\n try: os.killpg(pid, 0); time.sleep(0.1)\n except Exception: break\n os.remove(PID)\n if not quiet: print(\'host stopped\')\n\nif __name__ == \'__main__\':\n a = sys.argv[1:] or [\'help\']\n if a[0] == \'start\': start(*a[1:])\n elif a[0] == \'wait\': wait(*a[1:])\n elif a[0] == \'log\': log(\'--all\' in a, \'--details\' in a, \'--since-start\' in a)\n elif a[0] == \'stop\': stop()\n else: print(__doc__)\n')
os.environ["FHOST"] = os.path.abspath("fhost.py") # commands below run it as: python "$FHOST" ...
# Step 1: A nightly timer at 02:00 UTC: the schedule status the host keeps, then a run on demand
write('nightly_app/function_app.py', """\
import logging
import azure.functions as func
app = func.FunctionApp()
@app.timer_trigger(schedule="0 0 2 * * *", arg_name="timer",
run_on_startup=False, use_monitor=True)
def nightly_load(timer: func.TimerRequest) -> None:
if timer.past_due: # a missed run, started late
logging.warning("nightly_load is running late")
logging.info("nightly_load: load yesterday's orders, past_due=%s",
timer.past_due)
""")
write('nightly_app/host.json', """\
{
"version": "2.0",
"logging": {
"logLevel": {
"default": "Warning",
"Function": "Information",
"Azure.Core": "Error",
"Host.Function.Console": "Information"
}
},
"extensions": {
"queues": {
"batchSize": 1,
"newBatchThreshold": 0,
"maxPollingInterval": "00:00:01"
}
},
"extensionBundle": {
"id": "Microsoft.Azure.Functions.ExtensionBundle",
"version": "[4.*, 5.0.0)"
}
}
""")
write('nightly_app/local.settings.json', """\
{
"IsEncrypted": false,
"Values": {
"FUNCTIONS_WORKER_RUNTIME": "python",
"AzureWebJobsStorage": "UseDevelopmentStorage=true"
}
}
""")
write('nightly_app/requirements.txt', """\
azure-functions
""")
write('next_run.py', """\
import json, os
from datetime import datetime
from azure.storage.blob import ContainerClient
hosts = ContainerClient.from_connection_string(
os.environ["AZURE_STORAGE_CONNECTION_STRING"],
"azure-webjobs-hosts") # the host's own container
for blob in hosts.list_blobs(name_starts_with="timers/"):
status = json.loads(hosts.download_blob(blob.name).readall())
nxt = datetime.fromisoformat(status["Next"])
print(blob.name)
print(" next run:", nxt.strftime("%H:%M:%S"), nxt.tzname())
""")
write('run_now.py', """\
import sys
import requests
# Local host: no key needed here (in Azure: the master key)
name = sys.argv[1]
r = requests.post(f"http://localhost:7071/admin/functions/{name}",
json={"input": ""})
print("run", name, "now:", r.status_code)
""")
run('cd nightly_app && python "$FHOST" start')
run('python next_run.py')
run('python run_now.py nightly_load')
run('cd nightly_app && python "$FHOST" wait "Executed \'Functions.nightly_load\'" 30')
run('cd nightly_app && python "$FHOST" log')
run('cd nightly_app && python "$FHOST" stop')
# Step 2: HTTP routes with function and anonymous auth levels: what the local host returns
write('api_app/function_app.py', """\
import json
import azure.functions as func
app = func.FunctionApp(http_auth_level=func.AuthLevel.FUNCTION)
@app.route(route="orders/{order_id}", methods=["GET"],
auth_level=func.AuthLevel.FUNCTION) # key required
def get_order(req: func.HttpRequest) -> func.HttpResponse:
order_id = req.route_params["order_id"] # a string
body = {"id": order_id, "status": "shipped"}
return func.HttpResponse(json.dumps(body),
mimetype="application/json")
@app.route(route="health", methods=["GET"],
auth_level=func.AuthLevel.ANONYMOUS) # no key
def health(req: func.HttpRequest) -> func.HttpResponse:
return func.HttpResponse("ok")
""")
write('api_app/host.json', """\
{
"version": "2.0",
"logging": {
"logLevel": {
"default": "Warning",
"Function": "Information",
"Azure.Core": "Error",
"Host.Function.Console": "Information"
}
},
"extensions": {
"queues": {
"batchSize": 1,
"newBatchThreshold": 0,
"maxPollingInterval": "00:00:01"
}
},
"extensionBundle": {
"id": "Microsoft.Azure.Functions.ExtensionBundle",
"version": "[4.*, 5.0.0)"
}
}
""")
write('api_app/local.settings.json', """\
{
"IsEncrypted": false,
"Values": {
"FUNCTIONS_WORKER_RUNTIME": "python",
"AzureWebJobsStorage": "UseDevelopmentStorage=true"
}
}
""")
write('api_app/requirements.txt', """\
azure-functions
""")
write('call_api.py', """\
import requests
API = "http://localhost:7071"
calls = [("GET", "/api/health", None),
("GET", "/api/orders/o-1001", None),
("GET", "/api/orders/o-1001", "wrong"),
("POST", "/api/orders/o-1001", None)]
for method, path, key in calls:
headers = {"x-functions-key": key} if key else {}
r = requests.request(method, API + path, headers=headers)
tag = key or "-"
print(f"{method:4} {path:19} key={tag:5}", r.status_code, r.text)
keys = requests.get(API + "/admin/functions/get_order/keys").json()
print("get_order keys:", [k["name"] for k in keys["keys"]])
""")
run('cd api_app && python "$FHOST" start')
run('python call_api.py')
run('cd api_app && python "$FHOST" stop')
# Step 3: A queue trigger: three base64 orders run, a plain-text order goes straight to poison
write('queue_app/function_app.py', """\
import json, logging
import azure.functions as func
app = func.FunctionApp()
@app.queue_trigger(arg_name="msg", queue_name="orders",
connection="AzureWebJobsStorage")
def load_order(msg: func.QueueMessage) -> None:
order = json.loads(msg.get_body())
logging.info("load %s, attempt %s", order["id"],
msg.dequeue_count)
""")
write('queue_app/host.json', """\
{
"version": "2.0",
"logging": {
"logLevel": {
"default": "Warning",
"Function": "Information",
"Azure.Core": "Error",
"Host.Function.Console": "Information"
}
},
"extensions": {
"queues": {
"batchSize": 1,
"newBatchThreshold": 0,
"maxPollingInterval": "00:00:01"
}
},
"extensionBundle": {
"id": "Microsoft.Azure.Functions.ExtensionBundle",
"version": "[4.*, 5.0.0)"
}
}
""")
write('queue_app/local.settings.json', """\
{
"IsEncrypted": false,
"Values": {
"FUNCTIONS_WORKER_RUNTIME": "python",
"AzureWebJobsStorage": "UseDevelopmentStorage=true"
}
}
""")
write('queue_app/requirements.txt', """\
azure-functions
""")
write('send_mixed.py', """\
import json, os
from azure.storage.queue import QueueClient, TextBase64EncodePolicy
CONN = os.environ["AZURE_STORAGE_CONNECTION_STRING"]
b64 = QueueClient.from_connection_string( # what Functions expects
CONN, "orders", message_encode_policy=TextBase64EncodePolicy())
b64.create_queue()
for oid in ["o-1001", "o-1002", "o-1003"]:
b64.send_message(json.dumps({"id": oid}))
plain = QueueClient.from_connection_string(CONN, "orders") # plain
plain.send_message(json.dumps({"id": "o-1004"}))
print("sent 3 base64 orders and 1 plain-text order")
""")
write('queues.py', """\
import os
from azure.storage.queue import QueueServiceClient
svc = QueueServiceClient.from_connection_string(
os.environ["AZURE_STORAGE_CONNECTION_STRING"])
for name in ["orders", "orders-poison"]:
q = svc.get_queue_client(name)
count = q.get_queue_properties().approximate_message_count
peek = [m.content for m in q.peek_messages(max_messages=5)]
print(f"{name}: {count} messages {peek}")
""")
run('cd queue_app && python "$FHOST" start')
run('python send_mixed.py')
run('cd queue_app && python "$FHOST" wait "Executed \'Functions.load_order\'" 60 3')
run('cd queue_app && python "$FHOST" wait "Moving message to queue" 60')
run('cd queue_app && python "$FHOST" log')
run('python queues.py')
run('cd queue_app && python "$FHOST" stop')
# Step 4: A table output binding inserts: the second write for the same row key fails after the function returned
write('bind_app/function_app.py', """\
import json
import azure.functions as func
from customers_sdk import bp as sdk_bp
app = func.FunctionApp(http_auth_level=func.AuthLevel.FUNCTION)
app.register_functions(sdk_bp)
@app.route(route="customers", methods=["POST"])
@app.table_output(arg_name="row", table_name="Customers",
connection="AzureWebJobsStorage")
def add_customer(req: func.HttpRequest,
row: func.Out[str]) -> func.HttpResponse:
c = req.get_json()
row.set(json.dumps({"PartitionKey": "shop", "RowKey": c["id"],
"name": c["name"]})) # binding: an insert
return func.HttpResponse(f"saved {c['id']}")
""")
write('bind_app/host.json', """\
{
"version": "2.0",
"logging": {
"logLevel": {
"default": "Warning",
"Function": "Information",
"Azure.Core": "Error",
"Host.Function.Console": "Information"
}
},
"extensions": {
"queues": {
"batchSize": 1,
"newBatchThreshold": 0,
"maxPollingInterval": "00:00:01"
}
},
"extensionBundle": {
"id": "Microsoft.Azure.Functions.ExtensionBundle",
"version": "[4.*, 5.0.0)"
}
}
""")
write('bind_app/local.settings.json', """\
{
"IsEncrypted": false,
"Values": {
"FUNCTIONS_WORKER_RUNTIME": "python",
"AzureWebJobsStorage": "UseDevelopmentStorage=true"
}
}
""")
write('bind_app/requirements.txt', """\
azure-functions
""")
write('bind_app/customers_sdk.py', """\
import logging, os
import azure.functions as func
from azure.core.exceptions import HttpResponseError
from azure.data.tables import TableServiceClient
bp = func.Blueprint()
logging.getLogger("azure").setLevel(logging.WARNING) # quiet SDK logs
tables = TableServiceClient.from_connection_string(
os.environ["AzureWebJobsStorage"]) # one client, reused
customers = tables.get_table_client("Customers") # no I/O at import
@bp.route(route="customers/upsert", methods=["POST"],
auth_level=func.AuthLevel.FUNCTION)
def upsert_customer(req: func.HttpRequest) -> func.HttpResponse:
c = req.get_json()
row = {"PartitionKey": "shop", "RowKey": c["id"],
"name": c["name"]}
try:
customers.upsert_entity(row) # insert or merge
except HttpResponseError as e: # your own handling
return func.HttpResponse(f"retry later ({e.status_code})",
status_code=503)
return func.HttpResponse(f"upserted {c['id']}")
""")
write('call_customers.py', """\
import sys
import requests
path = sys.argv[1] # customers or customers/upsert
for name in sys.argv[2:]:
r = requests.post(f"http://localhost:7071/api/{path}",
json={"id": "c-1", "name": name})
print(f"POST /api/{path} {name!r} -> {r.status_code} {r.text}")
""")
write('rows.py', """\
import os
from azure.data.tables import TableClient
table = TableClient.from_connection_string(
os.environ["AZURE_STORAGE_CONNECTION_STRING"], "Customers")
for e in table.list_entities():
print("Customers row:", e["RowKey"], e["name"])
""")
run('cd bind_app && python "$FHOST" start')
run('python call_customers.py customers Ana "Ana Lee"')
run('cd bind_app && python "$FHOST" wait "Executed \'Functions.add_customer\'" 30 2')
run('cd bind_app && python "$FHOST" log | grep -E "^Executed|_binder|^ErrorCode" | fold -s -w 80')
# Step 5: The SDK version upserts the same customer and handles errors itself
run('python call_customers.py customers/upsert "Ana Lee"')
run('cd bind_app && python "$FHOST" wait "Executed \'Functions.upsert_customer\'" 30')
run('python rows.py')
run('cd bind_app && python "$FHOST" stop')
# Step 6: One function, three output bindings: a good order, a failing order, and a resent order
write('orders_app/function_app.py', """\
import json
import azure.functions as func
app = func.FunctionApp(http_auth_level=func.AuthLevel.FUNCTION)
C = "AzureWebJobsStorage"
@app.route(route="orders", methods=["POST"])
@app.blob_output(arg_name="doc", path="orders/{id}.json",
connection=C)
@app.queue_output(arg_name="msg", queue_name="warehouse",
connection=C)
@app.table_output(arg_name="row", table_name="Orders", connection=C)
def save_order(req: func.HttpRequest, doc: func.Out[str],
msg: func.Out[str],
row: func.Out[str]) -> func.HttpResponse:
order = req.get_json()
doc.set(json.dumps(order)) # 1. blob
msg.set(json.dumps({"orderId": order["id"]})) # 2. queue
row.set(json.dumps({"PartitionKey": "orders", # 3. table
"RowKey": order["id"],
"amount": order["amount"]}))
return func.HttpResponse(f"saved {order['id']}", status_code=201)
""")
write('orders_app/host.json', """\
{
"version": "2.0",
"logging": {
"logLevel": {
"default": "Warning",
"Function": "Information",
"Azure.Core": "Error",
"Host.Function.Console": "Information"
}
},
"extensions": {
"queues": {
"batchSize": 1,
"newBatchThreshold": 0,
"maxPollingInterval": "00:00:01"
}
},
"extensionBundle": {
"id": "Microsoft.Azure.Functions.ExtensionBundle",
"version": "[4.*, 5.0.0)"
}
}
""")
write('orders_app/local.settings.json', """\
{
"IsEncrypted": false,
"Values": {
"FUNCTIONS_WORKER_RUNTIME": "python",
"AzureWebJobsStorage": "UseDevelopmentStorage=true"
}
}
""")
write('orders_app/requirements.txt', """\
azure-functions
""")
write('post_orders.py', """\
import json, sys
import requests
for body in sys.argv[1:]:
r = requests.post("http://localhost:7071/api/orders", data=body)
print("POST", body, "->", r.status_code, r.text)
""")
write('check.py', """\
import json, os
from azure.data.tables import TableClient
from azure.storage.blob import ContainerClient
from azure.storage.queue import QueueClient, TextBase64DecodePolicy
CONN = os.environ["AZURE_STORAGE_CONNECTION_STRING"]
blobs = ContainerClient.from_connection_string(CONN, "orders")
queue = QueueClient.from_connection_string(
CONN, "warehouse", message_decode_policy=TextBase64DecodePolicy())
table = TableClient.from_connection_string(CONN, "Orders")
blob_text = {b.name: blobs.download_blob(b.name).readall().decode()
for b in blobs.list_blobs()}
messages = [json.loads(m.content)["orderId"]
for m in queue.peek_messages(32)]
print("blob orders/ :", blob_text)
print("queue warehouse:", messages)
print("table Orders :",
[(e["RowKey"], e["amount"]) for e in table.list_entities()])
""")
run('cd orders_app && python "$FHOST" start')
run('python post_orders.py \'{"id": "o-1001", "amount": 25.5}\' \'{"id": "o-1002"}\'')
run('python check.py')
run('python post_orders.py \'{"id": "o-1001", "amount": 30.0}\'')
run('python check.py')
run('cd orders_app && python "$FHOST" stop')
# Step 7: Binding expressions: %PICK_QUEUE%, {orderId} from the message, {DequeueCount}, {name} from the blob path
write('expr_app/function_app.py', """\
import csv, io, json, logging
import azure.functions as func
app = func.FunctionApp()
C = "AzureWebJobsStorage"
@app.queue_trigger(arg_name="msg", queue_name="%PICK_QUEUE%",
connection=C) # an app setting
@app.blob_input(arg_name="order", path="orders/{orderId}.json",
connection=C) # from the message
@app.blob_output(arg_name="pick", connection=C,
path="picks/{orderId}-try{DequeueCount}.txt")
def make_pick(msg: func.QueueMessage, order: str,
pick: func.Out[str]) -> None:
pick.set(f"pick list for {json.loads(order)['id']}")
@app.blob_trigger(arg_name="src", path="raw/{name}.csv",
connection=C) # name: no .csv
@app.blob_output(arg_name="dst", path="curated/{name}.json",
connection=C)
def csv_to_json(src: func.InputStream, dst: func.Out[str]) -> None:
rows = list(csv.DictReader(io.StringIO(src.read().decode())))
dst.set(json.dumps(rows))
logging.info("csv_to_json %s: %d rows", src.name, len(rows))
""")
write('expr_app/host.json', """\
{
"version": "2.0",
"logging": {
"logLevel": {
"default": "Warning",
"Function": "Information",
"Azure.Core": "Error",
"Host.Function.Console": "Information"
}
},
"extensions": {
"queues": {
"batchSize": 1,
"newBatchThreshold": 0,
"maxPollingInterval": "00:00:01"
}
},
"extensionBundle": {
"id": "Microsoft.Azure.Functions.ExtensionBundle",
"version": "[4.*, 5.0.0)"
}
}
""")
write('expr_app/local.settings.json', """\
{
"IsEncrypted": false,
"Values": {
"FUNCTIONS_WORKER_RUNTIME": "python",
"AzureWebJobsStorage": "UseDevelopmentStorage=true",
"PICK_QUEUE": "pick-requests"
}
}
""")
write('expr_app/requirements.txt', """\
azure-functions
""")
write('seed.py', 'import json, os\nfrom azure.storage.blob import BlobServiceClient\nfrom azure.storage.queue import QueueClient, TextBase64EncodePolicy\n\nCONN = os.environ["AZURE_STORAGE_CONNECTION_STRING"]\nblobs = BlobServiceClient.from_connection_string(CONN)\n\n\ndef container(name):\n box = blobs.get_container_client(name)\n if not box.exists():\n box.create_container()\n return box\n\n\ncontainer("orders").upload_blob("o-1001.json", json.dumps(\n {"id": "o-1001", "amount": 25.5}), overwrite=True)\npicks = QueueClient.from_connection_string(\n CONN, "pick-requests",\n message_encode_policy=TextBase64EncodePolicy())\npicks.create_queue()\npicks.send_message(json.dumps({"orderId": "o-1001"}))\nraw = container("raw")\nraw.upload_blob("sales_1030.csv", "id,amount\\n1,20.5\\n2,7\\n")\nraw.upload_blob("notes.txt", "not a csv file")\nprint("queued o-1001; uploaded raw/sales_1030.csv and raw/notes.txt")\n')
write('list.py', """\
import os, sys
from azure.storage.blob import BlobServiceClient
svc = BlobServiceClient.from_connection_string(
os.environ["AZURE_STORAGE_CONNECTION_STRING"])
for name in sys.argv[1:]:
box = svc.get_container_client(name)
for blob in box.list_blobs():
text = box.download_blob(blob.name).readall().decode()
print(f"{name}/{blob.name}: {text}")
""")
run('cd expr_app && python "$FHOST" start')
run('python seed.py')
run('cd expr_app && python "$FHOST" wait "Executed \'Functions.(make_pick|csv_to_json)\'" 60 2')
run('cd expr_app && python "$FHOST" log | grep "^Executed" | sort')
run('python list.py picks curated')
run('cd expr_app && python "$FHOST" stop')
# Step 8: Order API: validate, save the order, notify the warehouse; the warehouse function is idempotent
write('shop_app/function_app.py', """\
import json
import azure.functions as func
from warehouse import bp as warehouse_bp
app = func.FunctionApp(http_auth_level=func.AuthLevel.FUNCTION)
app.register_functions(warehouse_bp)
C = "AzureWebJobsStorage"
@app.route(route="orders", methods=["POST"])
@app.blob_output(arg_name="doc", path="orders/{id}.json",
connection=C)
@app.queue_output(arg_name="ship", queue_name="shipping",
connection=C)
def place_order(req: func.HttpRequest, doc: func.Out[str],
ship: func.Out[str]) -> func.HttpResponse:
order = req.get_json()
if order.get("amount", 0) <= 0: # validate first
return func.HttpResponse("invalid order", status_code=400)
doc.set(json.dumps(order)) # save the order
ship.set(json.dumps({"orderId": order["id"]})) # notify warehouse
return func.HttpResponse(f"accepted {order['id']}",
status_code=202)
""")
write('shop_app/host.json', """\
{
"version": "2.0",
"logging": {
"logLevel": {
"default": "Warning",
"Function": "Information",
"Azure.Core": "Error",
"Host.Function.Console": "Information"
}
},
"extensions": {
"queues": {
"batchSize": 1,
"newBatchThreshold": 0,
"maxPollingInterval": "00:00:01"
}
},
"extensionBundle": {
"id": "Microsoft.Azure.Functions.ExtensionBundle",
"version": "[4.*, 5.0.0)"
}
}
""")
write('shop_app/local.settings.json', """\
{
"IsEncrypted": false,
"Values": {
"FUNCTIONS_WORKER_RUNTIME": "python",
"AzureWebJobsStorage": "UseDevelopmentStorage=true"
}
}
""")
write('shop_app/requirements.txt', """\
azure-functions
""")
write('shop_app/warehouse.py', """\
import json, logging
import azure.functions as func
bp = func.Blueprint()
C = "AzureWebJobsStorage"
@bp.queue_trigger(arg_name="msg", queue_name="shipping", connection=C)
@bp.blob_output(arg_name="shipment", path="shipments/{orderId}.json",
connection=C) # same name on every rerun
def ship_order(msg: func.QueueMessage,
shipment: func.Out[str]) -> None:
oid = msg.get_json()["orderId"] # the message, not the blob
shipment.set(json.dumps({"orderId": oid, "status": "packed"}))
logging.info("shipped %s, attempt %s", oid, msg.dequeue_count)
""")
write('shop.py', """\
import requests
orders = [{"id": "o-1001", "amount": 25.5},
{"id": "o-1002", "amount": 14.0},
{"id": "o-1001", "amount": 25.5}, # a client retry
{"id": "o-1003", "amount": 0}] # invalid
for order in orders:
r = requests.post("http://localhost:7071/api/orders", json=order)
print(order["id"], r.status_code, r.text)
""")
write('list.py', """\
import os, sys
from azure.storage.blob import BlobServiceClient
svc = BlobServiceClient.from_connection_string(
os.environ["AZURE_STORAGE_CONNECTION_STRING"])
for name in sys.argv[1:]:
box = svc.get_container_client(name)
for blob in box.list_blobs():
text = box.download_blob(blob.name).readall().decode()
print(f"{name}/{blob.name}: {text}")
""")
run('cd shop_app && python "$FHOST" start')
run('python shop.py')
run('cd shop_app && python "$FHOST" wait "Executed \'Functions.ship_order\'" 60 3')
run('cd shop_app && python "$FHOST" log | grep shipped')
run('python list.py orders shipments')
run('cd shop_app && python "$FHOST" stop')
Part 3: Blob and File Processing
The sample data on this page is invented for teaching. Every terminal output is the real output of the command above it, run with Azure Functions Core Tools 4.16.0 (the real Functions host, Python 3.13 worker) and Azurite 3.37.0 for storage. Features the local host cannot show truthfully are shown as code. Part of the Real Time Azure Functions Interview Questions and Answers series on TechBrothersIT. Features, limits and their status (GA or preview) are current as of November 2026; check the official Azure Functions documentation (learn.microsoft.com/azure/azure-functions) for anything you quote in an interview.



No comments:
Post a Comment
Note: Only a member of this blog may post a comment.