azure functions: return json object

maswadkar picture maswadkar · Jun 13, 2019 · Viewed 12k times · Source
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 dict object it does not. error displayed is

Exception: TypeError: reponse is expected to be either of str, bytes, or bytearray, got dict

please help.

Answer

brandonbanks picture brandonbanks · Jan 13, 2020

You need to convert your dictionary to a json string using the builtin json library. https://docs.python.org/3/library/json.html#json.dumps

Then you can set the mimetype (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",
    )