Consider:
import logging
import azure.functions as func
def main(req: func.HttpRequest) -> func.HttpResponse:
logging.info('Python HTTP trigger function processed a request.')
name = {"test":"jjj"}
return func.HttpResponse(name)
Above is my Azure function (V2) using Python preview.
If I return
func.HttpResponse(f"{name}")
it works, but if I return a dict object it does not.
The error displayed is:
Exception: TypeError: reponse is expected to be either of str, bytes, or bytearray, got dict
Similar to the input, Azure Functions will automatically serialize the IActionResult returned from the bound method to JSON. This means that if you're calling the bound method directly (as we are in a request test), the result will be an instance of IActionResult , not a JSON string.
Using the Azure Function return valueIn languages that have a return value, you can bind a function output binding to the return value: In a C# class library, apply the output binding attribute to the method return value. In Java, apply the output binding annotation to the function method.
json file contains runtime-specific configurations and is in the root folder of the function app.
You need to convert your dictionary to a JSON string using the built-in JSON library - json.dumps.
Then you can set the MIME type (Content-Type) of your function to application/json
. By default Azure functions HttpResponse returns text/plain
Content-Type.
import json
import logging
import azure.functions as func
def main(req: func.HttpRequest) -> func.HttpResponse:
logging.info('Python HTTP trigger function processed a request.')
name = {"test":"jjj"}
return func.HttpResponse(
json.dumps(name),
mimetype="application/json",
)
Better way:
func.HttpResponse.mimetype = 'application/json'
func.HttpResponse.charset = 'utf-8'
return func.HttpResponse(json_object)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With