0

I have a function written in Python for IBM cloud. Which return results as json, for the following python dictionaries:

return {"billing_for_org": output1, "billing_for_org2:": output2}

Is there a way to return this data as a CSV file? So when I invoke the api I am able to download the data as CSV file?

NoviceMe
  • 3,126
  • 11
  • 57
  • 117

1 Answers1

1

Here is some sample I tested. Let me know if its what you are looking for.

import sys
import csv
import io

def main(dict):
  output = io.StringIO()
  my_dict = {"billing_for_org": "$100", "billing_for_org2": "$200"}
  w = csv.DictWriter(output, my_dict.keys())
  w.writeheader()
  w.writerow(my_dict)
  return {"body": output.getvalue(), 
  "headers": {'Content-Type': 'text/csv','Content-Disposition':'attachment;filename=myfilename.csv'}}

I am not sure how you are invoking the function as Rest API or Web Action.

I tested above code as web action function and got the result. Please note that extension says http at the end of Url which makes the function to return Non-Default(Json) payloads.

Example Url - https://openwhisk.ng.bluemix.net/api/v1/web/demo_dev/hello-world/helloworld.http

Response Received -

Body:

billing_for_org,billing_for_org2

$100,$200

Headers:

Content-Type →text/csv; charset=UTF-8 Content-Length →45 Connection →keep-alive Content-Disposition →attachment;filename=myfilename.csv

Reference - https://console.bluemix.net/docs/openwhisk/openwhisk_webactions.html#openwhisk_webactions. https://developer.ibm.com/answers/answers/406943/view.html

Imran
  • 5,542
  • 3
  • 23
  • 46
  • When I run above code as web action, I do not get any file downloaded? I just see this as a result: { "body": "billing_for_org,billing_for_org2\r\n$100,$200\r\n", "headers": { "Content-Disposition": "attachment;filename=myfilename.csv", "Content-Type": "text/csv" } } – NoviceMe Dec 25 '18 at 16:42
  • The Url should be ending with .http after function name. Are you hitting it with .json extension?. – Imran Dec 25 '18 at 16:52