3C109 Workshop 4 Rest Client
3C109 Workshop 4 Rest Client
Introduction
The REST client is a document, normally a webpage, that communicates with a REST server using
http GET and POST methods. The REST server will define an API containing a set of commands
and parameters and the Client will send these via the http POST or GET.
In this lab you will write a REST client which will make calls to a REST server (you will be using
http://www.jsontest.com/ as a demonstration). This server allows you to access some basic services
that include: returning your IP address, validating a json string that you’ve made, and returning a
hash of a string that you send it. To do this you will be using the GET and POST methods.
Instructions
To begin create an html document:
<!DOCTYPE html>
<html>
<head>
<script></script>
</head>
<body>
<p id=”id”></p>
<button type="button" onclick="getIp()">Click me to get your ip address.</button>
</body>
</html>
The client can be run directly from your browser, but it is better if it is launched from the server.
You can either copy your files to your htdocs directory on cs2s or if you are running Linux on your
laptop you can use the basic inbuilt php web server by navigating to the folder where your new file
is stored and then using the command:
php -S localhost:8000
You will be able to launch the REST client in your browser by going to
localhost:8000/nameofyourfile.html. If you have another way of hosting these files on your own
laptop, then you can use that, as long as it is able to send http requests.
GET Request
In order to create GET request, the most straightforward method is to make an AJAX
XMLHttpRequest();
This example uses Jsontest.com’s api that allows you to return your IP address, the API is located at
“http://ip.jsontest.com/”. If you go to that webpage in your browser you will see a json string with
an ip address there. That is the data that you want.
In this client you can access this service via button, which when you click it, will send the request.
Here is some example code:
<p id="ip"></p>
<button type="button" onclick="getIp()">Click me to get your ip address.</button>
The onclick = getIP() function will perform the getIp() function when the button is clicked.
}
</script>
The XMLHttpRequest() will send the request over http, note: despite its name can also parse json
as well as xml.
}
}
xhttp.open(“GET”, “http://ip.jsontest.com/”, true);
xhttp.send();
Then it opens your request, with the syntax xhttp.open(“Method”, “url”, asynchronous);
You are recommended to normally use asynchronous communication, i.e. set the parameter to be
true. This allows the webpage to continue with other functions while the request is sent. Otherwise,
the webpage will stall while it waits for the request to finish.
Next, you need your code inside your function() to process what happens each time the state
changes. You only want to do something when you know your request has finished and it has
returned something. You can use an if statement to check the state of your request using the
numbers mentioned above along with the http status, as follows:
Where 200 is the http status code for “OK” meaning if the state of our request is finished and ready.
Then you can perform your code to display your IP address. This is sent in the form of a JSON
string.
The above code is fairly self-explanatory. It parses the this.responseText (which will be whatever
the server returned) as a JSON string, then outputs this using variablename.fieldname (output.ip).
POST Requests
POST requests are very similar to GET requests in terms of how you make a request. You will need
the same set-up as earlier except when the button calls a function, within that function you need to
get the contents of an input tag. You can do this using your own method if you know of a better
way, or simply by doing:
Another change to be made is the method type in the open() function. However, it still maintains
the same format of open(“METHOD”, “url”, async); Another change is that because you are now
sending data, you need to set the proper request headers. You can use the following line to do this:
xhttp.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
And finally you need the data that you are actually sending in the correct format. Typically the
request you are making to the API will accept parameters. For example, when you are sending data
to a form that wants a first name and a second name. send() would look as follows:
xhttp.send("fname=foo&lname=bar");
Exercise 1:
Implement the web service described in the example above, to get the ip address of your computer
and print it out to your web page.
Exercise 2:
This exercises uses the second service provided at jsontest.com, which is a json validation service.
It validates a string to see if it is valid json. This is also a GET request to the service, but it requires
you to append the string you want to validate to the end of the url, so your url should look
something along the lines of http://validate.jsontest.com/?json=YourJsonString;
For the exercise - create a button that, when clicked, will display in a paragraph the result of
http://validate.jsontest.com/?json=
If the json string you give it is invalid it should display what the error is (hint: click on the link for
the url to see what fields will be returned). Otherwise, it should display some text to say that the
json was valid.
Exercise 3:
For this exercise you will need to use the third service provided by jsontest.com. This service
creates an md5 hash of a string that is passed to it.
For this you will need to programme a PUT rather than a GET request and the url for the service is
md5.jsontest.com .
When the hash is returned correctly, have it output what the hash is and what the original word is
that you sent.
Exercise 4:
Now convert your code for examples 1 and 2 from Javascript to JQuery.
function getIp() {
var xhttp = new XMLHttpRequest();
xhttp.onreadystatechange = function() {
if(this.readyState == 4 && this.status == 200) {
var output = JSON.parse(this.responseText);
document.getElementById("ip").innerHTML = output.ip;
}
}
xhttp.open("GET", "http://ip.jsontest.com/", true);
xhttp.send();
}
Is
$(document).ready(function(){
$("#ipButton").click(function(){
$.ajax({
url: "http://ip.jsontest.com/",
type: 'GET',
// data: $(),
success: function(output){
document.getElementById("ip").innerHTML = output.ip;
}});
});
});