You are on page 1of 9

ITAP3012

Developing Web Applications

Tutorial – 10

March 2022
ITAP3012 Tutorial 10

Individual Assessment:
Weightage: 10%
Report deadline: Week 11

This assessment relates to the following Learning Outcomes:

LO6 Compose service-oriented applications using web services and standard communication
frameworks

Guidelines

Start by putting everything into a folder named “ITAP3012_tutorial10”.

You need to complete the following activities and put all your answer in the Tutorial 10 report (word/pdf)
file and submit on Moodle.

Activity 1
Create a XML file with the <Article> as a root tag. Each article contains the Headline, Author, Para and
each para there is an instrument. Fill all the details and save the file as .xml. Open in the browser and
take the screenshot and save

<ARTICLE>
<HEADLINE> ----------- </HEADLINE>
<AUTHOR>--------------- </AUTHOR>
<PARA>
------------------------------
<INSTRUMENT>------------</INSTRUMENT>
------------------------------
</PARA>
</ARTICLE>

Activity 2

Create a “common.css” file and add styles to your XML file created in Activity 1. You need to add the
following styles
1. The display property for INSTRUMENT is inline and for all other it should be block
2. The font-family for ARTICLE should be serif
3. The text of PARA should be indented 1em.
4. The font style of the INSTRUMENT should be italic.

Copyright © 2022 VIT, All Rights Reserved. 2


ITAP3012 Tutorial 10

You need to add the common.css file to your XML file using following code

<?xml-stylesheet href="common.css"?>
<ARTICLE>
-----------------------------------------
-----------------------------------------
</ARTICLE>

Activity 3
We have created an art.xml file that contain the paintings record and test.html file that Html/JavaScript
code to get the “ID” and “Title” of each painting. Read the code and write the comments for each
JavaScript line. You can use online resources.

//Art.xml //Test.html
<?xml version = "1.0" encoding = "ISO-
8859-1"?> <script>
<art> if(window.XMLHttpRequest){
<painting id="290"> var xmlhttp = new XMLHttpRequest();
<title>Balcony</title> }
<artist> else{
<name>Manet</name> var xmlhttp = new XMLHttpRequest();
<nationality>France</nationality> }
</artist>
<year>1868</year> xmlhttp.open("GeT","art.xml",false);
<medium>Oil on canvas</medium> xmlhttp.send();
</painting> var xmlDoc = xmlhttp.responseXML;
<painting id="192">
<title>The Kiss</title> var paintings =
<artist> xmlDoc.getElementsByTagName("painting");
<name>Klimt</name> if(paintings)
<nationality>Austria</nationality> {

Copyright © 2022 VIT, All Rights Reserved. 3


ITAP3012 Tutorial 10

</artist> for (var i = 0; i<paintings.length; i++)


<year>1907</year> {
<medium>Oil and gold on alert("id = " +
canvas</medium> paintings[i].getAttribute("id"));
</painting>
</art> var title =
paintings[i].getElementsByTagName("title");
if(title)
alert("title = " +
title[0].textContent);
}
}
</script>

Activity 4
Consider the following code that is used to read data from the “art.xml” file discussed in Activity 3. Please
read the code and modify it to a show each painting title, author name, and year

<?php
$filename = 'art.xml';
if(file_exists ($filename)){
$art = simplexml_load_file($filename);

$painting = $art->painting[0];
echo '<h2>'.$painting->title.'</h2>';
echo '<p> By'.$painting->artist->name.'</p>';
echo '<p> ID = '.$painting["id"].'</p>';

echo "<ul>";
foreach ($art->painting as $p) {

Copyright © 2022 VIT, All Rights Reserved. 4


ITAP3012 Tutorial 10

echo '<li>'.$p->title.'</li>';
}
echo '</ul>'; }
else{
exit('Failed to Open '.$filename); }
?>

Activity 5
Consider you have been given the following JSON string.
'{"artist": {"name":"Manet","nationality":"France"}}';

1. Write the PHP code to get the name and nationality of the artist?
2. Write the JavaScript code to get the name and nationality of the artist?

Activity 6
Create a simple REST API in PHP using the instructions given below. You need to complete this activity
and share the screenshots with brief explanation of your final product in the Tutorial 10 report file.

What is REST

REST stands for Representational State Transfer as discussed in the lecture. It is an architectural style
which defines a set of constraints for developing and consuming web services through standard protocol
(HTTP). REST API is a simple, easy to implement and stateless web service. REST can provide output data
in multiple formats such as JavaScript Object Notation (JSON), Extensible Markup Language (XML),
Command Separated Value (CSV) and many other formats.

Working of REST API

To implement CRUD operations REST uses, GET, POST, PUT and delete request. GET is used to retrieve
information. POST is used to create a new record. PUT is used to update the existing record and DELETE
is used to delete an existing record.

The most common output format for REST API is JSON format.

In this activity you will develop a REST API for online transaction payments.

Step 1: Creating REST API

Copyright © 2022 VIT, All Rights Reserved. 5


ITAP3012 Tutorial 10

To create a REST API, follow these steps:


1. Create a Database and Table with Dummy Data
2. Create a Database Connection
3. Create a REST API File

Create a Database

First create a database (make sure the database name is same as your name) and add one table in it called
transactions using the following code.

CREATE DATABASE yourname;

CREATE TABLE IF NOT EXISTS `transactions` (


‘id’ int(20) NOT NULL AUTO_INCREMENT,
‘order_id’ int(50) NOT NULL,
‘amount’ decimal(9,2) NOT NULL,
‘response_code’ int(10) NOT NULL,
‘response_desc’ varchar(50) NOT NULL,
PRIMARY KEY (‘id’),
UNIQUE KEY ‘order_id’ (‘order_id’)
)

You also need to add some dummy data to your transaction table using INSET query.

Connect to a Database

Create a new db.php file and write a database connection code in the file. Use your database credentials
to connect with the database

// Enter your Host, username, password, database below.

$con = mysqli_connect("localhost","root","","yourname");
if (mysqli_connect_errno()){
echo "Failed to connect to MySQL: " . mysqli_connect_error();
die();
}

Create a REST API

Create another file called api.php and add the following script to it. You need to carefully read the
following scrip and identify the purpose of each statement.

<?php

Copyright © 2022 VIT, All Rights Reserved. 6


ITAP3012 Tutorial 10

header("Content-Type:application/json");
if (isset($_GET['order_id']) && $_GET['order_id']!="") {
include('db.php');
$order_id = $_GET['order_id'];
$result = mysqli_query(
$con,
"SELECT * FROM `transactions` WHERE order_id=$order_id");
if(mysqli_num_rows($result)>0){
$row = mysqli_fetch_array($result);
$amount = $row['amount'];
$response_code = $row['response_code'];
$response_desc = $row['response_desc'];
response($order_id, $amount, $response_code,$response_desc);
mysqli_close($con);
}else{
response(NULL, NULL, 200,"No Record Found");
}
}else{
response(NULL, NULL, 400,"Invalid Request");
}

function response($order_id,$amount,$response_code,$response_desc){
$response['order_id'] = $order_id;
$response['amount'] = $amount;
$response['response_code'] = $response_code;
$response['response_desc'] = $response_desc;

$json_response = json_encode($response);
echo $json_response;
}
?>

The above script accepts GET request and return the output in JSON format. As you put all your php files
in ITAP3012_tutorial10, you can get the transaction information using the following URL

http://localhost/ITAP3012_tutorial10/api.php?order_id=12345

Step 2: Consuming REST API

To consume a REST API, follow these steps:


1. Create an HTML form
2. Fetch records

Copyright © 2022 VIT, All Rights Reserved. 7


ITAP3012 Tutorial 10

Create an HTML Form

To create a simple form, you can use the following HTML code

<form action="" method="POST">


<label>Enter Order ID:</label><br />
<input type="text" name="order_id" placeholder="Enter Order ID" required/>
<br /><br />
<button type="submit" name="submit">Submit</button>
</form>

Fetch Records

To fetch the records for this tutorial, make sure CURL is enabled on your web server or on your localhost
when you are testing. You can use the following code to access the records

<?php
if (isset($_POST['order_id']) && $_POST['order_id']!="") {
$order_id = $_POST['order_id'];
$url = "http://localhost/rest/api?order_id=".$order_id;

$client = curl_init($url);
curl_setopt($client,CURLOPT_RETURNTRANSFER,true);
$response = curl_exec($client);

$result = json_decode($response);

echo "<table>";
echo "<tr><td>Order ID:</td><td>$result->order_id</td></tr>";
echo "<tr><td>Amount:</td><td>$result->amount</td></tr>";
echo "<tr><td>Response Code:</td><td>$result->response_code</td></tr>";
echo "<tr><td>Response Desc:</td><td>$result->response_desc</td></tr>";
echo "</table>";
}
?>

Reference
https://www.allphptricks.com/create-and-consume-simple-rest-api-in-php/

Copyright © 2022 VIT, All Rights Reserved. 8


ITAP3012 Tutorial 10

Marking Guide: 10 Marks

Task Description Marks


Questions Completed all the activities from 1-5 5
REST API – Complete activity 6 and showed the understanding of the concepts 5
Web Services by providing relevant screenshots and explanation of their
implementation

Copyright © 2022 VIT, All Rights Reserved. 9

You might also like