CS3220 Web and Internet Programming RESTful Web Service Chengyu Sun California State University, Los Angeles
Example: Files and Folders \ Documents \ Users \ John \ Courses \ CS3220 File.java files.sql \ CS5220 Homework1.pdf contacts.xls \ Jane log.txt
The Need to Exchange Data Between Client and Server Ajax Folder Expand Client Server + Documents + Users log.txt Folder ID List of files and subfolders in the folder
Usage of RESTful Web Service Applications Mobile Apps Server RESTful Web Service Desktop Applications Other Web Services
A RESTful Web Service Example Implementation File DbUtils FileServlet Request Get file with id=1: /file/1 JSON Response mapped to /file/* { “id”: 1, “name”: “Documents”, “parentId”: null, “folder”: true }
Is That Really A Web Service? Why does it look like a web application? Why is it called RESTful?
A Brief History of Web Service Remote Procedure Call Simplifies network programming RPC CORBA Cross-platform RPC (Traditional) Web Services Cross-platform RPC over HTTP SOAP – complex and not efficient RESTful Web Services
Why Does It Look Like A Web Application? Answer: it does, and it’s a good thing. Now all web technologies/languages can be used to create web services (and you don’t have to implement complex specifications like SOAP).
Why Is It Called RESTful? REpresentational State Transfer Introduced by Roy Fielding in his Ph.D. dissertation on network-base software architecture Describes the common characteristics of scalable, maintainable, and efficient distributed software systems
The REST Constraints Client and server Stateless Support caching Uniformly accessible Layered (Optional) support code-on-demand
RESTful Web Services Web applications for programs Generate responses in formats to be read by machines (i.e. JSON and XML) rather than by humans (i.e. HTML) Simulate how the static web (the largest REST system) works Use URLs that look like URLs for static web pages Utilize HTTP request methods and headers Stateless, i.e. no session
RESTful Web Service Example Files and folders Get Add Update Delete List All the top-level files and folders All the files and folders under a folder
Create a RESTful Web Service Identify resources and operations Determine resource representation, i.e. data exchange format between the service and the clients Design URL and request mapping Implement the operations
Resource Representation Data format should be easily “understandable” by all programming languages XML Already widely in use as a platform independent data exchange format XML parsers are readily available in many languages JSON Much more concise than XML Can be used directly in JavaScript
URL Design and Request Mapping Conventions (1) Operation: get a file/folder URL /file/{id} or /file/get?id={id} Path variable based design is usually preferred to request parameter based design.
URL Design and Request Mapping Conventions (2) Operation: get a file/folder Choose which data format to use to communicate with a client Solution: /file/{id}.{format}, or Check the Accept request header
URL Design and Request Mapping Conventions (3) Map HTTP Request Methods to CRUD operations POST (or PUT) GET PUT (or POST) DELETE Create Retrieve Update Delete
Request Mapping Example (I) Operation HTTP Request Get a file GET /file/1 HTTP 1.1 Delete a file DELETE /file/1 HTTP 1.1 Update a file PUT /file/1 HTTP 1.1 { “id”: 1, “name”: “Documents2”, “parentId”: null, “folder”: true }
Request Mapping Example (II) Operation HTTP Request List top-level files GET /files HTTP 1.1 List files under a folder GET /files/1 HTTP 1.1 Add a file POST /files HTTP 1.1 { “id”: null, “name”: “Lab1.pdf”, “parentId”: 7, “folder”: false }
Implement RESTful Web Service In theory any web application technology would do, but in practice it should be Easy to handle request methods and request/response headers Easy to handle “path parameters” like /file/{id} Easy to handle data in XML and/or JSON format
Service Implementation – Know Your Libraries Modern webapp frameworks like Spring Jersey - https://jersey.java.net/ Convert between objects and XML/JSON Jackson - https://github.com/FasterXML/jackson Gson, JAXB, Simple XML Serialization …
Serialization/Marshalling and Deserialization/Unmarshalling Java Object XML/JSON De-serialization/ Un-marshalling
Service Access – Libraries on the Client Side HTTP client Client-side JavaScript for web applications Apache HttpClient for Java applications HttpUrlConnection for Android apps Various XML/JSON parsers, e.g. Jackson, XmlPullParser, JsonReader, …
Service Testing Browser addons/extensions Standalone clients E.g. RESTClient for Firefox and Advanced REST Client for Chrome Standalone clients Full-featured test software like Selenium
Service Implementation Using Jersey https://jersey.java.net/ A Java library for creating and accessing RESTful web services The reference implementation of the JAX-RS (Java API for RESTful Web Services) specification
Use Maven for Dependency Management Convert an Eclipse Dynamic Web Project to a Maven Project: right click on project -> Configure -> Convert to Maven Project Maven is a project management tool for Java Project Object Model (POM) Project Lifecycles Dependency Management Plugin Framework
Maven Coordinates groupId artifactId version packaging, default: jar Name of the company, organization, team etc., usually using the reverse URL naming convention artifactId A unique name for the project under groupId version packaging, default: jar classifier Maven coordinates uniquely identifies a project.
Why Not Just Use Project Name Rage-quit: Coder unpublished 17 lines of JavaScript and “broke the Internet”
Dependency Management A dependency of a project is a library that the project depends on Adding a dependency to a project is as simple as adding the coordinates of the library to pom.xml Maven automatically downloads the library from an online repository and store it locally for future use
Dependency Example Add a dependency to pom.xml <dependencies> <dependency> <groupId>javax.servlet</groupId> <artifactId>jstl</artifactId> <version>1.2</version> </dependency> </dependencies> Add a dependency to pom.xml Add a dependency in Eclipse
More About Dependency Management Dependencies of a dependency are automatically included Dependency conflicts are automatically resolved
Jersey Dependencies org.glassfish.jersey.containers:jersey-container-servlet org.glassfish.jersey.media:jersey-media-json-jackson
Example: Get File in Jersey URL: /service/file/{id} Basic Jersey terminology Dispatcher servlet Resource class Resource method (i.e. sub-resource) Provider Entity Provider
Understand Request Routing in Jersey /service/file/1 Request URI Servlet mapping for the Jersey dispatcher servlet in web.xml /service/* Path annotation for resource class @Path(“/file”) Path annotation for resource method (optional) @Path(“/{id}”)
Common Jersey Annotations … @Path @PathParam Map part of the path to an argument of a resource method @GET, @POST, @PUT, @DELETE
… Common Jersey Annotations @Produces Tell Jersey which data format the return value should be converted to Help mapping a request to a resource method based on the Accept header in the request Set the Content-Type header in response @Consumes Tell Jersey the data format of the data in the request body Help mapping a request to a resource method based on the Content-Type header in the request
Example: RESTful Web Service Implementation and Access Complete the rest of the operations Test the operations Implement AJAX Folder Expand
Run the Code Example Download the zip file from https://csns.calstatela.edu/download?fileId=5956689 Unzip it to a local folder In Eclipse, select File Import Existing Maven Project Follow the instructions in README.md In Eclipse, right click on the project and select Run As Run on Server
Application Deployment Deploy Application Computer for Development Server Hosting the Web Application
WAR Files Web application ARchive A JAR file for packaging, distributing, and deploying Java web applications Ways to create WAR files The command line tool jar Eclipse Export -> Web -> WAR file mvn package
Deploy WAR Files to a Tomcat Server Copy the WAR file to the webapps folder Use the Manager App Need a user with the manager-gui role More options at http://tomcat.apache.org/tomcat-8.5-doc/deployer-howto.html