rabeeajaffari.files.wordpress.com€¦  · Web viewTo learn about web services and its various...

18
Department of Software Engineering Mehran University of Engineering and Technology, Jamshoro Course: SW412 – Web Technologies Instructo r Rabeea Jaffari Practical/Lab No. 13 Date CLOs CLO-3: P5 Signature Assessment Score Topic To become familiar with web services using PHP Objectives - To learn about web services and its various types - To learn various data exchange formats: XML and JSON - To learn to program a PHP web service using JSON Lab Discussion: Theoretical concepts and Procedural steps Web service : Web services may be defined as: A web service is a generic term for an interoperable (platform-independent) machine-to-machine software function that is hosted at a network addressable location. Or Web services are web application components that can be published, found, and used on the Web. Or A web service is any piece of software that makes itself available over the internet and uses a standardized XML messaging system. XML is used to encode all communications to a web service. Explanation: As described above, web services are platform-independent or interoperable because they make use of XML as a standard communication format. As all communication is in XML, web services are not tied to any

Transcript of rabeeajaffari.files.wordpress.com€¦  · Web viewTo learn about web services and its various...

Page 1: rabeeajaffari.files.wordpress.com€¦  · Web viewTo learn about web services and its various types . To learn various data exchange formats: XML and JSON. To learn to program a

Department of Software EngineeringMehran University of Engineering and Technology, Jamshoro

Course: SW412 – Web TechnologiesInstructor Rabeea Jaffari Practical/Lab No. 13Date CLOs CLO-3: P5Signature Assessment Score

Topic To become familiar with web services using PHPObjectives - To learn about web services and its various types

- To learn various data exchange formats: XML and JSON

- To learn to program a PHP web service using JSON

Lab Discussion: Theoretical concepts and Procedural steps

Web service : Web services may be defined as:

A web service is a generic term for an interoperable (platform-independent) machine-to-machine software function that is hosted at a network addressable location.

Or

Web services are web application components that can be published, found, and used on the Web.

OrA web service is any piece of software that makes itself available over the internet and uses a standardized XML messaging system. XML is used to encode all communications to a web service.

Explanation: As described above, web services are platform-independent or interoperable because they make use of XML as a standard communication format. As all communication is in XML, web services are not tied to any one operating system or programming language—Java can talk with Perl; Windows applications can talk with Unix applications, Android can talk to PHP, PHP with JSP and so on.

Web services are interoperable because they are built on top of open standards such as TCP/IP, HTTP, Java, HTML, and XML.

Types of web services: There are two types of web services: SOAP Web Services REST Web Services

1. SOAP Web services: SOAP stands for Simple Object Access Protocol and is an XML based protocol. The biggest advantage of using the SOAP Web Service is its own security. SOAP is a technique to send an XML

Page 2: rabeeajaffari.files.wordpress.com€¦  · Web viewTo learn about web services and its various types . To learn various data exchange formats: XML and JSON. To learn to program a

request over the Internet using HTTP protocol (hitting a URL), and in return getting an XML response.

2. REST Web services: The REST stands for Representational State Transfer. REST is not a set of standards or rules, rather it is a style of software architecture. The applications which follow this architecture are referred to as RESTful applications.

Unlike SOAP which targets the actions, REST concerns more on the resources. The REST service locates the resource based on the URL and performs the action based on the transport action verb with HTTP protocol. The various transport actions can be:

Transport operation DescriptionGET Provides a read only access to a

resource.

POST Used to create a new resource.DELETE Used to remove a resource.PUT Used to update an existing resource

or create a new resource.

REST accepts different data formats like, Plain Text, HTML, JSON, XML etc. unlike SOAP which only works with XML.

Note: If we look at the current software industry, you will find that, SOAP is being used in the enterprise applications, generally in the legacy code. Today the world is moving fast towards the RESTful Web Services.More information about types of web services can be found at the link below:

https://www.studytonight.com/rest-web-service/types-of-webservices

Data Exchange Formats :

1. XML: XML stands for eXtensible Markup Language XML is a markup language much like HTML (data in between tags

example <tag>my data</tag> XML is a markup meta-language. A framework for defining other markup

languages XML was designed to describe data (not how to present it) XML tags are NOT predefined. You must define your own tags

Difference between XML and HTML

HTML XMLHTML is for the formatting and presentation of data.

XML is for the storage/structuring of data.

HTML has a fixed set of elements that are defined for a specific function

XML allows users to create their own tags/elements that are dependent on

Page 3: rabeeajaffari.files.wordpress.com€¦  · Web viewTo learn about web services and its various types . To learn various data exchange formats: XML and JSON. To learn to program a

the application(s) that use the data.

HTML can be an XML document (called XHTML).

XML is not necessarily an HTML document

HTML is typically very difficult to parse to share its contained data with an application.

XML provides a standard way of sharing data between disparate systems.

Difference between XML and Relational Databases:

Relational Database XMLRelational databases store lists of similarly structured data. They are used to efficiently store, quickly search/retrieve, and join together different lists of data.Example: A user wants to see everyone who lives in Utah with a zip code of 84108 and drives a blue car. A list of Utah citizens could be joined with the DMV list of cars to quickly produce such a list.

XML typically stores nested hierarchical structures. These nested structures can completely contain all the data for a given item. Example: The same XML document structure can be used to store data about a motorcycle, car, truck, tractor, or tricycle.

XML is not:

A replacement for HTML (but HTML can be generated from XML) A presentation format (but XML can be converted into one) A programming language (but it can be used with almost any language) A network transfer protocol (but XML may be transferred over a

network) A database (but XML may be stored into a database)

Advantages:

Truly Portable Data Easily readable by human users and machines as well Very expressive (semantics near data) Very flexible and customizable (no finite tag set) Easy to use from programs (libs available) Easy to convert into other representations (XML transformation

languages) Many additional standards and tools Widely used and supported

XML Basics: Must begin with XML declaration

Page 4: rabeeajaffari.files.wordpress.com€¦  · Web viewTo learn about web services and its various types . To learn various data exchange formats: XML and JSON. To learn to program a

Must have one unique root element All element tags must have an opening and matching closing end-tag Blank/Empty elements can be coded in a single tag syntax. Example:

<MY_TAG_NAME/> XML element tags are case sensitive All elements must be properly nested All attribute values must be quoted HTML comments are supported

Example: <!--a comment block -->

Example:

<?xml version="1.0" encoding="ISO-8859 1"?><note>

<to>Dr. Isma</to><from>Rabeea</from><heading>Reminder</heading><body>Don't forget to read my paper!</body>

</note>

First line is the xml declaration The second line contains the root element Next four lines are child elements of the root

XML Document Rules: All elements must have a closing tag

E.g. <Name> Shahzad</Name> The tags are case sensitive

<name> Shahzad</name> Elements must be properly nested

<b><i>This text is bold and italic</b></i> (INCORRECT)<b><i>This text is bold and italic</i></b> (CORRECT)

Documents must have a root element

XML Element Naming Rules:XML elements must follow these naming rules:

Names can contain letters, numbers, and other characters Names cannot start with a number or punctuation character Names cannot start with the letters xml (or XML, or Xml, etc) Names cannot contain spaces Any name can be used, no words are reserved

XML Element Best Naming Practices:

Make names descriptive. Names with an underscore separator are nice:<first_name>, <last_name>.

Names should be short and simple, like this: <book_title> not like this:<the_title_of_the_book>.

Page 5: rabeeajaffari.files.wordpress.com€¦  · Web viewTo learn about web services and its various types . To learn various data exchange formats: XML and JSON. To learn to program a

Avoid "-" characters. If you name something "first-name," some software may think you want to subtract name from first.

Avoid "." characters. If you name something "first.name," some software may think that "name" is a property of the object "first.“

Avoid ":" characters. Colons are reserved to be used for something called namespaces (more later).

XML Entity References: Some characters have a special meaning in XML.

For e.g: <message>if salary < 1000 then</message> (same as tag delimiter <>) So, Use entity reference to avoid error

XML Comments:

The syntax for writing comments in XML is similar to that of HTML.For e.g: <!--This is a comment -->

White-space is preserved in XML. HTML truncates multiple white-space characters to one single white-space.

XML Elements: Everything between the start and the end tag is element Element can contain: Other elements, text, attributes, or a mixture of

these<bookstore>

<book category="CHILDREN"><title>Harry Potter</title><author>J K. Rowling</author><year>2005</year><price>29.99</price>

</book><book category="WEB">

<title>Learning XML</title><author>Erik T. Ray</author><year>2003</year><price>39.95</price>

</book></bookstore>

Page 6: rabeeajaffari.files.wordpress.com€¦  · Web viewTo learn about web services and its various types . To learn various data exchange formats: XML and JSON. To learn to program a

XML Attributes:

Attributes provide additional information about an element.E.g: <file type="gif">computer.gif</file>

Attribute values must always be quoted. Either single or double quotes canbe used.

For a person's gender, the person element can be written like this:o <person gender="male">o <person gender='male'>

XML Elements Vs Attributes:

Both examples provide the same information.

<person gender="female"><firstname>Anna</firstname><lastname>Smith</lastname>

</person>

OR

<person><gender>female</gender><firstname>Anna</firstname><lastname>Smith</lastname>

</person>

Examples:

<note date="12/11/2012"><to>Dr. Isma</to><from>Rabeea</from><heading>Reminder</heading><body>Don't forget to read my paper!</body> BAD

</note>

OR<note>

<date>10/11/2012</date><to>Dr. Isma</to><from>Rabeea</from><heading>Reminder</heading><body>Don't forget to read my paper!</body> GOOD

</note>OR

<note>

Page 7: rabeeajaffari.files.wordpress.com€¦  · Web viewTo learn about web services and its various types . To learn various data exchange formats: XML and JSON. To learn to program a

<date><day>10</day><month>01</month><year>2008</year>

</date><to>Dr. Isma</to><from>Rabeea</from><heading>Reminder</heading><body>Don't forget to read my paper!</body> BEST

</note>

XML files are saved with .xml extension.

Well-formed XML: XML created with a correct syntax is called well-formed. You can check if your XML document is correct syntax wise using the URL below:

https://www.xmlvalidation.com/

XML Validation:Even if documents are well-formed they can still contain errors, and those errors can have serious consequences. Hence, in order to check that such XML is valid or not, we use:

DTD or XML Schema

Thus, a "Valid" XML document is also a "Well Formed" XML document, which also conforms to the rules of a Document Type Definition (DTD) or XML Schema but not vice versa.

Document Type Definition (DTD): A Document Type Definition (DTD) defines the legal building blocks of an XML document. It defines the document structure with a list of legal elements and attributes. A DTD can be declared inline inside an XML document, or as an external reference.

Example:

<?xml version="1.0" encoding="ISO-8859-1"?><!DOCTYPE note SYSTEM "Note.dtd"><note date="12/11/2012">

<to>Dr. Isma</to><from>Rabeea</from><heading>Reminder</heading><body>Don't forget to read my paper!</body> BAD

</note>

Page 8: rabeeajaffari.files.wordpress.com€¦  · Web viewTo learn about web services and its various types . To learn various data exchange formats: XML and JSON. To learn to program a

DOCTYPE declaration in the example above is a reference to an external DTD file Note.dtd which is as follows:

<!DOCTYPE note[<!ELEMENT note (to +,from ?,heading,body)><!ELEMENT to (#PCDATA)><!ELEMENT from (#PCDATA)><!ELEMENT heading (#PCDATA)><!ELEMENT body (#PCDATA)>]>

Where: +: At least one occurrence but may be more *: None or more than one ?: Once or not at all |: any one of the option e.g. <!ELEMENT colour(red|blue|green)>

Internal DTD Example: (XML and DTD in the same file)

<?xmlversion = ‘1.0’><!DOCTYPE circle[<!ELEMENT circle><!ATTLIST circle Radius CDATA #REQUIRED>]>

<circle radius =’15’></circle>

PCDATA & CDATA in DTD:

PCDATA (parsed character data): PCDATA is text that WILL be parsed by a parser. The text will be examined by the parser for entities and markupCDATA (character data): CDATA is text that will NOT be parsed by a parser.

XML Schema: W3C supports an XML-based alternative to DTD, called XML Schema. XML Schema

o defines elements that can appear in a documento defines attributes that can appear in a documento defines which elements are child elementso defines the order of child elementso defines the number of child elementso defines whether an element is empty or can include texto defines data types for elements and attributeso defines default and fixed values for elements and attributes

Example: <xs:elementname="note">

<xs:complexType>

Page 9: rabeeajaffari.files.wordpress.com€¦  · Web viewTo learn about web services and its various types . To learn various data exchange formats: XML and JSON. To learn to program a

<xs:sequence><xs:elementname="to" type="xs:string"/><xs:elementname="from" type="xs:string"/><xs:elementname="heading" type="xs:string"/><xs:elementname="body" type="xs:string"/>

</xs:sequence></xs:complexType>

</xs:element>

XML Schema files are saved with .xsd extension.

XML Namespaces:

A name conflict may arise for the context and definition of two XML tags with same name in an XML document as shown below:

<table><tr><td>Apples</td><td>Bananas</td></tr>

</table>

<table><name>African Coffee Table</name><width>80</width><length>120</length>

</table>

Conflict on the definition of <table> tags can be resolved using prefixes as:

<h:table><h:tr><h:td>Apples</h:td><h:td>Bananas</h:td></h:tr>

</h:table>

<f:table><f:name>African Coffee Table</f:name><f:width>80</f:width><f:length>120</f:length>

</f:table>

When using prefixes in XML, a namespace for the prefix must be defined which specifies the location where the definition for the prefix is available. The

Page 10: rabeeajaffari.files.wordpress.com€¦  · Web viewTo learn about web services and its various types . To learn various data exchange formats: XML and JSON. To learn to program a

namespace is defined by the xmlns attribute in the start tag of an element. The namespace declaration ha sthe following syntax:

xmlns:prefix="URI"

<root xmlns:h=”http://www.w3.org/TR/html4/”xmlns:f="http://www.w3schools.com/furniture">

<h:table><h:tr><h:td>Apples</h:td><h:td>Bananas</h:td></h:tr>

</h:table><f:table>

<f:name>African Coffee Table</f:name><f:width>80</f:width><f:length>120</f:length>

</f:table></root>

xs namespace: The xs specified in the XML namespace example at start is also a prefix that refers to the w3schools namespace. Hence, the XML schemas must always be written mentioning the xs prefix along with its namespace as shown below:

xmlns:xs="http://www.w3.org/200 1/XMLSchema“: Indicates that the element and the datatypes are described at the given URL and also indicates that no need to type the entire URL use the xs prefix only

targetNamespace="http://www. w3schools.com”: Indicates that elements defined by thisschema (to, from, ..) come from thegiven URL.

xmlns="http://www.w3schools.com“:Indicates the default namespace elementFormDefault="qualified": Declared elements must be

namespace qualified

Page 11: rabeeajaffari.files.wordpress.com€¦  · Web viewTo learn about web services and its various types . To learn various data exchange formats: XML and JSON. To learn to program a

Difference between DTD and XML Schema:

DTD XML SchemaDTD's are not namespace aware for conflicting tags

XML Schemas are namespace aware and resolve the name conflict of using the same tags

DTDs are not very advanced XML Schemas are richer and more powerful than DTDs

DTDs require a different syntax XML Schemas are written in XMLNo data type support for elements XML Schemas support data typesLess flexible as compared to schemas XML Schemas are extensible to future

additions

2. JSON: JavaScript Object Notation. JSON is a syntax for storing and exchanging data. JSON is text, written with JavaScript object notation. Since JSON is text, and we can convert any object from any programming language into JSON, and send JSON to the server. We can also convert any JSON received from the server into specific programming language objects.

JSON Syntax: JSON syntax is derived from JavaScript object notation syntax: Data is in name/value pairs Data is separated by commas Curly braces hold objects Square brackets hold arrays

JSON Object:

var adam = {"age" : "24","hometown" : "Missoula, MT","gender" : "male"

};

JSON Arrays:

var family = [{ "name" : "Jason", "age" : "24", "gender" : "male"},{ "name" : "Kyle", "age" : "21", "gender" : "male"}];

Page 12: rabeeajaffari.files.wordpress.com€¦  · Web viewTo learn about web services and its various types . To learn various data exchange formats: XML and JSON. To learn to program a

JSON files are saved with .json extension. All programming languages contain methods to encode their objects into JSON and also to decode/parse the JSON objects into their respective syntaxes as described in the next section.

PHP RESTFUL Web service : We can create a RESTful web service using PHP which can be used to transfer data from the server in JSON to any client (such as android app, JSP server, Perl program etc.) which calls it. An example of PHP web service is as follows:

The web service above, fetches the data in name:value pairs from the database using mysqli_fetch_assoc() function into a variable $k. $k is then stored into an array $studentarray using array_push() function to hold data for all the rows returned by the query. Finally, the $studentarray which contains all the students’ data from the database in the form of name:value pairs is converted into json using json_encode() function and is echoed so that this json can be sent to the caller.

This web service can be called by any programming language or platform (such as android app, jsp server, browser, ios app, windows app etc.) that wishes to use this json data.

Associative arrays are used here because they are also name:value pairs and therefore, can be easily converted to json data.

Checking output: We can check the web service created above by calling it from any programming language. However, for ease we would install a browser utility that calls the web service and displays the json data sent by it. In Google chrome, download an extension Servistate which helps us to call any web service and view its output. A snapshot of the call made from this extension to our web service created above is given below:

Page 13: rabeeajaffari.files.wordpress.com€¦  · Web viewTo learn about web services and its various types . To learn various data exchange formats: XML and JSON. To learn to program a
Page 14: rabeeajaffari.files.wordpress.com€¦  · Web viewTo learn about web services and its various types . To learn various data exchange formats: XML and JSON. To learn to program a

Lab TasksSubmission Date: 15-02-19

Part A: Data Exchange Formats:

1. Write your CV as an XML document2. Write an XML document to show data about a department of an institute

and its students3. Check if your above XML documents are well-formed using the urL

https://www.xmlvalidation.com/ and create DTDs and XML Schemas to validate your XML documents.

4. Differentiate between XML and JSON.5. Create a JSON document for university’s map which describes various

departments and their positions in terms of latitudes and longitudes.

Part B: PHP RESTFUL Webservice:

1. Create a web service which takes your name and roll number using GET/POST method, queries a database (containing all student details i.e. name, roll num, address, father’s name, skills, dob, phone number etc.) with your roll number and displays your information in json format. Call and test the web service and attach the output.