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
- Python 3.7 or higher installed
- Azure Functions Core Tools installed
- An Azure subscription
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:
- req.params: A dictionary of URL query parameters.
- req.get_body(): The raw body of the request.
- req.get_json(): Parses the request body as JSON.
- req.headers: A dictionary of request headers.
- req.method: The HTTP method (e.g., 'GET', 'POST').
- req.url: The URL of the request.
Response Object (`func.HttpResponse`)
The HttpResponse object is used to send a response back to the client:
- func.HttpResponse(body=..., status_code=...): Creates an HTTP response.
- body: The content of the response.
- status_code: The HTTP status code (e.g., 200, 400, 404).
- mimetype: The content type of the response (e.g., 'application/json').
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:
- anonymous: No authentication required.
- function: Requires a function key.
- admin: Requires an admin key.
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.