Search code examples
pythonazurepostazure-functionsserverless

How to trigger a Azure Function with parameters from a POST request


I need to send a POST request (with user captured data) to azure function and I would like Azure function to use this as parameters and run.

I can see there are many ways to trigger an Azure function in the docoumentation however I have not been able to figure out how to do the above when supplying user input.

For more context I am developing a simple user form where the user enters some data. Once the user clicks submit I will need fire off a POST request to Azure function to carry out some processing.


Solution

  • The data from the submitted form will be a Bytes object. You must convert it to a string and then parse the parameters. This sample code handles the submission of a basic contact info form.

    import logging
    
    import azure.functions as func
    
    from urllib.parse import parse_qs
    
    
    def main(req: func.HttpRequest) -> func.HttpResponse:
        # This function will parse the response of a form submitted using the POST method
        # The request body is a Bytes object
        # You must first decode the Bytes object to a string
        # Then you can parse the string using urllib parse_qs
    
        logging.info("Python HTTP trigger function processed a request.")
        req_body_bytes = req.get_body()
        logging.info(f"Request Bytes: {req_body_bytes}")
        req_body = req_body_bytes.decode("utf-8")
        logging.info(f"Request: {req_body}")
    
        first_name = parse_qs(req_body)["first_name"][0]
        last_name = parse_qs(req_body)["last_name"][0]
        email = parse_qs(req_body)["email"][0]
        cell_phone = parse_qs(req_body)["cell_phone"][0]
    
        return func.HttpResponse(
            f"You submitted this information: {first_name} {last_name} {email} 
            {cell_phone}",
            status_code=200,
        )