CSE 154 LECTURE 17: WEB SERVICES. What is a web service? web service: software functionality that can be invoked through the internet using common protocols.

Slides:



Advertisements
Similar presentations
The Document Object Model
Advertisements

Cookies, Sessions. Server Side Includes You can insert the content of one file into another file before the server executes it, with the require() function.
XML CS What is XML?  XML: a "skeleton" for creating markup languages  you already know it!  syntax is identical to XHTML's: content  languages.
JavaScript and AJAX Jonathan Foss University of Warwick
JavaScript and the DOM Les Carr COMP3001 Les Carr COMP3001.
Document Object Model (DOM) JavaScript manipulation of the DOM.
More forms CS Reset Buttons  specify custom text on the button by setting its value attribute CS380 2 Name: Food: Meat? HTML.
 2008 Pearson Education, Inc. All rights reserved Document Object Model (DOM): Objects and Collections.
CSE 154 LECTURE 23: XML. Storing structured data in arbitrary text formats (bad) My note: BEGIN FROM: Alice Smith TO: Robert Jones.
Client, Server, HTTP, IP Address, Domain Name. Client-Server Model Client Bob Yahoo Server yahoo.com/finance.html A text file named finance.html.
FILE UPLOADS CHAPTER 11. THE BASIC PROCESS 1.The HTML form displays the control to locate and upload a file 2.Upon form submission, the server first stores.
CSE 154 LECTURE 9: FORMS. Web data most interesting web pages revolve around data examples: Google, IMDB, Digg, Facebook, YouTube, Rotten Tomatoes can.
JSON (JavaScript Object Notation).  A lightweight data-interchange format  A subset of the object literal notation of JavaScript (or ECMA-262).  A.
CMPT Web Programming Introduction and Basic HTML.
CSE 154 LECTURE 24: XML AND JSON. Debugging responseXML in Firebug can examine the entire XML document, its node/tree structure.
1 CIS336 Website design, implementation and management (also Semester 2 of CIS219, CIS221 and IT226) Lecture 9 JavaServer Pages (JSP) (Based on Møller.
FALL 2005CSI 4118 – UNIVERSITY OF OTTAWA1 Part 4 Web technologies: HTTP, CGI, PHP,Java applets)
JavaScript & jQuery the missing manual Chapter 11
Chapter 6: Forms JavaScript - Introductory. Previewing the Product Registration Form.
1 Fall 2006 Florida Atlantic University Department of Computer Science & Engineering COT 6930 Advanced Internet Programming Dr. Roy Levow Day 2.
Overview of Previous Lesson(s) Over View  ASP.NET Pages  Modular in nature and divided into the core sections  Page directives  Code Section  Page.
JavaScript, Fourth Edition Chapter 12 Updating Web Pages with AJAX.
CNIT 133 Interactive Web Pags – JavaScript and AJAX JavaScript Environment.
JavaScript & DOM Client-side scripting. JavaScript JavaScript is a tool to automate client side (which is implemented using HTML so far) JavaSript syntax.
D2L Notes Be sure to submit your link in the dropbox provided on D2L You can just upload an empty text file if a file upload is required Do not use D2L.
CSE 154 LECTURE 12: COOKIES. Including files: include include("filename"); PHP include("header.html"); include("shared-code.php"); PHP inserts the entire.
Working with the XML Document Object Model ©NIITeXtensible Markup Language/Lesson 7/Slide 1 of 44 Objectives In this lesson, you will learn to: *Identify.
 2004 Prentice Hall, Inc. All rights reserved. 1 Chapter 34 - Case Study: Active Server Pages and XML Outline 34.1 Introduction 34.2 Setup and Message.
1 Dr Alexiei Dingli XML Technologies XML Advanced.
Javascript II DOM & JSON. In an effort to create increasingly interactive experiences on the web, programmers wanted access to the functionality of browsers.
NMD202 Web Scripting Week3. What we will cover today Includes Exercises PHP Forms Exercises Server side validation Exercises.
 Whether using paper forms or forms on the web, forms are used for gathering information. User enter information into designated areas, or fields. Forms.
JavaScript IV ECT 270 Robin Burke. Outline DOM JS document model review W3C DOM.
_______________________________________________________________________________________________________________ PHP Bible, 2 nd Edition1  Wiley and the.
Lecture 9: AJAX, Javascript review..  AJAX  Synchronous vs. asynchronous browsing.  Refreshing only “part of a page” from a URL.  Frameworks: Prototype,
Lecture 3 : PHP5-DOM API UFCFR Advanced Topics in Web Development II 2014/15 SHAPE Hong Kong.
Internet & World Wide Web How to Program, 5/e. © by Pearson Education, Inc. All Rights Reserved.2 Revised by Dr. T. Tran for CSI3140.
ASP. What is ASP? ASP stands for Active Server Pages ASP is a Microsoft Technology ASP is a program that runs inside IIS IIS stands for Internet Information.
1 Javascript DOM Peter Atkinson. 2 Objectives Understand the nature and structure of the DOM Add and remove content from the page Access and change element.
 2008 Pearson Education, Inc. All rights reserved Document Object Model (DOM): Objects and Collections.
Operating Systems Lesson 12. HTTP vs HTML HTML: hypertext markup language ◦ Definitions of tags that are added to Web documents to control their appearance.
הרצאה 4. עיבוד של דף אינטרנט דינמי מתוך Murach’s PHP and MySQL by Joel Murach and Ray Harris.  דף אינטרנט דינמי משתנה עפ " י הרצת קוד על השרת, יכול להשתנות.
 Previous lessons have focused on client-side scripts  Programs embedded in the page’s HTML code  Can also execute scripts on the server  Server-side.
HTML Overview Part 5 – JavaScript 1. Scripts 2  Scripts are used to add dynamic content to a web page.  Scripts consist of a list of commands that execute.
ICM – API Server & Forms Gary Ratcliffe.
Internet Applications (Cont’d) Basic Internet Applications – World Wide Web (WWW) Browser Architecture Static Documents Dynamic Documents Active Documents.
RESTful Web Services What is RESTful?
Martin Kruliš by Martin Kruliš (v1.1)1.
Creating Animations, Working with Graphics, and Accessing Data Lesson 9.
AJAX. Ajax  $.get  $.post  $.getJSON  $.ajax  json and xml  Looping over data results, success and error callbacks.
CHAPTER 8 AJAX & JSON WHAT IS AJAX? Ajax lets you…
Session 11: Cookies, Sessions ans Security iNET Academy Open Source Web Development.
JavaScript, Sixth Edition Chapter 11 Updating Web Pages with Ajax.
Web Services Essentials. What is a web service? web service: software functionality that can be invoked through the internet using common protocols like.
CSE 154 LECTURE 18: FORMS AND UPLOADING FILES. Exercise: Baby name web service JSON Modify our babynames.php service to produce its output as JSON. For.
CITA 330 Section 10 Web Remoting Techniques. Web Remoting Web Remoting is a term used to categorize the technique of using JavaScript to directly make.
CSE 154 LECTURE 18: WEB SERVICES. Exercise: Baby name web service Write a web service that accepts a name and gender and finds and outputs the line from.
XML CS What is XML?  XML: a "skeleton" for creating markup languages  you already know it!  syntax is identical to XHTML's: content  languages.
THE DOM.
Lecture 16: File I/O; Functions
CSE 154 Lecture 12: XML.
CHAPTER 5 DOCUMENT OBJECT MODEL
XML in Web Technologies
CSE 154 Lecture 24: JSON.
IS333D: MULTI-TIER APPLICATION DEVELOPMENT
Lecture 19: Forms and uploading files
JavaScript & jQuery AJAX.
Lecture 14: JSON and Web SERVICES
Chengyu Sun California State University, Los Angeles
Presentation transcript:

CSE 154 LECTURE 17: WEB SERVICES

What is a web service? web service: software functionality that can be invoked through the internet using common protocols like a remote function(s) you can call by contacting a program on a web server many web services accept parameters and produce results can be written in PHP and contacted by the browser in HTML and/or Ajax code service's output might be HTML but could be text, XML, JSON or other content examples seen in CSE 154: quote.php, animalgame.php, books_json.php, urban.php, weather.php

Setting content type with header header("Content-type: type/subtype"); PHP header("Content-type: text/plain"); print "This output will appear as plain text now!\n"; PHP by default, a PHP file's output is assumed to be HTML (text/html) use the header function to specify non-HTML output header must appear before any other output generated by the script

Recall: Content ("MIME") typesMIME MIME typerelated file extension text/plain.txt text/html.html,.htm,... text/xml.xml application/json.json text/css.css text/javascript.js image/gif.gif Lists of MIME types: by type, by extensionby typeby extension

Example: Exponent web service Write a web service that accepts a base and exponent and outputs base raised to the exponent power. For example, the following query should output 81 : solution: <?php header("Content-type: text/plain"); $base = (int) $_GET["base"]; $exp = (int) $_GET["exponent"]; $result = pow($base, $exp); print $result; ?> PHP

Exercise: Baby name web service Write a web service that accepts a name and gender and finds and outputs the line from text file rank.txt with information about that name: rank.txt Aaron m Lisa f For the following call: The service should output the following line: Lisa f

What about errors? What if the user doesn't pass an important parameter? (no name passed!) What if the user passes a name that is not found in the file? (not found in file) What is the appropriate behavior for the web service?

Reporting errors web service should return an HTTP "error code" to the browser, possibly followed by output error messages ( print ) are not ideal, because they could be confused for normal output these are the codes you see in Firebug's console and in your Ajax request's status property HTTP codeMeaning 200OK page has moved (permanently or temporarily) 400illegal request 401authentication required 403you are forbidden to access this page 404page not found 410gone; missing data or resource 500internal server error complete list

Using headers for HTTP error codes header("HTTP/1.1 code description"); PHP if ($_GET["foo"] != "bar") { # I am not happy with the value of foo; this is an error header("HTTP/ Invalid Request"); die("An HTTP error 400 (invalid request) occurred."); } PHP if (!file_exists($input_file_path)) { header("HTTP/ File Not Found"); die("HTTP error 404 occurred: File not found ($input_file_path)"); } PHP header can also be used to send back HTTP error codes header("HTTP/ Forbidden"); header("HTTP/ File Not Found"); header("HTTP/ Server Error");

Checking for a mandatory query parameter function get_query_param($name) { if (!isset($_GET[$name])) { header("HTTP/ Invalid Request"); die("HTTP/ Invalid Request: missing required parameter '$name'"); } if ($_GET[$name] == "") { header("HTTP/ Invalid Request"); die("HTTP/ Invalid Request: parameter '$name' must be non-empty"); } return $_GET[$name]; } PHP

The $_SERVER superglobal array indexdescriptionexample $_SERVER["SERVER_NAME"]name of this web server"webster.cs.washington.edu" $_SERVER["SERVER_ADDR"]IP address of web server" " $_SERVER["REMOTE_HOST"]user's domain name"hsd1.wa.comcast.net" $_SERVER["REMOTE_ADDR"]user's IP address" " $_SERVER["HTTP_USER_AGENT"]user's web browser"Mozilla/5.0 (Windows;..." $_SERVER["HTTP_REFERER"]where user was before this page" $_SERVER["REQUEST_METHOD"]HTTP method used to contact server "GET" or "POST" call phpinfo(); to see a complete list phpinfo();

GET or POST? if ($_SERVER["REQUEST_METHOD"] == "GET") { # process a GET request... } elseif ($_SERVER["REQUEST_METHOD"] == "POST") { # process a POST request... } PHP some web services process both GET and POST requests to find out which kind of request we are currently processing, look at the global $_SERVER array's "REQUEST_METHOD" element

Emitting partial-page HTML data # suppose my web service accepts a "type" query parameter... PHP some web services do output HTML, but not a complete page the partial-page HTML is meant to be fetched by Ajax and injected into an existing page

Exercise: Baby name web service XML Modify our babynames.php service to produce its output as XML. For the data: Morgan m The service should output the following XML: XML

Emitting XML data manually... header("Content-type: text/xml"); print " \n"; foreach ($books as $book) { print " \n"; } print " \n"; XML specify a content type of text/xml or application/xml print an XML prologue (the <?xml line), then print XML data as output important: no whitespace output can precede the prologue; must be print ed messy; bad to embed XML syntax in print s; write-only (hard to read existing XML data)

PHP's XML DOM: DOMDocument The PHP DOMDocument class represents an XML document. It has these methods: DOMDocument createElement( tag )create a new element node to add to the document createTextNode( text )create a new text node to add to the document getElementById( id ), getElementsByTagName( tag ) search for elements in the document load( filename ), loadXML( string ) read XML data from a file on disk or from a string save( filename ), saveXML() write XML data to a file on disk or returns it as a string validate()return whether the current document consists of valid XML data

PHP's XML DOM: DOMElement The PHP DOMElement class represents each DOM element. It has these fields/methods: DOMElement tagName, nodeValuenode's name (tag) and value (text) parentNode, childNodes, firstChild, lastChild, previousSibling, nextSibling references to nearby nodes appendChild( DOMNode ), insertBefore( newNode, oldNode ), removeChild( DOMNode ) manipulate this node's list of children getElementsByTagName( tag )search for descendent elements within this element getAttribute( name ), setAttribute( name, value ), removeAttribute( name ) get/set the value of an attribute on this tag

PHP XML DOM example... $xmldoc = new DOMDocument(); # $books_tag = $xmldoc->createElement("books"); $xmldoc->appendChild($books_tag); # foreach ($books as $book) { $book_tag = $xmldoc->createElement("book"); # <book $book_tag->setAttribute("title", $book["title"]); # title="Harry Potter" /> $book_tag->setAttribute("author", $book["author"]); # author="J.K. Rowling" /> $books_tag->appendChild($book_tag); } # header("Content-type: text/xml"); print $xmldoc->saveXML(); much easier to read/write/manipulate complex XML saveXML automatically inserts the XML prolog for us

Exercise solution: Baby name web service XML # takes a line of rankings and produces XML in the specified format # example: Aaron m function generate_xml($line, $name, $gender) { $xmldom = new DOMDocument(); $baby_tag = $xmldom->createElement("baby"); # $baby_tag->setAttribute("name", $name); $baby_tag->setAttribute("gender", $gender); $year = 1890; $tokens = explode(" ", $line); for ($i = 2; $i < count($tokens); $i++) { $rank_tag = $xmldom->createElement("rank"); # $rank_tag->setAttribute("year", $year); $rank_tag->appendChild($xmldom->createTextNode($tokens[$i])); $baby_tag->appendChild($rank_tag); $year += 10; } $xmldom->appendChild($baby_tag); return $xmldom; } PHP

Exercise: Baby name web service JSON Modify our babynames.php service to produce its output as JSON. For the data: Morgan m The service should output the following JSON: { "name": "Morgan", "gender": "m", "rankings": [375, 410, 392, 478, 579, 507, 636, 499, 446, 291, 278, 332, 518] } JSON

Emitting JSON data manually... header("Content-type: application/json"); print "{\n"; print " \"books\": [\n"; foreach ($books as $book) { print " {\"author\": \"{$book['author']}\", \"title\": \"{$book['title']}\"}\n"; } print "\n"; specify a content type of application/json messy, just like when manually printing XML (not recommended)

PHP's JSON functions PHP includes the following global functions for interacting with JSON data: json_decode( string )parses the given JSON data string and returns an equivalent associative array object (like JSON.parse in JavaScript) json_encode( object )returns JSON equivalent for the given object or array or value (like JSON.stringify in JavaScript) json_encode will output associative arrays as objects and normal arrays as arrays

PHP JSON example <?php $data = array( "library" => "Odegaard", "category" => "fantasy", "year" => 2012, "books" => array( array("title" => "Harry Potter", "author" => "J.K. Rowling"), array("title" => "The Hobbit", "author" => "J.R.R. Tolkien"), array("title" => "Game of Thrones", "author" => "George R. R. Martin"), array("title" => "Dragons of Krynn", "author" => "Margaret Weis"), ) ); header("Content-type: application/json"); print json_encode($data); ?> PHP

PHP JSON example - output { "library": "Odegaard", "category": "fantasy", "year": 2012, "books": [ {"title": "Harry Potter", "author": "J.K. Rowling"}, {"title": "The Hobbit", "author": "J.R.R. Tolkien"}, {"title": "Game of Thrones", "author": "George R. R. Martin"}, {"title": "Dragons of Krynn", "author": "Margaret Weis"}, ] } JSON

For reference: Provided web services code quote.php animalgame.php books_json.php urban.php (caution: contains profanity) urban.php babynames.php