laila
laila

Reputation: 1059

POST request to IBM Watson Relationship extraction returns error

In Bluemix, I am trying to call the IBM Watson relationship extraction API from Python. First off I create an application on Bluemix and bing the relationship extractor api to it. Then from the drop-down menu on the API I get the user name and password from the instantiating credentials. Which in the coe below I have replaced with bluemux-username and bluemix-password. The Python code I wrote for this is as follows:

import requests
import json

url="https://gateway.watsonplatform.net/relationship-extraction-beta/api/v1/sire/0"
username="bluemix_username"
password="bluemix_passowrd"
with open ("data.txt", "r") as myfile:
    text=myfile.read().replace('\n', '')

raw_data = {
    'contentItems' : [{
        'contenttype' : 'text/plain',
        'content': text
    }]
}

input_data = json.dumps(raw_data)


response = requests.post(url, auth=(username, password), headers =   {'content-type': 'application/json'}, data=input_data)
try:
    response.raise_for_status()
except requests.exceptions.HTTPError as e:
    print("And you get an HTTPError: %s"% e.message)

However, when I run this I get the following error:

And you get an HTTPError: 400 Client Error: Bad Request

*Note: I used the same method for the personality insights API and that worked.

Any ideas?

Thanks

Upvotes: 0

Views: 1162

Answers (2)

German Attanasio
German Attanasio

Reputation: 23653

If you don't want to use data.txt and use the standard input in your terminal, you can do:

## -*- coding: utf-8 -*-

import os
import requests
import fileinput

class RelationshipExtractionService:
    url = None

    def __init__(self):
        self.url = "https://gateway.watsonplatform.net/relationship-extraction-beta/api/v1/sire/0"
        self.user = "<username>"
        self.password = "<password>"

    def extract(self, text):
        data = {
            'txt': text,
            'sid': 'ie-en-news',  # English News, for Spanish use: ie-es-news
            'rt': 'xml',
        }

        r = requests.post(self.url,
                          auth=(self.user, self.password),
                          headers = {
                              'content-type': 'application/x-www-form-urlencoded'},
                          data=data
                          )
        print("Request sent. Status code: %d, content-type: %s" %
              (r.status_code, r.headers['content-type']))
        if r.status_code != 200:
            print("Result %s" % r.text)
            raise Exception("Error calling the service.")
        return r.text

if __name__ == '__main__':
    service = RelationshipExtractionService()
    for line in fileinput.input():
        print service.extract(line)

Usage

Simple text analysis:
echo "New York is awesome" | python main.py

You can also pipe a file:
cat article.txt | python main.py

From .txt to .xml:
cat article.txt | python main.py > article.xml

Upvotes: 0

dalelane
dalelane

Reputation: 2765

Here's an updated copy of your code that should work:

import requests
import json

url="https://gateway.watsonplatform.net/relationship-extraction-beta/api/v1/sire/0"
username="bluemix_username"
password="bluemix_passowrd"
with open ("data.txt", "r") as myfile:
    text=myfile.read().replace('\n', '')

input_data = {
    'sid' : 'ie-en-news',
    'txt' : text
}

response = requests.post(url, auth=(username, password), data=input_data)
try:
    response.raise_for_status()
    print response.text
except requests.exceptions.HTTPError as e:
    print("And you get an HTTPError: %s"% e.message)

Basically I changed the payload you were posting to add some missing values.

Hope this helps!

Upvotes: 1

Related Questions