Lesson 2 of 4 Serverless APIs with Azure Functions

Building Serverless APIs with HTTP Triggers

This lesson explains HTTP routes and requests, authorization levels and keys, securing APIs properly and handling long-running requests.

Learning outcomes

After completing this lesson, you will be able to:

  • Describe how routes and methods are declared.
  • Compare the authorization levels.
  • Choose between function keys, App Service authentication and API Management.
  • Explain the asynchronous request-reply pattern.

Routes, methods and requests

An HTTP-triggered function is declared with @app.route. The route template sets the URL path, with parameters in braces, and the methods list restricts the HTTP verbs. By default, routes are prefixed with /api, which host.json can change. The function receives an HttpRequest with route_params, params (query string), headers and get_json(), and returns an HttpResponse with a body, status code, headers and MIME type.

@app.route(route="documents/{doc_id}", methods=["GET"])
def get_document(req: func.HttpRequest) -> func.HttpResponse:
    doc_id = req.route_params.get("doc_id")
    include_chunks = req.params.get("chunks") == "true"
    doc = load_document(doc_id, include_chunks)
    if doc is None:
        return func.HttpResponse(status_code=404)
    return func.HttpResponse(json.dumps(doc), mimetype="application/json")

@app.route(route="documents", methods=["POST"])
def create_document(req: func.HttpRequest) -> func.HttpResponse:
    try:
        body = req.get_json()
    except ValueError:
        return func.HttpResponse("Invalid JSON", status_code=400)
    doc_id = save_document(body)
    return func.HttpResponse(json.dumps({"id": doc_id}), status_code=201, mimetype="application/json")

Teams that prefer a web framework can host a FastAPI or other ASGI application inside a function app with func.AsgiFunctionApp, which routes all requests through one HTTP-triggered entry point.

Match the pairs

Reading an HTTP request

Exam skills 3.2.1

Match each part of a request to <code>/api/documents/d-7?chunks=true</code> with how the function reads it.

Log in to try this activity Interactive activities are free with an account.

Authorization levels and keys

Each HTTP function has an authorization level that decides whether callers must present a key.

  • Anonymous: no key is required.
  • Function (the default): a function-specific key or a host key is required, passed in the code query parameter or the x-functions-key header.
  • Admin: the master key is required.

Keys are shared secrets that identify a calling application loosely; they are useful to stop casual access to an endpoint but are not user authentication, cannot express per-user permissions and must be rotated if leaked. Production APIs authenticate callers with App Service authentication (built-in Microsoft Entra ID or other providers, which validates tokens before the function runs), with token validation in code, or by placing Azure API Management in front, which adds token validation, rate limits, quotas and a consistent API surface. The function's own level is then often set to anonymous, with network restrictions so that only API Management can reach it.

Function keys
IdentifiesA calling application, loosely
Extra capabilitiesNone
Best forInternal or test endpoints
Choose when Simple protection from casual calls
App Service authentication
IdentifiesA signed-in user or app through tokens
Extra capabilitiesToken validation without code
Best forApps whose users sign in with Entra ID
Choose when User authentication with least code
API Management in front
IdentifiesCallers through subscriptions and tokens
Extra capabilitiesRate limits, quotas, transformation, versioning
Best forPublic or partner APIs at scale
Choose when Managing a product API surface
Scenario questions

Protecting an HTTP function

Exam skills 3.2.1

Choose how to protect each HTTP-triggered function.

Log in to try this activity Interactive activities are free with an account.

Long-running requests

An HTTP-triggered function must respond within 230 seconds, whatever the function timeout, because of the idle timeout of the load balancer in front of the platform. AI back ends often have operations that take longer, such as summarizing a large document. The standard solution is the asynchronous request-reply pattern.

  1. Accept

    The HTTP function validates the request, writes a job record and a Service Bus message, and returns 202 Accepted with a status URL.

  2. Process

    A Service Bus-triggered function, or a container worker, performs the long work and updates the job record.

  3. Poll or notify

    The client polls the status URL, or receives a callback or event when the job finishes.

The Durable Functions extension implements the same pattern with built-in status endpoints and orchestration state, which suits multi-step workflows.

The following diagram traces a request through the asynchronous request-reply pattern.

The asynchronous request-reply pattern for long summaries. The HTTP function queues the job in Service Bus and returns 202 Accepted with a status URL at once, a queue-triggered function produces the summary, and the caller polls the status URL. No HTTP response has to wait for the summary, so the 230-second HTTP limit no longer applies to the work.
App Service authentication validates the callers' Microsoft Entra tokens.
Put in order

Asynchronous request-reply

Exam skills 3.2.1

Put the steps of the asynchronous request-reply pattern in order.

Log in to try this activity Interactive activities are free with an account.

API behaviour and resilience

Serverless APIs should be stateless, because consecutive requests may reach different instances, and should reuse clients for databases and services across invocations by creating them at module level, outside the function body. CORS settings on the function app allow browser applications from other origins to call the API. On the Flex Consumption plan, HTTP concurrency per instance can be set, which controls how many requests an instance handles before the platform adds instances.

Reuse clients across invocations

Creating a CosmosClient, a database pool or an OpenAI client inside the function body repeats connection set-up on every invocation. Clients created at module level are reused for as long as the instance lives, which cuts latency and avoids exhausting connections.

Spot the bug

A slow serverless API

Exam skills 3.2.1

Find the line that makes every invocation slower than it needs to be.

Log in to try this activity Interactive activities are free with an account.
Worked example

An API that times out

A function exposes POST /api/summaries, which downloads a document and calls a language model to summarize it. Small documents work, but large ones fail with HTTP 502 after about four minutes, although the function app's functionTimeout is set to 30 minutes. Callers are internal applications that already sign in with Microsoft Entra ID.

The failures are the 230-second HTTP limit, which a longer function timeout does not change. The API should use the asynchronous request-reply pattern: return 202 Accepted with a status URL after queuing the job in Service Bus, and let a queue-triggered function perform the summary. Because callers already have Entra ID tokens, App Service authentication should validate them, rather than distributing function keys.

Raising functionTimeout further changes nothing for HTTP. Moving to the Premium plan still has the 230-second HTTP limit. Splitting the document client-side would push complexity to every caller.

Check yourself

Does raising functionTimeout to 30 minutes let an HTTP function take ten minutes to respond?

Show answer

No. HTTP-triggered functions must respond within 230 seconds because of the front-end load balancer's idle timeout. Long work belongs behind a queue with a 202 response.

Exam Tips

Remember for the exam

  • @app.route sets the route and methods; routes are prefixed with /api by default.
  • Authorization levels: anonymous, function (default) and admin; keys are not user authentication.
  • HTTP functions must respond within 230 seconds; use 202 Accepted and a queue for long work.
  • Create SDK clients at module level so they are reused across invocations.