0

I have deployed my personality insights service App in Bluemix and I could invoke post command to send the text. I want to save the output of a data to csv, i had gone through the API documentation of Personality API, however i could not understand where i am going wrong. Can any one help me in storing the output to csv file.

Here is the code i have used in Python.

#!/usr/bin/env python
# coding: utf-8

import requests
import json
import csv

response = requests.post("https://gateway.watsonplatform.net/personality-insights/api/v2/profile",
                         auth=("user-id", "password"),
                         headers={"content-type": "application/json", "Accept": "text/csv"},
                         data = "text to be analyzed"
                         )

jsonProfile = json.loads(response.text)

with open('test1234.csv', 'w') as f:
    for row in jsonProfile:
        f.writer(csvfile, delimiter=' ', quotechar='|', quoting=csv.QUOTE_MINIMAL)

Please help me on this.

albert
  • 8,027
  • 10
  • 48
  • 84
Mohanrac
  • 85
  • 6
  • first of all your indentation is all wrong and then, what do you want and what did you get, tell us that. – sadaf2605 Jun 07 '15 at 16:34
  • There are a couple of things wrong: (1) You are sending plain text, but also indicating content-type=application/json; (2) You are getting CSV output, but trying to parse it as JSON; (3) then you try to output this using `csv` library, but that JSON structure (if you called the JSON API) is a nested object - for `for` iterator does not work there that simply. All these are corrected in my response below. – herchu Jun 07 '15 at 21:36

1 Answers1

2

You are already getting CSV data from the request, with the Accept: text/csv request header. All you need is to output this directly to a file, no need of using any library (Personality Insights has already formatted this for you!).

Here is a modified code that works:

response = requests.post("https://gateway.watsonplatform.net/personality-insights"+
                         "/api/v2/profile?headers=True",
     auth = ("userid", "password"),
     headers = {"content-type": "text/plain", "Accept": "text/csv"},
     data = "replace your text here"
     )
with open('personality-insights.csv', 'w') as f:
    print >> f, response.text

Also note the addition of the ?headers=True as query parameter in the URL: this will output the column names -- you will likely find this useful (If you are concatenating outputs of several API calls, then omit this parameter and just get the values as in your original example).

herchu
  • 936
  • 7
  • 24
  • Hi Herchu.. you have a repository for user modelling service, Python on GitHub. Do u have any repositories related to Watson services? – Mohanrac Jun 09 '15 at 06:35
  • Hi Krishna, you can find all the repos related to Watson services here: https://github.com/watson-developer-cloud – Eric S. Bullington Jun 09 '15 at 09:31