Search code examples
pythonazure-functionshttpresponse

How to pass json data in localhost url in python?


This is HttpTrigger function. where i want to pass binary image in Local host (http://localhost:7071/api/HttpTrigger1) as appending to parameter like below example http://localhost:7071/api/HttpTrigger1//9j/4AAQSkZJRgABAQAAAQABAAD/2wCEAAYGBgYHBgcICAc.......

My code

import base64
import numpy as np
import cv2 as cv


def main(req: func.HttpRequest) -> func.HttpResponse:
    base_64_image_bytes = req.get_body()
    image_bytes = base64.b64decode(base_64_image_bytes)
    img_nparr = np.frombuffer(image_bytes, dtype=np.uint8)
    image = cv.imdecode(img_nparr, cv.IMREAD_COLOR)
    cv.imwrite(TEMP_IMAGE_FILENAME, image)
    return func.HttpResponse("Done", status_code=200)

but base_64_image_bytes is empty. please help me out....


Solution

  • For this problem, you can't put the binary in the request url path. If you want to put the binary as a parameter in request url, you need to use the url like: http://localhost:7071/api/HttpTrigger1?binary=xxxxx. And then you can get the parameter binary in your function with the code:

    def main(req: func.HttpRequest) -> func.HttpResponse:
        binary = req.params.get('binary')
    

    If you use the url which you mentioned in your question: http://localhost:7071/api/HttpTrigger1//9j/4AAQSkZJRgABAQAAAQABAAD/2wCEAAYGBgYHBgcICAc......., it can't trigger your function because your function request url is http://localhost:7071/api/HttpTrigger1 but not http://localhost:7071/api/HttpTrigger1//9j/4AAQSkZJRgABAQAAAQABAAD/2wCEAAYGBgYHBgcICAc........

    And you can also put the binary in the request body of your request. If so, you need to use "Post" method to request your function instead of "Get" method. For example, you request the function with "Post" method and with request body like:

    {
      "binary":"xxxxxx"
    }
    

    Then you can get the binary in your function with the code like:

    req_body = req.get_json()
    binary = req_body.get('binary')