def create_request_body()

in projects/vision-ai-edge-camera-client/camera_client.py [0:0]


def create_request_body(image_data, request_body_template):
    """Creates the request body to perform API calls.

    Args:
        image_data: The input image.
        request_body_template (str): Bbody template with placeholders.

    Returns:
        A JSON format string of the request body.
    """
    encoded_string = base64.b64encode(image_data).decode("utf-8")

    # Use json.loads to parse the template string into a Python dictionary
    request_body = json.loads(request_body_template)

    # Define a recursive function to find and replace the placeholder
    def replace_placeholder(data):
        if isinstance(data, dict):
            for key, value in data.items():
                if isinstance(value, str) and "{encoded_string}" in value:
                    data[key] = value.format(encoded_string=encoded_string)
                else:
                    replace_placeholder(value)
        elif isinstance(data, list):
            for _, item in enumerate(data):
                replace_placeholder(item)

    # Call the recursive function to replace the placeholder
    replace_placeholder(request_body)

    return json.dumps(request_body)