Call the Search Endpoint

The Search Endpoint

So what is a search endpoint? A search endpoint is a URL that you use to call SAPI. Currently there is just one search endpoint called intent search. This endpoint supports any type of search query and automatically determines if you're searching for a business type, name or both. We may add more endpoints in the future for specific types of searches.

The URL of the Search endpoint is:

http://api.sensis.com.au/v1/test/search

See also: Searching for more information.

Now that we have an API key, and know the URL of the search endpoint, we can actually perform a search.

Testing It Out

First off, lets do a really simple search using just a web browser. This will prove that you can contact the server and that your API key is working correctly, without all the hassle of having to write any code. Simply navigate to the following URL, replacing '<key>' with your API key:

http://api.sensis.com.au/v1/test/search?key=<key>

If all goes well, you should see a response that looks something like:

{"date":"2017-07-11T14:28:25.549+1000","time":0,"code":400,"message":"The request contained invalid parameters.","validationErrors":["Both query and location are empty."],"count":0}

This is actually an error response, but that's OK! This is expected because the query parameter is required but we didn't specify it. If you don't see a message like the one above, please check that your API key is correct and that you have a working connection to the internet. See the troubleshooting guide for more ideas.

Note: Some browsers don't handle the raw response from the API very well. Please see the Technical Resources section for a list of browsers that are better for the purpose of testing the API.

The response message is encoded in a format called JSON (JavaScript Object Notation). JSON is a popular, lightweight data format that is both easy for humans and computers to read.

See also: Technical Resources for more information.

OK, now that we've proved the API is accessible, lets perform a search. Enter the following URL in your browser (once again, replacing '<key>' with your API key):

http://api.sensis.com.au/v1/test/search?key=<key>&query=cafe&location=melbourne

This will perform a search for cafe and return something like:

{
    "results": [
        {
            "id": "999",
            "name": "Bob's Cafe",
            
            "categories": [
                {
                    id: 1,
                    name: "Cafes"
                }
            ],
            "primaryAddress": {
                "addressLine": "123 Main Street",
                ...
            }
            ...
        }
        ...
    ],
    ...
    "count": 20,
    "totalResults": 19791,
    "date": "2011-02-28T12:01:02.345+1000",
    "time": 10,
    "code": 200,
    "message": "OK" 
    ...
}

Note: This example message has been formatted (indented and line breaks added) and abbreviated for readability. If you're not using a JSON plug-in to format the API output, the response message will probably be all on a single line. This is still valid, but just harder to read.

This message contains the first page of listings returned from the search endpoint.

See also: For more information on the structure of the response see Searching and Listing Schema.

Writing Some Code

We've seen the search endpoint in action, now let's write some code to invoke it.

The first thing we need to do, just as when testing above, is construct a URL to the search endpoint we want to use. In the examples below, the variable query should contain the user-entered search query, location should contain the location to search near and key should contain your API key.

Ruby Example

    # location of the Search API endpoint
    endpoint = "http://api.sensis.com.au/v1/test/search"

    # construct a URL with the query string, escaping any special characters.
    url = "#{endpoint}?key=#{key}&query=#{URI.encode(query)}&location=#{URI.encode(location)}"

Java Example

    // location of the Sensis Search API endpoint
    String endpoint = "http://api.sensis.com.au/v1/test/search";
    
    // construct a URL with the query string, escaping any special characters.
    java.net.URL url = new java.net.URL(endpoint + "?key=" + key + 
            "&query=" + java.net.URLEncoder.encode(query, "UTF-8") +
            "&location=" + java.net.URLEncoder.encode(location, "UTF-8"));

PHP Example

    # location of the Sensis Search API endpoint
    $endpoint = "http://api.sensis.com.au/v1/test/search";

    # construct a URL with the query string, escaping any special characters.
    $url = $endpoint . "?key=" . $key . 
            "&query=" . urlencode($query) . 
            "&location=" . urlencode($location);

Next, we need to actually send a request to the search endpoint. There are a number of ways to do this depending on the language you are using. The examples below show just one fairly simple way.

See also: Examples for complete examples.

Ruby Example

    require 'net/http'
                    
    # call the endpoint, returning the HTTP response
    response = Net::HTTP.get_response(URI.parse(url))

Java Example

    // open connection to the server
    java.net.HttpURLConnection conn = (java.net.HttpURLConnection)url.openConnection();
    conn.connect();

PHP Example

    # create HttpRequest class for calling endpoint
    $request = new HttpRequest($url, HttpRequest::METH_GET);
     
    # call the endpoint, returning the HTTP response
    $response = $request->send();

OK, we've fired off the request and got back a response. The first thing you should always do before trying to get any data from the response is check if the server returned a successful HTTP status code.

SAPI will always return an HTTP 200 (OK) status code if it returned a response. Any other HTTP status indicates that there was an authentication or server problem, and that no JSON response was returned. For example, a validation error will still return an HTTP 200 status code, but the JSON response will contain an error code and description.

See also: Status Codes and Messages for more information.

Ruby Example

    # raise an exception if not an HTTP 200 (OK) response
    response.error! unless response.instance_of? Net::HTTPOK

Java Example

    // ensure HTTP 200 (OK) response
    if (conn.getResponseCode() != java.net.HttpURLConnection.HTTP_OK) {
        throw new RuntimeException(
                "Error calling Search API (HTTP status " + conn.getResponseCode() + ")");
    }

PHP Example

    # ensure HTTP 200 (OK) response       
    if ($response->getResponseCode() != 200) {
        throw new Exception("Server returned error: HTTP " . $request->getResponseCode());
    }

Note: How you report errors really depends on your application and framework. The methods used in the above examples are simple, but are not necessarily good practice in all environments.

Now that we know that a response message was returned, we can start to interpret it. In the JSON response message, there is another field called code that we must check for errors. The search endpoints will return one of two status codes for a successful search:

  • 200 if the entered search query was used and returned some results.
  • 206 if the spell checker was run because the entered query did not return any results.

Any other code means a failure of some kind (see the endpoint's documentation for possible errors and their meanings).

Ruby Example

    require 'rubygems'
    require 'json'

    # convert response using 'JSON implementation for Ruby'
    result = JSON.parse(response.body)
     
    # grab the response code
    code = result["code"]

    # ensure successful status code
    raise "API returned error: #{result["message"]}, code: #{code}" \
            unless code == 200 || code == 206 

Java Example

    // grab the response stream
    java.io.InputStream stream = conn.getInputStream();

    // parse JSON response using the Jackson library
    org.codehaus.jackson.map.ObjectMapper mapper = 
            new org.codehaus.jackson.map.ObjectMapper();
    org.codehaus.jackson.JsonNode root = mapper.readValue(stream, 
            org.codehaus.jackson.JsonNode.class);

    // grab the reponse code and message
    int code = root.get("code").getIntValue();
    String message = root.get("message").getTextValue();

    // ensure successful status code
    if (code != 200 && code != 206) {
        throw new RuntimeException(
                "API returned error: " + message + ", code: " + code);
    }

PHP Example

    # convert the response message to an associative array
    $result = json_decode($response->getBody(), true);
     
    # grab the response code
    $code = $result["code"];

    # ensure successful status code
    if ($code != 200 && $code != 206) {
        throw new Exception("API returned error: " . 
                $result["message"] . ", code: " . $result["code"]);
    }

All that's left to do now is display the listings we got back. Keep reading for some tips on how to do this.

Next: Display the Results.