Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Azure functions: return JSON object

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

like image 732
maswadkar Avatar asked Jun 13 '19 18:06

maswadkar


People also ask

Can Azure function return json?

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.

Can Azure functions return data?

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.

Where is function json in Azure function?

json file contains runtime-specific configurations and is in the root folder of the function app.


2 Answers

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",
    )
like image 115
brandonbanks Avatar answered Jan 21 '23 20:01

brandonbanks


Better way:

func.HttpResponse.mimetype = 'application/json'
func.HttpResponse.charset = 'utf-8'

return func.HttpResponse(json_object)
like image 38
Fremin Abreu Avatar answered Jan 21 '23 21:01

Fremin Abreu