HTTP Trigger Python

This document explains how to use the HTTP trigger for Azure Functions with Python. The HTTP trigger allows you to invoke your Azure Function via an HTTP request.

Overview

The HTTP trigger binds to HTTP requests, enabling you to build serverless APIs and webhooks. When an HTTP request is received, your Python function is executed. You can define routes, methods, and handle request and response objects.

Prerequisites

Creating an HTTP Trigger Function

You can create a new HTTP trigger function using the Azure Functions Core Tools:


func init MyFunctionProj --python
cd MyFunctionProj
func new --name HttpTriggerPython --template "HTTP trigger" --authlevel "anonymous"
            

Understanding the HTTP Trigger Code

The generated Python code for an HTTP trigger typically looks like this:

import logging import azure.functions as func async def main(req: func.HttpRequest) -> func.HttpResponse: logging.info('Python HTTP trigger function processed a request.') name = req.params.get('name') if not name: try: req_body = req.get_json() except ValueError: pass else: name = req_body.get('name') if name: return func.HttpResponse( f"Hello, {name}. This HTTP triggered function executed successfully.", status_code=200 ) else: return func.HttpResponse( "Please pass a name on the query string or in the request body", status_code=400 )

Request Object (`func.HttpRequest`)

The HttpRequest object provides access to various parts of the incoming HTTP request:

Response Object (`func.HttpResponse`)

The HttpResponse object is used to send a response back to the client:

Example: Handling POST requests

To handle POST requests, you can check the req.method and process the request body:

import logging import azure.functions as func import json async def main(req: func.HttpRequest) -> func.HttpResponse: logging.info('Python HTTP trigger function processed a request.') if req.method == 'POST': try: req_data = req.get_json() message = req_data.get('message') if message: return func.HttpResponse( json.dumps({"response": f"Received message: {message}"}), mimetype="application/json", status_code=200 ) else: return func.HttpResponse( json.dumps({"error": "Missing 'message' in request body"}), mimetype="application/json", status_code=400 ) except ValueError: return func.HttpResponse( json.dumps({"error": "Invalid JSON in request body"}), mimetype="application/json", status_code=400 ) else: return func.HttpResponse( "Please use POST method for this endpoint.", status_code=405 )

Routing

You can define specific routes for your HTTP trigger in the function.json file. For example, to route requests to /api/myroute:

In function.json:


{
  "scriptFile": "__init__.py",
  "bindings": [
    {
      "authLevel": "function",
      "type": "httpTrigger",
      "direction": "in",
      "name": "req",
      "methods": [
        "get",
        "post"
      ],
      "route": "myroute"
    },
    {
      "type": "http",
      "direction": "out",
      "name": "res"
    }
  ]
}
            

Authentication and Authorization

The authLevel property in function.json controls access to your HTTP trigger:

Note: For production environments, it's recommended to use function or admin authentication.

Next Steps

Explore other trigger types and bindings in Azure Functions to build more complex serverless applications.

Related Articles: