A very common question we receive from our API users is how to call the True Knowledge API using Javascript/AJAX.
The short answer: you don't call the API directly using Javascript, but you can call it indirectly. This post explains why and how to do so.
Why not
The reason for not calling the API directly is because the URL call contains your API account credentials, namely your username and API "password" (the API key if you will). If you embed this information into a web page so that it can call the API directly using Javascript, you will be exposing these credentials: anyone can then find your account details.
Another complication: our API currently outputs only XML, which is not the most Javascript-friendly output.
Solution
So what to do? Proxy the calls via a server-side script on your website. The server-side script, would be written in PHP or Python or your programming language of choice. It will accept, via a query string variable, the actual search, process it, and then return the results to the Javascript.
In detail:
- Create the server side-script; let's call this script tk.php and let's say it is hosted on your website at http://example.com/tk.php. We'll talk about the exact contents of tk.php in a second.
- Using jQuery or any other way to do the AJAX call, request tk.php. For example, if the Javascript wants to call the True Knowledge API to ask "what is the capital of France", the AJAX call could be to:
Here, we're using the query string variable "input" to pass the search to tk.phphttp://example.com/tk.php?input=what+is+the+capital+of+france - Wait for tk.php to call the True Knowledge API and display its output in the page. The exact details of this vary by how you are doing the AJAX call, and most Javascript frameworks like jQuery and Prototype give you an easy way to embed AJAX output into a web page.
What happens on the server
We already have an excellent starting point for tk.php: it is the da.php example in our API PHP library. What we want here is an even simpler version of this file, so we're going to strip it down.
The da.php file calls our Direct Answer API service, which is the easiest to work with for this example. You can certainly build more complicated API calls using a True Knowledge Query API call as detailed in the tkquery.php file in the library examples folder.
The first task is to get rid of the HTML page formatting because the output is going to be embedded into a pre-existing HTML page.
Secondly, you need to decide if you would like the AJAX output to (potentially) show any errors. In the code below, I've commented out anything that does not display a search result.
You'll notice that the code below is printing everything the API returned without any real formatting and basic HTML markup. Of course customize this to your needs.
And with all this said, below is the full code for the tk.php proxy for your AJAX calls.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 | <?php define('API_DIRECTORY', dirname(__FILE__) . '/..'); define('API_ACCOUNT_ID', ''); define('API_ACCOUNT_PW', ''); if(isset($_GET['input'])) { //You should sanitize the input as necessary for your application. $query = $_GET['input']; } if(is_string($query) && strlen($query) > 0) { require_once(API_DIRECTORY.'/api.php'); $request = new KnowledgeEngineDirectAnswerRequest(); $request->setAccountId(API_ACCOUNT_ID); $request->setAccountPassword(API_ACCOUNT_PW); try { $request->setQuery($query); $response = $request->execute(); if(strlen($response->getErrorCode()) > 0) { //NOTE: for this example, we are hiding any errors //echo "<p>Error for query (".$query."):</p>"; //echo "<p>".$response->getErrorCode()." ".$response->getErrorMessage()."</p>"; } else { echo "<p>Answer for ".$query."</p>"; echo "<p>".$response->getTextResult()."</p><hr/>"; if ($results = $response->getResults()) { foreach($results as $result) { echo "<p>True Knowledge ID: ".$result->getId()."</p>"; if($result->getOfficialWebSite()) { echo "<p>Official website: <a href=\"".$result->getOfficialWebSite()."\">".$result->getOfficialWebSite()."</a></p>"; } if($result->getWikiPage()) { echo "<p>Wikipedia page: <a href=\"".$result->getWikiPage()."\">".$result->getWikiPage()."</a></p>"; } if($result->getImage()) { echo "<p>Image: <img src=\"".$result->getImage()."\" /></p>"; } echo "<hr/>"; } } } } catch ( Exception $ex) { //NOTE: for this example, we are hiding any errors //echo $ex->getMessage(); } } |
Comments