Eclipse, Java and a Rest API – An introduction

In this post I want to introduce a few real world tools and programming examples to anyone who is fed up with the hundred-and-one ‘Hello World’ examples.  More often than not, tutorials have little substance and leave students feeling that they want more.  My goal is to introduce several hot-industry topics which could help beginners on the path to becoming a software programmer.

The following is a step-by-step guide for downloading and installing Eclipse and Java.  Once installed we’ll write a little program which takes advantage of a technology call a Rest API.  If you are unfamiliar with these tools and terms, don’t worry.  I’ll do my best to explain.

I want this post to be brief and concise, so let’s get started.

Eclipse

Eclipse is an integrated development environment (IDE).  It’s the tool programmers use to author and compile their code.  Just as a Word Processor such as Microsoft’s Word assists authors to write a books, IDEs include a plethora of features to aid programmers to perform their craft.  Features such as auto-complete and syntactical checking are expected in modern IDEs and Eclipse is no exception.

Java

Here is Oracle official intro, “Java is a programming language and computing platform first released by Sun Microsystems in 1995. It is the underlying technology that powers state-of-the-art programs including utilities, games, and business applications. Java runs on more than 850 million personal computers worldwide, and on billions of devices worldwide, including mobile and TV devices.”

In none-marketing terms, Java is a collection of tools that allow programmers to write code.

RESTful API

In simple terms a RESTful API is a collection of structured web addresses which permit extraction of data from a target website. For example Twitter publishes an API which allows programs to extract details about Tweets.  Here’s another example: imagine an API that allows you to recall data like live soccer scores, league tables or player information.  One of the addresses at the end of the API might be http://mysport.com/api/league-table which would result in the league table being returned to the calling interface, or, http://mysport.com/api/league-info?query=topscorers&limit=10 which would return the top 10 scorers in the league.

Installing the tools

Eclipse can be downloaded from the official site at http://www.eclipse.org/.  The homepage includes a Download link as follows:

Eclipse
Eclipse Homepage

Selecting the “Downloads” link navigates to the URL http://www.eclipse.org/downloads/

Download Image
Download Eclipse

There are a few variants of Eclipse.  Download the “Eclipse IDE for Java Developers”.  Eclipse is cross-platform, meaning the same download can be run on Windows, Apple Mac or Linux.  Due to this the Eclipse download is a zip file and not a traditional set-up routine.  Once downloaded extract the zip file to your chosen location.  In my case, I’m installing Eclipse to c:\eclipse.  It’s wise to avoid spaces in the path to Eclipse.  I recommend placing a short-cut on your quick launch bar to the eclipse.exe file within the extracted directory e.g.

Short-cut

Eclipse includes its own Java compiler; thus, it is not strictly necessary to have a version of the Java Development Kit (JDK) installed on your computer. However, I recommend installing one, as when it comes to distributing your programs to the world the users of your programs will probably use the official Java software from Oracle.

To get Java click the downloads link at http://www.java.com

java-download

Java is supplied as a set-up routine.  Thus, once downloaded run the set-up and navigate through the steps as appropriate.  Once Java is installed you can start Eclipse and we are ready to start coding!

Let’s code

When first executed Eclipse will prompt you for the location of your workspace: this is where Eclipse will, by default, keep your projects:

workspace selection

Keep the default and press OK.  Eclipse will then present its Welcome screen when started:

Welcome page
Eclipse welcome

Close the Welcome page to reveal the workbench:

Eclipse workbench

Eclipse is project driven.  Thus, from the File menu select New->Project->Java Project.  The new project wizard will open:

Eclipse New Java project

Enter the project name as “RestAPITest” and simply click Finish.  Eclipse will create an empty project within the project window:

eclipse-new-empty-projectWe now need to create a file to hold our source-code.  To do this click on the src folder and single-click the the right-mouse button.  From the menu displayed select New->Class.  The class wizard will open:

New class

Complete the fields as shown above and click the Finish button.  Eclipse will create and open a file containing your new source-code.  This will contain the following:

package geeksretreat;

public class HttpGetter {

	/**
	 * @param args
	 */
	public static void main(String[] args) {
		// TODO Auto-generated method stub

	}

}

Java is a classed based programming language. Thus, every bit of source code your write must be included within a class. The above example creates a class called HttpGetter.  A class contains methods which equate to line of source code. It the example above our HttpGetter class contains one method call main. Although this method functions like any other it has a special attribute. The main method acts as the main entry point for a program. Therefore, when we ask Eclipse to run our method we know any code within the main method will be executed first.  Thus, we need to add our code to access the RestAPI.

The RestAPI I intend to use for this example is weather related.  The end-point which our program will extract data from is http://api.geonames.org/weatherIcao?ICAO=LSZH&username=rheh&style=full.  You can browse to this page within any browser:

api-data-result

Let me explain what is a happening here:  The API end-point can be split into two parts: the URL http://api.geonames.org/weatherIcao and the parameters ICAO=LSZH&username=rheh&style=full.  The URL is self explanatory, but, the parameters require further explanation.  The parameter section includes a number of named fields and a related value.  The first of which is given the name ICAO.  The names applied to each parameter must be unique for the call; but, can be arbitrary in nature.  In this case the API creators decided to use the name ICAO, as it best suites the call. In the aviation world, ICAO is the International Civil Aviation Organisation.  One of the things this organisation does is maintain a set of 4-letter codes.  Each code represents an airfield.  For example, in the above example  LSZH is the airfield Zurich Kloten.  Therefore, it becomes quite obvious that the end-point is requesting information about a specific airport.

So how do we automate this request in Java?  We first need to request the URL with the appropriate parameter and then parse the XML to extract the data we require.  The code to do this would look similar to the following:


	public static void main(String[] args) throws Exception {

		String sXML = HttpGetter
				.getDoc("http://api.geonames.org/weatherIcao?ICAO=LSZH&username=rheh&style=full");

		Document dom = HttpGetter.loadXMLFromString(sXML);

		Element el = dom.getDocumentElement();

		System.out.println(HttpGetter.getTextValue(el, "stationName"));
		System.out.println(HttpGetter.getTextValue(el, "temperature"));

	}

That’s only four lines of code. The eagle eyed of you may notice that three methods within are class are called. The first is getDoc(). This function includes the following code:


	public static String getDoc(String urlToRead) {

		URL url;
		HttpURLConnection conn;
		BufferedReader rd;
		String line;
		String result = "";

		try {

			url = new URL(urlToRead);
			conn = (HttpURLConnection) url.openConnection();
			conn.setRequestMethod("GET");

			rd = new BufferedReader(
					new InputStreamReader(conn.getInputStream()));

			while ((line = rd.readLine()) != null) {
				result += line;
			}

			rd.close();

		} catch (Exception e) {

			e.printStackTrace();

		}

		return result;
	}

The source code above, takes the URL provided and requests the page over the HTTP protocol. The result is then returned to the calling interface. In other terms, this is simply doing what a browser would do if you typed the URL into the address bar.

The second function called is loadXMLFromString(). This contains the following code:


	public static Document loadXMLFromString(String xml) throws Exception {
		DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
		DocumentBuilder builder = factory.newDocumentBuilder();
		InputSource is = new InputSource(new StringReader(xml));
		return builder.parse(is);
	}

This function takes the XML returned by the API call and creates a Document object which is returned to the calling interface. A Document object makes it’s easier to handle XML data. The final method call is getTextValue(). This enables us to extract a given value from the XML data. The code for the method is:


	private static String getTextValue(Element ele, String tagName) {
		String textVal = null;
		NodeList nl = ele.getElementsByTagName(tagName);
		if (nl != null && nl.getLength() > 0) {
			Element el = (Element) nl.item(0);
			textVal = el.getFirstChild().getNodeValue();
		}

		return textVal;
	}

That’s the coding complete. On executing the program we can see the output in Eclispe’s console window:

RestAPI

The results show the current temperature in Zurich is negative 4 degrees: cold! That concludes the post and I hope this will help someone learn to program.

Advertisements

5 thoughts on “Eclipse, Java and a Rest API – An introduction

  1. Well explained. Thanks for sharing such useful knowledge. This inspired me to get into Java programming for API calls. I used to write API calls for Databases earlier.
    Could you put the whole code from your Eclipse console into this web page. I am new to programming and I was asked to import various libraries when I tried to use your code as is. Finally there were still few errors which I am unable to debug.

    Thanks
    MAK

    1. It was a good articles for beginners but you didn’t mentioned the types of jars to be in included in your project !

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s