CE303 Lecture 5
CE303 Lecture 5
CE303 Lecture 5
Advanced Programming
Somdip Dey
Today:
Web services: Exchanging information over the web
Overview
Web Services
Underlying resource can represent different media content types (MIME type)
- E.g. text/plain, text/html, text/javascript, image/png, video/mp4, audio/mpeg, application/pdf, application/octet-stream, multipart/form-data
Slide 7/N
HTTP Protocol specification - Requests
A single line consisting of:
- An HTTP method, that describes the action to be performed.
- E.g. a ‘verb’ such as GET, POST, PUT, DELETE, CONNECT or a ‘noun’ such as HEAD, OPTIONS, TRACE, PATCH.
- For a full list see: https://developer.mozilla.org/en-US/docs/Web/HTTP/Methods
- A request target, which could be a URL, or an absolute path to a file, relative to the host server’s web-root
- Typically a path, as the remaining components, i.e. protocol, domain, and port, are obvious from the context of the connection
- Specifying only a directory typically implies requesting the index.html file from the relevant directory by default
Optional headers
- Syntax: “Key: value”, one per line. E.g. “Host: example.com” (Host is the only mandatory header for HTTP/1.1), Content-type, Accept, etc.
- The start-line and optional headers are often collectively referred to as the ‘head’ of the request.
Slide 8/N
HTTP Request Example
Slide 9/N
HTTP Protocol specification - Responses
A single line consisting of Some HTTP Status Codes
- The version of the HTTP protocol used.
- A status code, indicating if the request was successful or not, and why. 2xx Success
200 OK
- A status message, acting as a short description of the status code.
204 No Content
Slide 10/N
HTTP Request Methods
GET
- The GET method requests a representation of the specified resource. Requests using GET should only retrieve data.
POST
- The POST method submits an entity to the specified resource, often causing a change in state or side effects on the server.
PUT
- The PUT method replaces all current representations of the target resource with the request payload.
DELETE
- The DELETE method deletes the specified resource.
HEAD
- The HEAD method asks for a response identical to a GET request, but without the response body.
CONNECT
- The CONNECT method establishes a tunnel to the server identified by the target resource.
OPTIONS
- The OPTIONS method describes the communication options for the target resource.
TRACE
- The TRACE method performs a message loop-back test along the path to the target resource.
PATCH
- The PATCH method applies partial modifications to a resource.
GET requests should be preferred choice for queries that do not modify data
The URL can encode parameters (“query string”) which are decomposed on the
server (“URL rewriting”):
- http://www.mysite.org/myservice?fName=Fred&sName=Flintstone
Slide 12/N
POST Requests
They often originate from HTML elements where the method is set to POST:
POST requests should be used preferably when you want to create or modify data
Slide 13/N
GET vs POST comparison
GET
- Appends the form data to the URL, in name/value pairs
- NEVER use GET to send sensitive data! (the submitted form data is visible in the URL!)
POST
- Appends the form data inside the body of the HTTP request
- The submitted form data is not shown in the URL
- POST has no size limitations, and can be used to send large amounts of data.
- Form submissions with POST cannot be bookmarked
Slide 14/N
Media Types and Content Negotiation
HTTP clients can specify:
- the media type they are sending, and
- the media type they expect in the response of the server
- E.g. see Content-Type / Accept headers
But. Does the travel agent have access to the airline’s database?
- No. The airline provides an ‘interface’ (interaction protocol?) for requests
- The travel agent transforms your request to the kind expected by the airline’s API.
- The airline provider responds appropriately with a useful resource (JSON?)
No requirement for the travel agent and many different airlines to be implemented
in the same language / stack.
- As long as they can handle requests and respond in a useful manner
Slide 19/N
Web Applications vs Web Services
A Web Application:
- Is for human users.
- Typically a complete application
- Involves interaction with a browser or other front-end / Graphical User Interface (GUI).
A Web Service:
- Generally not intended for direct human consumption
- Provides some “computational service” for the purpose of machine-to-machine interaction via HTTP(S), e.g. data transfer between Web Applications.
Slide 20/N
Web Service Communication styles
Why “REST”?
- Representational – because it leverages HTTPs existing ability to deal with many ‘representation types’ (i.e.
html, xml, json)
- Each object at the end of a URI corresponds to a particular ‘representation’ of a resource, which can be of a specific type of resource.
- Transfer, because this representation in this specific state can be transferred between web services.
Slide 21/N
So what exactly classifies as RESTful?
W3 consortium definition:
“The REST Web is the subset of the WWW (based on HTTP) in which agents provide uniform interface semantics -- essentially
create, retrieve, update and delete -- rather than arbitrary or application-specific interfaces, and manipulate resources only by the
exchange of representations. Furthermore, the REST interactions are "stateless" in the sense that the meaning of a message does not
depend on the state of the conversation.
REST-compliant Web services, in which the primary purpose of the service is to manipulate XML representations of Web
resources using a uniform set of "stateless" operations; and
Arbitrary Web services, in which the service may expose an arbitrary set of operations.
Both classes of Web services use URIs to identify resources and use Web protocols (such as HTTP and SOAP 1.2) and XML data
formats for messaging”
Source: https://www.w3.org/TR/2004/NOTE-ws-arch-20040211/#relwwwrest
Slide 22/N
So what exactly classifies as RESTful?
“A RESTful web service (also called a RESTful web API) is a web service implemented using HTTP
and the principles of REST. It is a collection of resources, with four defined aspects:
Source: https://stackoverflow.com/a/12728166
Slide 23/N
REST Architectural elements
Stateless protocols
- Each interaction is independent; a response/request pair is all that is required to complete that interaction.
- Therefore no session information (i.e. on past requests) needs to be stored by the server.
Other:
- Use of standard content types: JSON, XML, text, ...
- Use of web features: HTTP status codes, caching, …
- Aims: simplicity, efficiency/scalability, re-use
Slide 24/N
RESTful principles – URIs and HTTP Methods
Slide 25/N
Part III:
Web Services in Java, using JAX-RS / Jersey
Web Services using JAX-RS / Jersey
Slide 27/N
JAX-RS Fundamentals
These are the methods which are invoked in response to HTTP requests
Slide 28/N
Slide 29/N
What are annotations?
Slide 30/N
What are annotations?
Slide 31/N
What are annotations?
Slide 32/N
What are annotations?
What are annotations?
Slide 33/N
JAX-RS Fundamentals
These are the methods which are invoked in response to HTTP requests
- Note: The methods themselves are never invoked by name. They are invoked instead via reflection.
Slide 34/N
Some Basic JAX-RS Annotations
Content negotiation
- @Consumes specifies one or more media types a resource can accept (“consume”) from the client
- @Produces specifies one or more media types a resource can “produce” and send back to the client
Slide 35/N
Deployment, Testing,
and Clients for RESTful Web Services
Jersey web services need to be deployed on a web server
Both the web server and Jersey can be configured extensively
Once the server has started, the web services can be accessed via HTTP
The curl command line tool can easily generate HTTP requests for testing
curl -H "Accept: text/plain" http://localhost:8080/examples/rest/hello/Sam
Slide 36/N
Invoking RESTful Services from Java
Typical usage
- Create a Web Target pointing at a Web resource
- Build the request
- Submit request and process the response
Usage considerations:
- Web target creation includes building a client
- This can have an associated configuration such as setting of message handlers and logging levels
- Request building may involve construction of entities that are passed in the body
- Especially relevant for POST and PUT requests
Slide 37/N
package webserver;
import java.io.File;
import javax.servlet.ServletException;
import org.apache.catalina.Context;
import org.apache.catalina.LifecycleException;
import org.apache.catalina.startup.Tomcat;
import org.glassfish.jersey.logging.LoggingFeature;
import org.glassfish.jersey.server.ResourceConfig;
import org.glassfish.jersey.servlet.ServletContainer;
public TomcatServer() {
}
import javax.ws.rs.Consumes;
import javax.ws.rs.FormParam;
import javax.ws.rs.GET;
import javax.ws.rs.POST;
import javax.ws.rs.Path;
import javax.ws.rs.PathParam;
import javax.ws.rs.Produces;
import javax.ws.rs.QueryParam;
import javax.ws.rs.core.MediaType;
@Path("/hello")
public class HelloServer {
@GET
@Path("/{name}")
@Produces(MediaType.TEXT_PLAIN)
public String helloPlain(@PathParam("name") String name) {
return "Hello, " + name + "!";
}
@GET
@Produces(MediaType.APPLICATION_JSON)
Slide 39/N
package hello;
import javax.ws.rs.client.ClientBuilder;
import javax.ws.rs.client.Entity;
import javax.ws.rs.client.WebTarget;
import javax.ws.rs.core.Form;
import javax.ws.rs.core.MediaType;
import webserver.TomcatServer;
public HelloClient() {
webTarget = ClientBuilder.newClient().target(TomcatServer.HELLO_URL);
}
RESTful web services have become popular in recent years, especially for “public
facing” web services
They are supported in many different programming languages and web application
frameworks
Slide 41/N
Summary
Web Services
essex.ac.uk