Search code examples
javamachine-learningnlpalchemyapi

Using Alchemy Entity Extraction to retrieve JSON output


I am running the EntityTest.java file from the Alchemy API Java SDK which can be found here. The programs works just fine, but it seems there is no way to change output format to JSON.

I have tried executing this code-

// Create an AlchemyAPI object.
        AlchemyAPI alchemyObj = AlchemyAPI.GetInstanceFromFile("api_key.txt");
        
        // Force the output type to be JSON
        AlchemyAPI_NamedEntityParams params = new AlchemyAPI_NamedEntityParams();
        params.setOutputMode("json");

        // Extract a ranked list of named entities for a web URL.
        Document doc = alchemyObj.URLGetRankedNamedEntities("http://www.techcrunch.com/", params);
        System.out.println(getStringFromDocument(doc));

But the code throws a RunTimeException, and prints the following on console-

Exception in thread "main" java.lang.RuntimeException: Invalid setting json for parameter outputMode
    at com.alchemyapi.api.AlchemyAPI_Params.setOutputMode(AlchemyAPI_Params.java:42)
    at com.alchemyapi.test.EntityTest.main(EntityTest.java:29)

Also, here is the setOutputCode method from AlchemyAPI_Params.java file-

public void setOutputMode(String outputMode) {
        if( !outputMode.equals(AlchemyAPI_Params.OUTPUT_XML) && !outputMode.equals(OUTPUT_RDF) ) 
        {
            throw new RuntimeException("Invalid setting " + outputMode + " for parameter outputMode");
        }
        this.outputMode = outputMode;
    }

As is evident from the code, it seems that the only 2 acceptable output formats are XML and RDF. Is that so?? Is there no way the get the output in JSON?

Can anybody please help me out regarding that??


Solution

  • I solved the problem by resorting to a completely different approach. Instead of using the already available Java SDK, I made an HTTP connection to the endpoint of URLGetRankedNamedEntities API, and retrieved the response.

    Here is a code sample that demonstrates how to do this-

    URL urlObj = new URL("http://access.alchemyapi.com/calls/url/URLGetRankedNamedEntities?apikey=" + API_KEY_HERE + "&url=http://www.smashingmagazine.com/2015/04/08/web-scraping-with-nodejs/&outputMode=json");
    System.out.println(urlObj.toString() + "\n");
    
    URLConnection connection = urlObj.openConnection();
    connection.connect();
    
    BufferedReader reader = new BufferedReader(new InputStreamReader(connection.getInputStream()));
    
    String line;
    StringBuilder builder = new StringBuilder();
    while ((line = reader.readLine()) !=  null) {
        builder.append(line + "\n");
    }
    
    System.out.println(builder);
    

    Similar endpoints are avaliable for other APIs as well, which can found here.