0

I am new to Azure functions and looking for a way to validate the request data received by my POST request.

Is it possible to use pydantic library to perform these validations and if not what is the best way to input validations.

1 Answers1

0

Data validation and settings management using python type annotations.

pydantic enforces type hints at runtime, and provides user friendly errors when data is invalid.

You can use the pydantic library for any validation of the body like:

from  pydantic  import  ValidationError  
try:  
    User(signup_ts='broken',  friends=[1,  2,  'not number'])  
except  ValidationError  as  e:  
    print(e.json())

I have a azure function code which takes POST request and triggers the function. 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,
    )

Check out this GitHub sample of Python POST request: https://github.com/yokawasa/azure-functions-python-samples/tree/master/v2functions/http-trigger-onnx-model