REST

From Wiki RB4

Concept[edit]

Representational state transfer (REST) invented by Roy Fielding (inventor of HTTP) is a way to create, read, update or delete information on a server often using simple HTTP calls. REST provides guidance on how to implement web application interfaces to the web (s. Web Services). Typically, one says a web application is constructed in a REST-like way or not. REST is often associated (or implemented) with HTTP, but it could be implemented with other technologies too. REST is platform and language independent.

  • Resource – In REST everything is a resource. A logical resource is any concept (car, dog, user, invoice…) which can be addressed and referenced using a global identifier. Typically, each resource is accessible with a URI when implementing REST over HTTP (for example: http://www.mysite.com/invoice/34657). The preference is given to nouns rather than verbs to indicate the type of a resource (cat, dog, car…).A group of resources can also be accessed with a URI, for example: http://www.mysite.com/user/7723/invoices. REST allows that resources have different representations, e.g., text, XML, JSON etc. The REST client can ask for a specific representation via the HTTP protocol (content negotiation).
  • Server – A logical server is where resources are located, together with any corresponding data storage features. Such servers do not deal with end user interfaces (GUI).
  • Client – Logical clients make requests to logical servers to perform operations on their resources. For example, a client can request the state of the resource, create a resource, update a resource, delete a resource, etc… Clients do not possess resources or corresponding data storage features. However, they deal with end user interfaces (GUI).
  • Request and Responses – The interactions between client and servers is organized with requests from client to server, and responses to requests from server back to client. Requests can contain representations of the resource.
  • Representation – A representation is a document representing the current status of a resource. It can also be the new desired status when a client makes a request to update a resource, for example.

Exceptions[edit]

There is a general agreement that whatever ‘resource’ is required to implement authentication between the client and the server is considered out-of-scope for REST. These authentication resources do not have to follow REST principles

Principles[edit]

  • The state of a resource remains internal to the server, not the client – The client can request it, or update it with requests made to the server.
  • No client context saved on the server between requests – The server must not store the status of a client. Otherwise, this would break the scalability objective of REST when reaching a couple million users. Remember that requests can be distributed to several physical servers, which could cause physical resource consumption issues.
  • Client requests contain all information to service it – No matter which request is sent by a client to a server, it must be complete enough for the server to process it.
  • Session states are stored on the client side – If necessary, any information about the status of the communication between a logical server and a logical client must be held on the client side.
  • Multiple representations of a resource can coexist – The chosen format used to represent the state of a resource in requests and responses is free (XML, JSON…). Multiple formats can be used.
  • Responses explicitly indicate their cacheability – When a server returns a response to a request, the information it contains may or may not be cached by the client. If not, the client should make new requests to obtain the latest status of a resource, for example.
  • Code on Demand – This is an optional feature in REST. Clients can fetch some extra code from the server to enrich their functionalities. An example is Javascript.
  • send the right response, e.g. CREATE return code instead of SUCCESS code

There is a discussion ongoing which HTTP message type should be used for which actions. E.G. see here (see corresponding annotations below):

  • Use PUT to UPDATE data
  • Use POST to ADD data
  • Use DELETE to REMOVE data
  • Use GET to RETREIVE data

Sometimes there is a recommendation to use the PATCH message if parts are updated.

Another explanation is: choose between PUT and POST based on idempotence of the action. Idempotence means that calling the API multiple times it should be as a single modification, wheras Non-Idempotence means calling an API multiple times results in multiple resources.

so:

POST /expense-report

or:

PUT  /expense-report/10929

Web Application Description Language (WADL) is a machine-readable description of HTTP based REST web services, but is not popular. An alternative is Swagger.

Authentification[edit]

Implementations[edit]

JAX-RS[edit]

Java defines REST support via the JSR 311. This specification is called JAX-RS (The Java API for RESTful Web Services), kurz JAX-RS. Es handelt es sich um die Spezifikation einer Programmierschnittstelle (API) der Programmiersprache Java, die die Verwendung von REST im Rahmen von Webservices ermöglicht und vereinheitlicht. Wie auch andere Programmierschnittstellen der Java Platform Enterprise Edition (JEE) benutzt JAX-RS Annotationen, um die Entwicklung und das Deployment von Webservice-Clients und Service-Endpunkten zu vereinfachen.

Annotations[edit]

@javax.ws.rs.ApplicationPath(<Path>)[edit]

Class annotation which extends javax.wx.rs.core.Application instructs the container to look for JAX-RS annotated classes and install them as endpoints e.g.

@ApplicationPath("/rest")

will lead to

http://localhost:8080/MyFirstJEEWebProjectFromScratch/rest/<Services>
@javax.ws.rs.Path(<Path>)[edit]

The Path annotation in JAX-RS is used to define a URI matching pattern for incoming HTTP requests. It can be placed upon a class or on one or more Java methods. For a Java class to be eligible to receive any HTTP requests, the class must be annotated with at least the @Path("/") expression. These types of classes are called JAX-RS root resources.

To receive a request, a Java method must have at least an HTTP method annotation like @javax.ws.rs.GET applied to it. This method is not required to have an @Path annotation on it, though. So it gets called if the Path of the class matches.

@Path can also be applied to your Java method. If you do this, the URI matching pattern is a concatenation of the class’s @Path expression and that of the method’s.

see a detailled description here

Implementing a Restful Service with JAX-RS[edit]

  • implement an empty class with annoation like
@javax.ws.rs.ApplicationPath("/rest")
public class JaxRsActivator extends javax.ws.rs.Application { }
  • reuse BaseEntityService as base class of project uweheuer_new and define subclass like
@javax.ws.rs.Path("/notes")
@javax.ejb.Stateless // This is a stateless service, so a single shared instance can be used in this case.
public class NotesService extends BaseEntityService<Note>

The return type obviously depends on the purpose of the API. The procudure to set the return value depends of the outcome of API:

  1. Http codes: 404 requested resource does not exist, 400 the request is semantically incorrect, 401 the user is not authorized, 500 there is a problem with the database connection) via e.g.
return Response.status(Response.Status.NOT_FOUND).entity("...").build();
  1. Http code 201 created


  • annotate changing services like and return response applying the following patterns
@javax.ws.rs.POST
@javax.ws.rs.Consumes(MediaType.APPLICATION_JSON)
public Response saveNote(Note note)
{
  return Response.ok(); // creates a response with a status of 200 and an empty entity body.
  return Response.ok(entity).build(); // creates a response with a status of 200, stores the supplied object in the
                                      // responses entity body, and determines the entities media type by introspecting the object
  return Response.noContent().build(); // reating a response with a 204 status (no content)
}

Resources[edit]

  1. restful java with JAX-RS