Presentation is loading. Please wait.

Presentation is loading. Please wait.

SOAP-based and RESTful Web Services

Similar presentations


Presentation on theme: "SOAP-based and RESTful Web Services"— Presentation transcript:

1 SOAP-based and RESTful Web Services
Claudio Ochoa, PhD Sr Software Intel SEG – UNSL September 2007

2 Agenda Web Services SOAP-based WS Definition
Advantages and reservations Classification: SOAP vs REST SOAP-based WS XML, XSL, XPath, XSLT WSDL/ UDDI SOAP SOA (Service Oriented Architecture) SOA Benefits Demo: Creating and consuming a SOAP-based WS 11/8/2018

3 Agenda (cont’d) RESTful WS AJAX JSON Demo: JSON and REST-WS
The XmlHttpRequest object The HttpRequest object JSON JSON data structures JSON vs XML Benefits and lowlights of JSON Generating and Consuming JSON Demo: JSON and REST-WS 11/8/2018

4 Agenda (cont’d) Mashups Hands On Wrap up Example of mashups
Mashing up a yahoo map object Hands On Consuming a REST-WS Creating/Adding a mashup Wrap up 11/8/2018

5 Agenda Web Services SOAP-based WS Definition
Advantages and reservations Classification: SOAP vs REST SOAP-based WS XML, XSL, XPath, XSLT WSDL/ UDDI SOAP SOA (Service Oriented Architecture) SOA Benefits Demo: Creating and consuming a SOAP-based WS 11/8/2018

6 Need for Web Services Distributed Computing allows sharing information and processing Traditional distributed processing models assume Common environment or architecture (J2EE, COM+) Interoperability is easier to achieve Distributed processing using different platforms, architectures, and dev languages is complicated Interoperability between different systems is key WS are an approach for dealing with this problem 11/8/2018

7 Web Services WS provide a way to access biz or app logic using Internet standard protocols (e.g. HTTP, SMTP, FTP) Organizations already have communication SW and infrastructure needed to support WS What are WS for? Early Internet apps (mail, web sites) helped individuals communicate with each other WS help applications communicate with each other WS allow interoperability across independent processing environments and domains 11/8/2018

8 WS: advantages Interaction between different companies systems
Interoperation between apps inside a company Processing is loosely coupled No need for common application environment Do not abandon existing investments in software Add WS front end to existing apps Big players (Microsoft, IBM, Sun) are investing in WS and creating tools to support them 11/8/2018

9 WS: reservations WS are not proven technology SOAP WS rely on XML
Fashionable solution of the day? SOAP WS rely on XML XML expands the size of data several times over More processing is needed to format and parse msgs Internal apps are now exposed to external threats WS can expose valuable corporate data, apps, systems… 11/8/2018

10 WS: Classification WS can be classified in two main kinds
SOAP-based WS RESTful WS SOAP-based WS have been around for a while Google (except blogger), enterprise software RESTful WS are the trendy way for designing WS Yahoo, Flickr, del.icio.us, pubsub, bloglines, technorati eBay and Amazon use both REST and SOAP 11/8/2018

11 SOAP-based WS: overview
SOAP is a protocol for exchanging XML-based messages over computer networks SOAP stands for SOAP Originally stood for Simple Object Access Protocol Later stood for Service Oriented Architecture Protocol Provides a basic messaging framework Successor of XML-RPC (still used for some apps like blogger) Makes use of Internet transport protocol (HTTP/SMTP) 11/8/2018

12 SOAP-based WS (cont’d)
Web Services building blocks Web services SOAP UDDI WSDL XML HTTP SMTP FTP Internet Protocols 11/8/2018

13 Advantages of SOAP WS Easier communication behind proxies and firewalls than previous remote execution technology. Versatile - allows the use of different transport protocols. Easy to consume (sometimes) Rigid - type checking, adheres to a contract Development tools 11/8/2018

14 RESTful WS REST stands for Representational State Transfer
Collection of network architecture principles that outline how resources are defined and addressed All resources can be uniquely identified by an URI No need for additional message layer like SOAP An application interacts with a resource by knowing the identifier of the resource the action required No need to know if there are caches, proxies, gateways, firewalls, tunnels between client and server... The application needs to understand the format of the information (representation) returned, HTML, XML, JSON, images… 11/8/2018

15 Advantages of Restful WS
Lightweight - not a lot of extra xml markup Human Readable Results Improved response times and server loading characteristics Improves server scalability by reducing the need to maintain communication state. different servers can be used to handle initial and subsequent requests A single browser can access any any resource Easy to build, no toolkits required Does not require a separate resource discovery mechanism 11/8/2018

16 Agenda Web Services SOAP-based WS Definition
Advantages and reservations Classification: SOAP vs REST SOAP-based WS XML, XSL, XPath, XSLT WSDL/ UDDI SOAP SOA (Service Oriented Architecture) SOA Benefits Demo: Creating and consuming a SOAP-based WS 11/8/2018

17 SOAP-based Web Services
Web services are application components Web services communicate using open protocols Web services are self-contained and self-describing Web services can be discovered using UDDI Web services can be used by other applications (Interoperability) XML is the basis for SOAP-Web services Web services and the service-oriented architecture (SOA) Understanding services The concept of services within an application has been around for a while. Services, much like components, are intended to be independent building blocks that collectively represent an application environment. Unlike traditional components, though, services have a number of unique characteristics that allow them to participate as part of a service-oriented architecture. One of these qualities is complete autonomy from other services. This means that each service is responsible for its own domain, which typically translates into limiting its scope to a specific business function (or a group of related functions). This design approach results in the creation of isolated units of business functionality loosely bound together by a common compliance to a standard communications framework. Due to the independence that services enjoy within this framework, the programming logic they encapsulate does not need to comply to any one platform or technology set. Web services have two types of uses. Reusable application components There are things different applications needs very often. So why make these over and over again? Web services can offer application components like currency conversion, weather reports or even language translation as services. Ideally, there will only be one type of each application component, and anyone can use it in their application. Connect existing software Web services help solve the interoperability problem by giving different applications a way to link their data. Using Web services you can exchange data between different applications and different platforms. 11/8/2018

18 XML Overview XML stands for eXtensible Markup Language.
XML is a markup language much like HTML. XML tags are not predefined. XML uses a Document Type Definition (DTD) or an XML Schema to describe the data. XML with a DTD is designed to be self-descriptive. XML was designed to store, carry, describe and exchange data. 11/8/2018

19 <price> 123.45 </price>
XML elements Begin with a start tag and end with an end tag Unlike html, every start tag must have a matching end tag XML elements can be nested <price> </price> <book> <title> Web Services </title> <author> <firstname>John</firstname> <lastname> Doe </lastname> </author> <isbn> </isbn> </book> 11/8/2018

20 XML Syntax XML documents use a self-describing and simple syntax.
<?xml version="1.0" encoding="ISO "?> <note> <to>Juan</to> <from>Pedro</from> <heading>Reminder</heading> <body>Don't forget me this weekend!</body> </note> XML elements are extensible. <note> <date> </date> <to>Juan</to> <from>Pedro</from> <heading>Reminder</heading> <body>Don't forget me this weekend!</body> </note> The syntax rules of XML are very simple and very strict. The rules are very easy to learn, and very easy to use. Because of this, creating software that can read and manipulate XML is very easy. The first line in the document - the XML declaration - defines the XML version and the character encoding used in the document. In this case the document conforms to the 1.0 specification of XML and uses the ISO (Latin-1/West European) character set. The next line describes the root element of the document (like it was saying: "this document is a note"): <note> The next 4 lines describe 4 child elements of the root (to, from, heading, and body): <to>Tove</to> <from>Jani</from> <heading>Reminder</heading> <body>Don't forget me this weekend!</body> And finally the last line defines the end of the root element:</note> Can you detect from this example that the XML document contains a Note to Tove from Jani? Don't you agree that XML is pretty self-descriptive? All XML elements must have an opening and a closing tag XML tags are case sensitive All XML elements must be properly nested All XML documents must have a root element (single) There is nothing special about XML There is nothing special about XML. It is just plain text with the addition of some tags enclosed in angle brackets. Software that can handle plain text can also handle XML. In a simple text editor, the XML tags will be visible and will not be handled specially. In an XML-aware application however, the XML tags can be handled specially. The tags may or may not be visible, or have a functional meaning, depending on the nature of the application. XML Elements are Extensible Let's imagine that we created an application that extracted the <to>, <from>, and <body> elements from the XML document to produce a given output. Imagine that the author of the XML document added some extra information to it: The application should still be able to find the <to>, <from>, and <body> elements in the XML document and produce the same output. “XML documents are Extensible”. XML Elements have Relationships Elements are related as parents and children. Elements have Content Elements can have different content types. An XML element is everything from (including) the element's start tag to (including) the element's end tag. An element can have element content, mixed content, simple content, or empty content. An element can also have attributes. In the example above, book has element content, because it contains other elements. Chapter has mixed content because it contains both text and other elements. Para has simple content (or text content) because it contains only text. Prod has empty content, because it carries no information. In the example above only the prod element has attributes. The attribute named id has the value "33-657". The attribute named media has the value "paper".  XML Elements have simple naming rules Names can contain letters, numbers, and other characters Names must not start with a number or punctuation character Names must not start with the letters xml (or XML, or Xml, etc) Names cannot contain spaces 11/8/2018

21 XML Attributes XML elements can have attributes.
Attributes are used to provide additional information about elements. Data can be stored in child elements or in attributes. <person sex="female"> <firstname>Anna</firstname> <lastname>Smith</lastname> </person> <person> <sex>female</sex> <firstname>Anna</firstname> <lastname>Smith</lastname> </person> Attribute values must always be enclosed in quotes, but either single or double quotes can be used. For a person's sex, the person tag can be written like this: In the first example sex is an attribute. In the last, sex is a child element. Both examples provide the same information. There are no rules about when to use attributes, and when to use child elements. My experience is that attributes are handy in HTML, but in XML you should try to avoid them. Use child elements if the information feels like data. Should you avoid using attributes? Some of the problems with using attributes are: attributes cannot contain multiple values (child elements can) attributes are not easily expandable (for future changes) attributes cannot describe structures (child elements can) attributes are more difficult to manipulate by program code attribute values are not easy to test against a Document Type Definition (DTD) - which is used to define the legal elements of an XML document If you use attributes as containers for data, you end up with documents that are difficult to read and maintain. Try to use elements to describe data. Use attributes only to provide information that is not relevant to the data. Sometimes we assign ID references to elements. These ID references can be used to access XML elements in much the same way as the NAME or ID attributes in HTML. So a good way here is that metadata (data about data) should be stored as attributes, and that data itself should be stored as elements 11/8/2018

22 XML Validation Well Formed vs Valid XML
A Well Formed XML document has correct XML syntax. <?xml version="1.0" encoding="ISO "?> <note> <to>Tove</to> <from>Jani</from> <heading>Reminder</heading> <body>Don't forget me this weekend!</body> </note> A Valid XML document also conforms to a DTD. <?xml version="1.0" encoding="ISO "?> <!DOCTYPE note SYSTEM "InternalNote.dtd"> <note> <to>Tove</to> <from>Jani</from> <heading>Reminder</heading> <body>Don't forget me this weekend!</body> </note> A DTD defines the legal elements of an XML document. The purpose of a DTD is to define the legal building blocks of an XML document. It defines the document structure with a list of legal elements. XML Schema is an XML based alternative to DTD. W3C supports an alternative to DTD called XML Schema 11/8/2018

23 XML – Other basic concepts
XML Namespaces Provide a method to avoid element name conflicts. XML Encoding: Allow representing extended or foreign characters XML Parsers: Provide a way to create and manipulate an XML document. XML CDATA: Provide a way to store text data which is ignored by the parser. 11/8/2018

24 XSL languages XSL stands for EXtensible Stylesheet Language
CSS = HTML Style Sheets XSL = XML Style Sheets XSL started as a way to describe how XML data should be displayed, but rapidly evolved to 3 main languages: XSLT - a language for transforming XML documents XPath - a language for navigating in XML documents XSL-FO - a language for formatting XML documents It started with XSL and ended up with XSLT, XPath, and XSL-FO. CSS = HTML Style Sheets HTML uses predefined tags and the meaning of the tags are well understood. The <table> element in HTML defines a table - and a browser knows how to display it. Adding styles to HTML elements is simple. Telling a browser to display an element in a special font or color, is easy with CSS.  XSL = XML Style Sheets XML does not use predefined tags (we can use any tag-names we like), and the meaning of these tags are not well understood. A <table> element could mean an HTML table, a piece of furniture, or something else - and a browser does not know how to display it. XSL describes how the XML document should be displayed! XSL - More Than a Style Sheet Language XSL consists of three parts: XSLT - a language for transforming XML documents XPath - a language for navigating in XML documents XSL-FO - a language for formatting XML documents Due XSLT uses xPath to navigate the XML document, we should start by xPath introduction first 11/8/2018

25 XPath Language for finding information in an XML document.
Is used to navigate through elements and attributes in an XML document. Syntax for defining parts of an XML document. Library of standard functions. W3C Standard. XPath is a language for finding information in an XML document. XPath is used to navigate through elements and attributes in an XML document. XPath Path Expressions XPath uses path expressions to select nodes or node-sets in an XML document. These path expressions look very much like the expressions you see when you work with a traditional computer file system. XPath Standard Functions XPath includes over 100 built-in functions. There are functions for string values, numeric values, date and time comparison, node and QName manipulation, sequence manipulation, Boolean values, and more. XPath is Used in XSLT XPath is a major element in the XSLT standard. Without XPath knowledge you will not be able to create XSLT documents. XQuery and XPointer are both built on XPath expressions. XQuery 1.0 and XPath 2.0 share the same data model and support the same functions and operators. XPath is a W3C Standard XPath became a W3C Recommendation 16. November 1999. XPath was designed to be used by XSLT, XPointer and other XML parsing software 11/8/2018

26 XPath Nodes In XPath, XML documents are treated as trees of nodes. There are seven types of nodes: Document (root) Element Attribute Text Namespace Processing-instruction Comment <?xml version="1.0" encoding="ISO "?> <bookstore> <book> <title lang="en">Harry Potter</title> <author>J K. Rowling</author> <year>2005</year> <price>29.99</price> </book> </bookstore Nodes In XPath, there are seven kinds of nodes: element, attribute, text, namespace, processing-instruction, comment, and document (root) nodes. XML documents are treated as trees of nodes. The root of the tree is called the document node (or root node). Example: <bookstore> (document node) <author>J K. Rowling</author> (element node) lang="en" (attribute node) Atomic values Atomic values are nodes with no children or parent. Example of atomic values: J K. Rowling"en"Items Items are atomic values or nodes. Relationship of Nodes Parent Each element and attribute has one parent. In the example; the book element is the parent of the title, author, year, and price. Children Element nodes may have zero, one or more children. In the example; the title, author, year, and price elements are all children of the book element. Siblings Nodes that have the same parent Ancestors A node's parent, parent's parent, etc. Descendants A node's children, children's children, etc. 11/8/2018

27 XPath Syntax XPath uses path expressions to select nodes or node-sets in an XML document. Path Expression Result /bookstore/* Selects all the child nodes of the bookstore element //* Selects all elements in the document Selects all title elements which have any attribute XPath wildcards can be used to select unknown XML elements. XPath uses path expressions to select nodes or node-sets in an XML document. The node is selected by following a path or steps. Selecting Nodes XPath uses path expressions to select nodes in an XML document. The node is selected by following a path or steps. The most useful path expressions are listed below: In the table below we have listed some path expressions and the result of the expressions: Path ExpressionResult /bookstore/* Selects all the child nodes of the bookstore element //* Selects all elements in the document Selects all title elements which have any attribute Wildcard Description * Matches any element node @* Matches any attribute node node() Matches any node of any kind 11/8/2018

28 XSLT basics XSLT is a language for transforming XML docs into XHTML documents or to other XML documents. XSLT stands for XSL Transformations XSLT is the most important part of XSL XSLT uses XPath to navigate in XML documents XSLT is a W3C Recommendation XSLT is a language for transforming XML documents into XHTML documents or to other XML documents. XSLT = XSL Transformations XSLT is the most important part of XSL. XSLT is used to transform an XML document into another XML document, or another type of document that is recognized by a browser, like HTML and XHTML. Normally XSLT does this by transforming each XML element into an (X)HTML element. With XSLT you can add/remove elements and attributes to or from the output file. You can also rearrange and sort elements, perform tests and make decisions about which elements to hide and display, and a lot more. A common way to describe the transformation process is to say that XSLT transforms an XML source-tree into an XML result-tree. XSLT Uses XPath XSLT uses XPath to find information in an XML document. XPath is used to navigate through elements and attributes in XML documents. How Does it Work? In the transformation process, XSLT uses XPath to define parts of the source document that should match one or more predefined templates. When a match is found, XSLT will transform the matching part of the source document into the result document. 11/8/2018

29 Web Services Operations
Requestors query registry to discover a set of services that it can interact with Providers advertise their services to service registry Service Registry find publish Service Requestor Service Provider bind Requestors negotiate with providers to access and invoke services 11/8/2018

30 XML Web Services Framework
The most widely accepted and successful type of service is the XML Web service (from hereon referred to as Web service or, simply, service). This type of service has two fundamental requirements: it communicates via Internet protocols (most commonly HTTP) it sends and receives data formatted as XML documents That's pretty much it. You can write a simple ASP or JSP script that resides on a Web server sending and receiving XML formatted messages via HTTP, and you can go out and get yourself an "I'm Service-Oriented" T-shirt. Broad acceptance of the Web service design model has resulted in the emergence of a set of supplementary technologies that have become de facto standards. An industry standard Web service, therefore, generally is expected to: provide a service description that, at minimum, consists of a WSDL document be capable of transporting XML documents using SOAP over HTTP These technologies do not alter the core functionality of a Web service as much as they do its ability to represent itself and communicate in a standard way. Many of the architectural conventions expressed in this chapter assume that SOAP and WSDL are part of the described Web services framework. Additionally, it is common for Web services to: be able to act as both the requestor and provider of a service be registered with a discovery agent through which they can be located In a typical conversation with a Web service, the client initiating the request is a Web service as well. Any interface exposed by this "client service" also qualifies it as a service from which other services can request information. Therefore, Web services do not fit into the classic client-server model. Instead, they tend to establish a peer-to-peer system, where each service can play the role of client or server. 11/8/2018

31 SOAP SOAP is a simple XML based protocol to let applications exchange information over HTTP. Stands for Simple Object Access Protocol. Protocol for accessing a Web Service. Platform and language independent. Allows you to get around firewalls. A SOAP message MUST be encoded using XML A SOAP message MUST use the SOAP Envelope namespace A SOAP message MUST use the SOAP Encoding namespace A SOAP message must NOT contain a DTD reference A SOAP message must NOT contain XML Processing Instructions <soap:Envelope xmlns:soap=" soap:encodingStyle=" <soap:Header> </soap:Header> <soap:Body> <soap:Fault> </soap:Fault> </soap:Body> </soap:Envelope> 11/8/2018

32 SOAP Envelope – Header element
The optional SOAP Header element contains application specific information (like authentication, payment, etc) about the SOAP message. If the Header element is present, it must be the first child element of the Envelope element. 11/8/2018

33 SOAP Envelope – Body element
The required SOAP Body element contains the actual SOAP message intended for the ultimate endpoint of the message. SOAP Request Envelope SOAP Response Envelope <?xml version="1.0" encoding="UTF-8" ?> <soapenv:Envelope xmlns:xsd=" xmlns:xsi=" <soapenv:Body> <ns0:getBalance xmlns:ns0=" soapenv:encodingStyle=" <accountId xsi:type="xsd:int">1</accountId> </ns0:getBalance> </soapenv:Body> </soapenv:Envelope> <soapenv:Envelope xmlns:soapenv=" xmlns:xsd=" xmlns:xsi=" <soapenv:Body> <ns1:getBalanceResponse soapenv:encodingStyle=" xmlns:ns1=" <getBalanceReturn xsi:type="xsd:string">1 Pedro 34.1</getBalanceReturn> </ns1:getBalanceResponse> </soapenv:Body> </soapenv:Envelope> 11/8/2018

34 SOAP Envelope – Fault element
The optional SOAP Fault element is used to hold error and status information for a SOAP message. Sub Element Description <faultcode> A code for identifying the fault <faultstring> A human readable explanation of the fault <faultactor> Information about who caused the fault to happen <detail> Holds application specific error information related to the Body element FaultCode Description VersionMismatch Found an invalid namespace for the SOAP Envelope element MustUnderstand An immediate child element of the Header element, with the mustUnderstand attribute set to "1", was not understood Client The message was incorrectly formed or contained incorrect information Server There was a problem with the server so the message could not proceed 11/8/2018

35 WSDL WSDL is an XML-based language for describing Web services and how to access them. Stands for Web Services Description Language. Used to describe and locate Web services. WSDL Describes Web Services WSDL stands for Web Services Description Language. WSDL is a document written in XML. The document describes a Web service. It specifies the location of the service and the operations (or methods) the service exposes. 11/8/2018

36 Service contracts – WSDL files
<?xml version="1.0" encoding="UTF-8"?> <wsdl:definitions <wsdl:message name="getBalanceResponse"> <wsdl:part name="getBalanceReturn" type="xsd:string"/> </wsdl:message> <wsdl:message name="getBalanceRequest"> <wsdl:part name="accountId" type="xsd:int"/> <wsdl:portType name="BankService"> <wsdl:operation name="getBalance" parameterOrder="accountId"> <wsdl:input name="getBalanceRequest" message="impl:getBalanceRequest"/> <wsdl:output name="getBalanceResponse" message="impl:getBalanceResponse"/> </wsdl:operation> </wsdl:portType> <wsdl:binding name="BankServiceSoapBinding" type="impl:BankService"> <wsdlsoap:binding style="rpc" transport=" <wsdl:operation name="getBalance"> <wsdlsoap:operation soapAction=""/> <wsdl:input name="getBalanceRequest"> <wsdlsoap:body use="encoded" encodingStyle=... namespace=" </wsdl:input> <wsdl:output name="getBalanceResponse"> <wsdlsoap:body use="encoded" encodingStyle=… namespace=" </wsdl:output> </wsdl:binding> <wsdl:service name="BankServiceService"> <wsdl:port name="BankService" binding="impl:BankServiceSoapBinding"> <wsdlsoap:address location=" </wsdl:port> </wsdl:service> </wsdl:definitions> Implementation - Interoperability Problems 11/8/2018

37 WSDL Contract Architecture
11/8/2018

38 UDDI Registry UDDI is a directory service where businesses can register and search for Web services. Platform-independent framework for describing services, discovering businesses, and integrating business services by using the Internet. Stands for Universal Description, Discovery and Integration. Directory of web service interfaces described by WSDL UDDI communicates via SOAP 11/8/2018

39 UDDI Registry (cont’d)
Helps to find a web service and its description Search by business Search by service type Two types of UDDI registries Public registries Private registries 11/8/2018

40 Service Oriented Architecture
The Details of SOA depends on your role… Implementation Architecture Business Architectural style which requires a service provider, requestor and a service description. Set of architectural principles, patterns and criteria which address characteristics such as modularity, encapsulation, loose coupling, separation of concerns, reuse, composability and single implementation. Set of services that a business exposes to their customers and partners, or other portions of the organization. Programming model complete with standards, tools and technologies such as Web Services. 11/8/2018

41 SOA – WS relationship Web Services "Web services are software components described via WSDL which are capable of being accessed via standard network protocols such as SOAP over HTTP.“ Web services achieves most of the goals of SOA. Web Services technology is one style of creating services for SOA. BUT SOA does not require the use of Web Services. We can create useful services that don't speak SOAP. SOA and WS are not the same thing. 11/8/2018

42 SOA – WS relationship Most of today's production Web Services systems are not service oriented architectures – they're simple remote procedure calls or point-to-point messaging via SOAP or well structured integration architectures. There are production service oriented architectures that do not primarily use Web Services - they use ftp, batch files, asynchronous messaging, etc. 11/8/2018

43 Benefits of SOA Support for all major vendors. WS Standards.
Interoperability and integration capability. Services reuse. Well defined public interfaces. High abstraction level. User roles. Specialized profiles. Easy assembling for new business process. 11/8/2018

44 Limitations of SOA Business components in closed application domains.
Performance issues in XML parsing. Long-running asynchronous processes. WS-Security implementation. WS-Transaction overhead. Complex data types interoperability. 11/8/2018

45 Agenda Web Services SOAP-based WS Definition
Advantages and reservations Classification: SOAP vs REST SOAP-based WS XML, XSL, XPath, XSLT WSDL/ UDDI SOAP SOA (Service Oriented Architecture) SOA Benefits Demo: Creating and consuming a SOAP-based WS 11/8/2018

46 Demo: Creating and consuming a SOAP-based WS
11/8/2018

47 Agenda (cont’d) RESTful WS AJAX JSON Demo: JSON and REST-WS
The XmlHttpRequest object The HttpRequest object JSON JSON data structures JSON vs XML Benefits and lowlights of JSON Generating and Consuming JSON Demo: JSON and REST-WS 11/8/2018

48 Need for AJAX Their ease of deployment allows a site to have millions of users with minimal cost Traditional Web UI are not responsive to users Websites forced users into submit/wait/redisplay Ajax allows to build more dynamic and responsive Web applications ability to communicate with the server asynchronously use JS and DHTML to immediately update the UI spawn an asynchronous request to the server to perform an update or query a database 11/8/2018

49 AJAX AJAX stands for Asynchronous JavaScript And XML
AJAX incorporates several technologies Standards-based presentation using XHTML and CSS Dynamic display and interaction using the Document Object Model Asynchronous server communication using XMLHttpRequest Supported by most modern browsers Allows to perform HTTP requests which returns some form of response. Can automatically parse an XML document sent in response to a request. JavaScript binding everything together AJAX allows to communicate with the web server to send and retrieve data without loading a new page reloading the current page 11/8/2018

50 HTTP: Quick Overview When loading http://www.example.net/index.html
The browser opens a connection to the host It then sends the server an HTTP request which consists of several lines of plain text The server sends back an HTTP response which also consists of several lines of plain text The first line contains the HTTP verb or method. In this case, the method is GET which means return the following document. Following that is the path to the document to retrieve (/about/index.html). The HTTP/1.1 tells the server what version of HTTP the browser supports. The lines that follow are called request headers. The specify additional information that may be used by the web server to help it send a proper response to the browser. 11/8/2018

51 HTTP Request Contains HTTP method Path to document to retrieve
HTTP version Request header GET /index.html HTTP/1.1 Host: User-Agent: Mozilla/5.0 (Windows; U; Windows NT 5.1; en-US; rv:1.7.12)... Accept: text/xml,application/xml,application/xhtml+xml,text/html;q=0.9,... Accept-Language: en-us,en;q=0.5 Accept-Encoding: gzip,deflate Accept-Charset: ISO ,utf-8;q=0.7,*;q=0.7 Keep-Alive: 300 Proxy-Connection: keep-alive Pragma: no-cache Cache-Control: no-cache 11/8/2018

52 HTTP version and status
HTTP Response The web server will return a response The response consists of several lines of plain text. HTTP/1.x 200 OK Server: Microsoft-IIS/5.1 Date: Fri, 20 Jan :29:47 GMT Content-Length: 534 Content-Type: text/html Cache-Control: private <html> <head> <title>About Us</title> </head> <body> <h1>About us</h1> <p>...</p> </body> </html> HTTP version and status Response Header The first line contains the HTTP version and a three digit status code. The text following that number is a short description of that code. 200 means "OK," the request was successfully processed. If the requested page did not exist, the status would be "404 Not found." The lines following are request headers. Like the response headers, these give additional information about the response such as the document type ("text/html") and size (534 bytes). A blank line follows, signaling the end of the response header. The rest of the lines represent the response data. In this case, it is the HTML of the page which the browser will parse and render. Response Data 11/8/2018

53 Passing Data in an HTTP Request
Append a query string to the URL Each field is represented as name=value Fields are separated by a '&' character Each name and value is url-encoded non-alphanumeric characters are replaced by a hex value "%xx“ Use the POST method. Often used with forms on web pages. POST /signup.asp HTTP/1.1 Host: User-Agent: Mozilla/5.0 (Windows; U; Windows NT 5.1; en-US; rv:1.7.12)... Accept: text/xml,application/xml,application/xhtml+xml,text/html;q=0.9,... Accept-Language: en-us,en;q=0.5 Accept-Encoding: gzip,deflate Accept-Charset: ISO ,utf-8;q=0.7,*;q=0.7 Keep-Alive: 300 Connection: keep-alive Content-Type: application/x-www-form-urlencoded Content-Length: 38 name=Jane+Doe& =jane%40myhost.com 11/8/2018

54 How does AJAX work? The kernel of Ajax is the XmlHttpRequest JavaScript object. XmlHttpRequest was originally introduced in IE5 It is the enabling technology that allows asynchronous requests XmlHttpRequest lets use JS to make a request to the server and process the response without blocking the user. Before using the XMLHttpRequest object, create an instance of it (no standard way for doing this) XMLHttpRequest is supported natively by most browsers IE is an exception, MS introduced the idea, but as an ActiveX object. 11/8/2018

55 XMLHttpRequest Object: Properties
readyState A number representing the current state of the request status The numeric HTTP status code returned by the web server. statusText The text associated with the above HTTP status code. For example, 200 means "OK" and 404 means "Not found". responseText A string containing the response data returned from the web server. responseXML If the web server returns an XML document, this will be a DOM document object representing the parsed XML. 11/8/2018

56 XMLHttpRequest Object: Methods
open(method, url, asynch, username, password) Initializes a new request. method is usually GET or POST. setRequestHeader(name, value) Sets a the named request header. send(data) Makes the request, optionally passing data. abort() Aborts an active request. getResponseHeader(name) Returns the value of the named response header. getAllResponseHeaders() Returns a string containing all the response headers. 11/8/2018

57 Examples of AJAX uses Dynamically update totals on your shopping cart without forcing the user to click Update and wait for the server to resend the entire page. Increase site performance by reducing the amount of data downloaded from the server. When updating the quantity of an item in a basket, if the entire page is reloaded, forces several KB of data to be downloaded. Using Ajax to calculate the new total, the server can respond with just the new total value, thereby reducing the required bandwidth Eliminate page refreshes every time there is user input. If the user clicks Next on a paginated list, Ajax allows you to just refresh the list with the server data, instead of redrawing the entire page. Edit table data directly in place, without requiring the user to navigate to a new page to edit the data. When the user clicks Edit, you can redraw the static table into a table with editable contents. Once the user clicks Done, you can spawn an Ajax request to update the server, and redraw the table to have static, display-only data. 11/8/2018

58 The HttpRequest object
Wrapper for XMLHttpRequest Hides the browser differences in instantiating the object Simplifies the process of making a request and obtaining the response. Defined in HttpRequest.js library Constructor HttpRequest() Creates a new instance of the HttpRequest object. 11/8/2018

59 The HttpRequest object (Properties)
successCallback A function to be called when a GET or POST request completes successfully failureCallback A function to be called when a GET or POST request completes unsuccessfully url The URL to send the request to queryString A query string to append to the URL username Username for authentication, if required password Password for authentication, if required status, statusText, responseText, responseXML These are equivalent to the XMLHttpRequest properties of the same name 11/8/2018

60 The HttpRequest object (Methods)
clearRequestHeaders() Removes all request headers. get() Performs an asynchronous GET request. post(data) Performs an asynchronous POST request, passing the given data abort(), setRequestHeader(name, value), getResponseHeader(name), getAllResponseHeaders() These are equivalent to the XMLHttpRequest methods of the same name. 11/8/2018

61 The HttpRequest JS library
Need HttpRequest.js library Create HttpRequest object var postRequest = new HttpRequest(); Define failure callback postRequest.failureCallback = requestFailed; function requestFailed(httpRequest){…} Perform an asynchronous request postRequest.url = address of service; postRequest.queryString =; postRequest.successCallback = responseOK; postRequest.get(); 11/8/2018

62 RESTful WS Web services are practically synonymous with XML
The application architecture imposed by Ajax and REST techniques has forced many to contemplate alternatives like JSON JSON is lighter and more friendly format for Web services clients in the form of a browser (Ajax-enabled application) 11/8/2018

63 AJAX and XML Ajax establishes a separate channel on which to send and receive information from remote WS If response is an XML DOM used for manipulating and processing text simple access to a data tree requires numerous method calls DOM: differing implementation details among various browsers complex programming scheme for cross-browser compatibility Need to accommodate WS response to AJAX leverage a common component in all mainstream browsers: the JavaScript engine JSON fits natively to the JS engine 11/8/2018

64 Agenda (cont’d) RESTful WS AJAX JSON Demo: JSON and REST-WS
The XmlHttpRequest object The HttpRequest object JSON JSON data structures JSON vs XML Benefits and lowlights of JSON Generating and Consuming JSON Demo: JSON and REST-WS 11/8/2018

65 JSON JSON stands for JavaScript Object Notation
Lightweight data-interchange format Text Format: easy for humans to read and write Trivial for JS engine to parse and generate Based on a subset of the JavaScript Programming Language JSON is a text format that is completely language independent uses conventions familiar to programmers of the C-family of programming languages 11/8/2018

66 JSON data structures JSON is built on two structures:
A collection of name/value pairs. In various languages, this is realized as an object, record, struct, dictionary, hash table, keyed list, or associative array. An ordered list of values. In most languages, this is realized as an array, vector, list, or sequence. These are universal data structures. Virtually all modern programming languages support them 11/8/2018

67 JSON vs XML <addressbook> <name>Mary Lebow</name>
<street>5 Main Street</street> <city zip="91912"> San Diego, CA </city> <phoneNumbers> <phone> </phone> <phone> </phone> </phoneNumbers> </address> </addressbook> {"addressbook": {"name": "Mary Lebow", "address": { "street": "5 Main Street“, "city": "San Diego, CA", "zip": 91912 }, "phoneNumbers": [ " ", " " ] } 11/8/2018

68 JSON Object An object is an unordered set of name/value pairs
An object begins with { and ends with }  Each name is followed by : and the name/value pairs are separated by ,  Example: { firstname : Juan, lastname : Lucero } 11/8/2018

69 JSON Array An array is an ordered collection of values
An array begins with [ and ends with ] Values are separated by ,  Example: [{ firstname:Juan, lastname:Lucero }, { firstname:Jose, lastname:Perez }] 11/8/2018

70 JSON Value A value can be Examples: 34, “Joseph”, true, {price:32.2}
11/8/2018

71 JSON String A string is a collection of zero or more Unicode characters, wrapped in double quotes A character is represented as a single character string. 11/8/2018

72 JSON Number A number is very much like a C or Java number
Octal and hexadecimal formats are not used 11/8/2018

73 Benefits of JSON Easier data access {"addressbook":
{"name": "Mary Lebow", "address": { "street": "5 Main Street“, "city": "San Diego, CA", "zip": 91912 }, "phoneNumbers": [ " ", " " ] } Easier data access Same internal representation used by JS engines for data structures like strings, arrays, and objects Name access from JSON: addressbook.name Street address access from JSON: addressbook.address.street First phone number access from JSON: addressbook.address.phoneNumbers[0] 11/8/2018

74 Benefits of JSON (cont’d)
JSON has a less verbose nature XML requires closing tags for markup compliance JSON only needs a } In data exchanges comprising a hundred or more fields, this additional XML markup can add to transit times JSON libraries produced for many languages C#, Java, PHP, Haskell, Lisp… 11/8/2018

75 Lowlights of JSON Namespaces are missing in JSON
JSON lacks of attributes Creation and validation of JSON may be more complex XML has several developing tools for its processing 11/8/2018

76 public class Person { #region Member fields int id = - 1; string name = ""; #endregion #region Properties public int ID get{return this.id;} set{this.id = value;} } public string Name get{return this.name;} set{this.name = value;} #region Constructors public Person(): this( - 1, ""){} public Person(int id, string name) this.id = id; this.name = name; Generating JSON Use a StringBuilder (or similar) class to serialize object Use existing DLLs or libraries that perform this task for different languages public string ToJSON() StringBuilder sb = new StringBuilder(); sb.Append("{"); sb.AppendFormat("\"{0}\": \"{1}\"", this.ID, this.Name); sb.Append("}"); return sb.ToString(); } Add 11/8/2018

77 Consuming JSON function ReadyStateChangeHandler() { if (xmlHttpRequest.readyState == 4) // Completed if (xmlHttpRequest.status == 200) // Response OK // Process data var jsonStringObj = xmlHttpRequest.responseText; // Parse the JSON string object to a real JSON object var jsonObj = jsonStringObj.parseJSON(); // display some data alert("Person Name: " + jsonObj.Name); } else alert("Error: HTTP " + xmlHttpRequest.status + " " + xmlHttpRequest.statusText); On JS, use json.js from json.org to convert a json-formatted string into a json object 11/8/2018

78 JSON and REST-WS demo 11/8/2018

79 Agenda (cont’d) Mashups Hands On Wrap up Example of mashups
Mashing up a yahoo map object Hands On Consuming a REST-WS Creating/Adding a mashup Wrap up 11/8/2018

80 Mashups Web application that combines data from more than one source into a single integrated tool 11/8/2018

81 Mashup: Yahoo! Maps API Obtain an application ID
<html> <head> <script type="text/javascript" src=" </script> </head> <body> ... </body> </html> 11/8/2018

82 Mashup: Yahoo! Maps API Add a div container in which to place the map
Create a map object and use the drawZoomAndCenter() method to draw the map <script type="text/javascript"> // Create a map object var map = new YMap(document.getElementById('map')); // Set map type to either of: YAHOO_MAP_SAT, YAHOO_MAP_HYB, YAHOO_MAP_REG map.setMapType(YAHOO_MAP_SAT); // create geopoint var geopoint = new YGeoPoint(latitude,longitude); // Display the map centered on a geocoded location map.drawZoomAndCenter(geopoint, 3); </script> <div id="map"></div> 11/8/2018

83 Agenda (cont’d) Mashups Hands On Wrap up Example of mashups
Mashing up a yahoo map object Hands On Consuming a REST-WS Creating/Adding a mashup Wrap up 11/8/2018

84 JSON / RESTful WS Client
WS is located in Parameters: Lat // latitude, use Long // longitude, use Within // range of interest in meters, e.g. Within=500 An html template file is in <serverip> Use a ftp client to download it locally, modify it, rename it, and uploaded to the server. Then opening it using IE JS Scripts are also located there Your job Consume the WS, convert the response to a JSON object, and display the answer in the html page Play a bit. Resources have url pictures, you can retrieve these pictures from the server too 11/8/2018

85 JSON Object objects id name desc type resource object images img_thumb
elements res latitude longitude distance 11/8/2018

86 Mashing up with Yahoo! Maps
A reference card for the API is located in <serverip> Your job: Place a map centered in ( , ) Place markers for each resource on the map using YMarker(geopoint); addOverlay(marker); Play with addAutoExpand() method 11/8/2018

87 Agenda (cont’d) Mashups Hands On Wrap up Example of mashups
Mashing up a yahoo map object Hands On Consuming a REST-WS Creating/Adding a mashup Wrap up 11/8/2018

88 SOA and WEB 2.0 Convergence
11/8/2018

89 XML vs JSON: considerations
Which one to use depends mainly on the WS consumer Thick WS clients (Java , .NET , PHP, …) should use XML. Most programming language environments provide custom libraries, parsers, or helper classes, ... Thin WS clients (web-based, AJAX) should consider JSON. Processing XML can be tough in this environment Programming the DOM is a difficult undertaking when compared to accessing a JSON tree. 11/8/2018

90 References SOAP-based Web Services RESTful Web Services JSON
Service-Oriented Architecture : A Field Guide to Integrating XML and Web Services, by Thomas Erl, Prentice Hall RESTful Web Services RESTful Web Services, Richardson et al, O’Reilly JSON Yahoo! Maps AJAX API 11/8/2018

91 Questions ? 11/8/2018

92 Backup 11/8/2018

93 11/8/2018

94 Similarities 11/8/2018


Download ppt "SOAP-based and RESTful Web Services"

Similar presentations


Ads by Google