search

Welcome, dear reader, to another post of my blog. On this post, we will learn to use Google’s custom search API. With this API, you can make searches using Google’s infrastructure, enriching searching business features, like a web crawler, for example.

Pre-steps

Before we start coding, we need to create the keys to make our authentication with the API. One key is the API key itself and the other one is the search engine key. A search engine key is a key to a search engine you create to pre-filter the types of domains you want to make for your searches, so you dont end up searching sites in chinese, for example, if your application only want sites from England.

To start, access the site https://console.developers.google.com. After inputting our credentials, we get to the main site, where we can create a project, activate/deactivate APIs and generate a API key for the project. This tutorial from Google explain how to create API keys.

On this hands-on, we will use Eclipse Luna and Maven 3.2.1. First, create a Maven project, without a archetype:

After creating our project, we add the dependencies. Instead of offering a Java library for the consumption, Google’s API consists of a URL, which is called by a simple GET execution, and returns a JSON structure. For the return, we will use a JSON API we used on our previous post. First, we add the following dependencies in our pom.xml:

Finally, with the dependencies included, we write our code. In this example, we will make a call to the API for a search with the string “java+android”. The API has a limit usage of 100 results per search – in the free mode -, and uses a pagination format of 10 results per page, so we will make 10 calls to the API. The following code make our example:

As we can see above, we make use of the java.net standard classes to make the calls. Using counters to control the calls for the API. The result when we run the program is a list of sites for the search string printed on the console:

And so we concluded our hands-on. With a simple usage, Google’s custom search API offers a simple but powerful tool in the belt of every developer who need to use a search engine of the internet in his solutions. Thank you for reading, until next time.