Question

How to return array of dictionary in a serverless python function

I was trying to build a function which can return array of dictionaries instead of only one dictionary as per the below tutorial https://github.com/digitalocean/sample-functions-python-jokes I can return

import pyjokes

def main(args):
  joke = pyjokes.get_joke()
  return {
    'body': {
      'response_type': 'in_channel',
      'text': joke
    }
  }

I get this error

{
  "result": {
    "error": "The function did not return a dictionary."
  },
  "size": 54,
  "status": "action developer error",
  "success": false
}

I need something like

return [{
    'body': {
      'response_type': 'test1',
      'text': 'joke'
    }
  },
  {
    'body': {
      'response_type': 'test2',
      'text': 'no-joke'
    }
  }]

is this possible with serverless functions?


Submit an answer


This textbox defaults to using Markdown to format your answer.

You can type !ref in this text area to quickly search our full set of tutorials, documentation & marketplace offerings and insert the link!

Sign In or Sign Up to Answer

These answers are provided by our Community. If you find them useful, show some love by clicking the heart. If you run into issues leave a comment, or add your own answer to help others.

Bobby Iliev
Site Moderator
Site Moderator badge
February 6, 2023

Hi there,

You can have just one body and inside the body you can pass your dictionary, for example:

def main(args):

      # Samle dictionary

      dict = {

            "name": "John",

            "age": 30,

            "city": "New York"

      }

      print(dict)

      return {"body": dict}

The response when you visit/trigger the function will be:

Hope that this helps! Let me know how it goes.

Best,

Bobby

Try DigitalOcean for free

Click below to sign up and get $200 of credit to try our products over 60 days!

Sign up

card icon
Get our biweekly newsletter

Sign up for Infrastructure as a Newsletter.

Sign up
card icon
Hollie's Hub for Good

Working on improving health and education, reducing inequality, and spurring economic growth? We’d like to help.

Learn more
card icon
Become a contributor

You get paid; we donate to tech nonprofits.

Learn more
Welcome to the developer cloud

DigitalOcean makes it simple to launch in the cloud and scale up as you grow – whether you’re running one virtual machine or ten thousand.

Learn more ->
DigitalOcean Cloud Control Panel