Making Java REST
with JAX-RS 2.0
April 24, 2014	

Dmytro Chyzhykov
Disclaimer
The views and opinions expressed in this
presentation expressed by the speaker are solely his
own and do not necessary represent the views and
opinions of companies he is working or worked for.
3
Agenda
- What is REST?
- REST Principles and JAX-RS 2.0
- Q & A
4
HTTP
Response	

200 OKJSON
Media Type
Client ServerHTTP GET
Resources
Request http://example.com
Read more Hypertext Transfer Protocol -- HTTP/1.1
5
What is REST?
6
REST?
7
REST JEE7 Definition
REpresentational State Transfer is an
architectural style of client-server applications
centered around the transfer of representations
of resources through requests and responses.
Serves to build loosely coupled, lightweight web
services that are particularly well suited for creating
APIs for clients spread out across the Internet.
Was introduced and defined by Roy T. Fielding in
his doctoral dissertation.
Read more The Java EE 7 Tutorial: 29.1 What Are RESTful Web Services?
8
REST is...
- An architectural style, not a technology
- Everything is a Resource
- Suitable for CRUD (Create/Read/Update/Delete)
- Stateless by nature (excellent for distributed
systems)
- Cacheable (naturally supported by HTTP)
- Composable code on demand applications
9
REST Principles
- Give every thing its own ID
- Link things together (HATEOAS)
- Use standard HTTP methods
- Resources can have multiple representations 
- Communicate statelessly
- Support caching
10
Give every thing its own ID
11
Individual Resource ID
http://habrahabr.ru/users/theshade/!
https://twitter.com/fielding!
https://api.github.com/teams/46059!
Collection Resource ID
https://api.github.com/teams/!
https://twitter.com/fielding/followers!
https://api.github.com/user/repos?page=2!
http://ajax.googleapis.com/ajax/services/
search/web?v=1.0&q=Paris%20Hilton
12
JAXRS 2.0 resource example
GET http://locahost:8080/articles/7!
GET http://locahost:8080/articles/!
GET http://locahost:8080/articles/?page=1!
13
JAXRS 2.0 resource example
GET http://locahost:8080/articles/7!
GET http://locahost:8080/articles/!
GET http://locahost:8080/articles/?page=1!
@Path("articles")
public class ArticleResource {
}
14
JAXRS 2.0 resource example
GET http://locahost:8080/articles/7!
GET http://locahost:8080/articles/!
GET http://locahost:8080/articles/?page=1!
@Path("articles")
public class ArticleResource {
@GET
@Path("{id}")
public Article read(@PathParam("id") int id) {…}
}
15
JAXRS 2.0 resource example
GET http://locahost:8080/articles/7!
GET http://locahost:8080/articles/!
GET http://locahost:8080/articles/?page=1!
@Path("articles")
public class ArticleResource {
@GET
@Path("{id}")
public Article read(@PathParam("id") int id) {…}
@GET
public List<Article> list(@QueryParam("page")
@DefaultValue("1")
int page) {…}
}
16
Article POJO
public class Article {
private Integer id;
private String title;
private String content;
!
// Getters and setters go here
}
17
Let's try
$ curl -X GET http://localhost:8080/articles/7!
{!
"id": 7,!
"title": "REST Individual Resource",!
"content": "REST Individual Resource example"!
}
$ curl -X GET http://localhost:8080/articles/!
[!
{!
"id": 7,!
"title": "REST Individual Resource",!
"content": "REST Individual Resource example"!
}!
]
18
Link things together
19
HATEOAS
HATEOAS is abbreviation for Hypermedia as the
Engine of Application State.

A hypermedia-driven site provides information to
navigate the site's REST interfaces dynamically by
including hypermedia links with the responses.
Read more Why hypermedia APIs? and Understanding HATEOAS
20
Atom Links Style
<article id="123">
<title>Hypermedia and JAX-RS 2.0</title>
<content>JAX-RS 2.0 supports Hypermedia …</content>
!
<link rel="self" href=“/articles/123/" />
<link rel="update" href=“/articles/123/" />
<link rel="delete" href=“/articles/123/" />
<link rel="list" href=“/articles/“ />
!
</article>
Read more Atom Format Link Relation Extensions
21
Link Headers Style
HTTP/1.1 200 OK
Content-Type: application/xml
Link: </articles/123/>; rel=self;
Link: </articles/123/>; rel=update;
Link: </articles/123/>; rel=delete;
Link: </articles/>; rel=list;
!
<article id="123">
<title>Hypermedia and JAX-RS 2.0</title>
<content>JAX-RS 2.0 supports Hypermedia …</content>
</article>
Read more Web Linking:The Link Header Field
22
How to Imaging HATEOAS
23
How to Imaging HATEOAS
24
JAX-RS 2.0 HATEOAS
@POST
@Consumes({"application/json", "application/xml"})
@Produces({"application/json", "application/xml"})
public Response create(Article article) {
Article created = articleDao.create(article);
return Response
.ok(created)
.link("link-URI", “link-rel")
.links(produceLinks(created))
.build();
}
!
private Link[] produceLinks(Article article) {...}
Read more javax.ws.rs.core.Link
25
Jersey 2.x HATEOAS
public class Article {
@InjectLinks({
@InjectLink(resource = ArticleResource.class,
rel = "self", method = "read"),
@InjectLink(resource = ArticleResorce.class,
rel = "edit", method = "update"),
@InjectLink(resource = ArticleResource.class,
rel = "delete", method = "delete"),
@InjectLink(resource = ArticleResource.class,
rel = "list", method = “list")
})
private List<Link> links;
!
Read more Jersey 2.x Chapter 12. Declarative Hyperlinking
26
Let's try
$ curl -X GET “http://localhost:8080/articles/123"
{
"id": 123,
"title": "Hypermedia and JAX-RS 2.0",
"content": "JAX-RS 2.0 supports Hypermedia …",
"links": [
{ "uri": "/articles/",
"rel": "self" },
{ "uri": "/articles/",
"rel": "edit" },
{ "uri": "/articles/",
"rel": "delete" },
{ "uri": "/articles",
"rel": “list"}]
}
27
Use standard HTTP methods
Method Purpose
GET Read representation of the specified resource
POST Create or Update without a know ID
PUT Update or Create with a know ID
DELETE Remove
HEAD GET with no response, just metadata
OPTIONS Supported methods for the specified URL.
28
HTTP methods and JAX-RS 2.0
Method Annotation
POST @POST
GET @GET
PUT @PUT
DELETE @DELETE
HEAD @HEAD
OPTIONS @OPTIONS
29
Multiple Representations
30
Content Negotiation
GET http://example.com/stuff
Accept: application/xml, application/json, text/*
Give me resource contents as (in priority):
1. XML
2. or JSON
3. or any text content type you can
4. or return 406 Not Acceptable Error 

otherwise
31
Content Negotiation Example
curl -X POST "http://localhost:8080/articles" 
-H "Content-Type: application/xml" 
-d "<article> 
<title>Conneg and JAX-RS 2.0</title> 
<content> 
JAX-RS 2.0 supports Conneg… 
</content> 
</article>" 
-H "Accept: application/json"
{
"id": 7,
"title": "Conneg and JAX-RS 2.0",
"content": "JAX-RS 2.0 supports Conneg …"
}
32
Content Negotiation Example
curl -X POST "http://localhost:8080/articles" 
-H "Content-Type: application/xml" 
-d "<article> 
<title>Conneg and JAX-RS 2.0</title> 
<content> 
JAX-RS 2.0 supports Conneg… 
</content> 
</article>" 
-H "Accept: application/json"
{
"id": 7,
"title": "Conneg and JAX-RS 2.0",
"content": "JAX-RS 2.0 supports Conneg …"
}
33
Content Negotiation Example
@POST
@Consumes({"application/json", "application/xml"})
@Produces({"application/json", "application/xml"})
public Article create(Article article) {
return articleDao.create(article);
}
34
Language Negotiation
GET http://example.com/stuff
Accept-Language: en-us, en, ru
Encoding Negotiation
GET http://example.com/stuff
Accept-Encoding: gzip, deflate
35
Communicate Statelessly
36
State is Bad
Client
Load
Balancer
Server 1
Sessions
Server 3
Sessions
Server 2
Sessions
37
State is Bad
Client
Load
Balancer
Server 1
Sessions
Server 3
Sessions
Server 2
Sessions
Replication
Replication
38
State is Bad
Client
Load
Balancer
Server 1
Sessions
Server 3
Sessions
Server 2
Sessions
Replication
Replication
ItD
oesN
otScale 39
Communicate statelessly
Client
Load
Balancer
Server 1
Server 3
Server 2 Token	

Storage
40
Caching Support
“The best requests are those
that not even reach me”
- Anonymous overloaded Server
41
Caching Benefits
- Reduce bandwidth
- Reduce latency
- Reduce load on servers
- Hide network failures
42
Caching
Client	

Client

Cache	

Proxy

Cache	

Server
Reverse

Proxy

Cache	

Client	

Client

Cache	

Client	

Client

Cache	

43
HTTP Caching
GET http://example.com/stuff
!
< HTTP/1.1 200 OK
< Cache-Control: max-age=60
Cache-Control: max-age=<delta-seconds>

| s-max-age=<delta-seconds>

| no-cache

| no-store

| …
Read more Caching in HTTP
44
JAX-RS 2.0 Cache Control
Directive Usage
max-age cache.setMaxAge(int maxAge)
s-max-age cache.setSMaxAge(int maxAge)
no-cache cache.setNoCache(boolean noCache)
no-store cache.setNoStore(boolean noStore)
… …
CacheControl cache = new CacheControl();
Read more javax.ws.rs.core.CacheControl
45
Caching and JAX-RS 2.0
@GET
@Path("{id}")
public Response read(@PathParam("id") int id) {
Article article = articleDao.findById(id);
CacheControl cacheControl = new CacheControl();
cacheControl.setMaxAge(60);
!
return Response.ok(article)
.cacheControl(cacheControl)
.build();
}
46
Let's try
curl -X GET "http://localhost:8081/rest/articles/8"
-H "Accept: application/json" -v
< HTTP/1.1 200 OK
< Cache-Control: max-age=60
< Content-Type: application/json
<
{
"id": 8,
"title": "HTTP Caching and JAX-RS 2.0",
"content": "JAX-RS 2.0 supports HTTP Caching"
}
47
Wrapping Up
JAX-RS 2.0 is a POJO-based HTTP-centric
annotation-driven specification for for RESTful Web
Services.

Makes the developer focus on URLs, HTTP
methods and Media Types.
Implementations:
- Apache CXF
- Jersey
- RESTeasy
- Restlet
- others
48
Q & A
49
Thank you!
50
Старший Разработчик
Киноплатформы
Дмитрий Чижиков
dmytro.chyzhykov@yandex.ru
ffbit

Making Java REST with JAX-RS 2.0

  • 2.
    Making Java REST withJAX-RS 2.0 April 24, 2014 Dmytro Chyzhykov
  • 3.
    Disclaimer The views andopinions expressed in this presentation expressed by the speaker are solely his own and do not necessary represent the views and opinions of companies he is working or worked for. 3
  • 4.
    Agenda - What isREST? - REST Principles and JAX-RS 2.0 - Q & A 4
  • 5.
    HTTP Response 200 OKJSON Media Type ClientServerHTTP GET Resources Request http://example.com Read more Hypertext Transfer Protocol -- HTTP/1.1 5
  • 6.
  • 7.
  • 8.
    REST JEE7 Definition REpresentationalState Transfer is an architectural style of client-server applications centered around the transfer of representations of resources through requests and responses. Serves to build loosely coupled, lightweight web services that are particularly well suited for creating APIs for clients spread out across the Internet. Was introduced and defined by Roy T. Fielding in his doctoral dissertation. Read more The Java EE 7 Tutorial: 29.1 What Are RESTful Web Services? 8
  • 9.
    REST is... - Anarchitectural style, not a technology - Everything is a Resource - Suitable for CRUD (Create/Read/Update/Delete) - Stateless by nature (excellent for distributed systems) - Cacheable (naturally supported by HTTP) - Composable code on demand applications 9
  • 10.
    REST Principles - Giveevery thing its own ID - Link things together (HATEOAS) - Use standard HTTP methods - Resources can have multiple representations - Communicate statelessly - Support caching 10
  • 11.
    Give every thingits own ID 11
  • 12.
    Individual Resource ID http://habrahabr.ru/users/theshade/! https://twitter.com/fielding! https://api.github.com/teams/46059! CollectionResource ID https://api.github.com/teams/! https://twitter.com/fielding/followers! https://api.github.com/user/repos?page=2! http://ajax.googleapis.com/ajax/services/ search/web?v=1.0&q=Paris%20Hilton 12
  • 13.
    JAXRS 2.0 resourceexample GET http://locahost:8080/articles/7! GET http://locahost:8080/articles/! GET http://locahost:8080/articles/?page=1! 13
  • 14.
    JAXRS 2.0 resourceexample GET http://locahost:8080/articles/7! GET http://locahost:8080/articles/! GET http://locahost:8080/articles/?page=1! @Path("articles") public class ArticleResource { } 14
  • 15.
    JAXRS 2.0 resourceexample GET http://locahost:8080/articles/7! GET http://locahost:8080/articles/! GET http://locahost:8080/articles/?page=1! @Path("articles") public class ArticleResource { @GET @Path("{id}") public Article read(@PathParam("id") int id) {…} } 15
  • 16.
    JAXRS 2.0 resourceexample GET http://locahost:8080/articles/7! GET http://locahost:8080/articles/! GET http://locahost:8080/articles/?page=1! @Path("articles") public class ArticleResource { @GET @Path("{id}") public Article read(@PathParam("id") int id) {…} @GET public List<Article> list(@QueryParam("page") @DefaultValue("1") int page) {…} } 16
  • 17.
    Article POJO public classArticle { private Integer id; private String title; private String content; ! // Getters and setters go here } 17
  • 18.
    Let's try $ curl-X GET http://localhost:8080/articles/7! {! "id": 7,! "title": "REST Individual Resource",! "content": "REST Individual Resource example"! } $ curl -X GET http://localhost:8080/articles/! [! {! "id": 7,! "title": "REST Individual Resource",! "content": "REST Individual Resource example"! }! ] 18
  • 19.
  • 20.
    HATEOAS HATEOAS is abbreviationfor Hypermedia as the Engine of Application State.
 A hypermedia-driven site provides information to navigate the site's REST interfaces dynamically by including hypermedia links with the responses. Read more Why hypermedia APIs? and Understanding HATEOAS 20
  • 21.
    Atom Links Style <articleid="123"> <title>Hypermedia and JAX-RS 2.0</title> <content>JAX-RS 2.0 supports Hypermedia …</content> ! <link rel="self" href=“/articles/123/" /> <link rel="update" href=“/articles/123/" /> <link rel="delete" href=“/articles/123/" /> <link rel="list" href=“/articles/“ /> ! </article> Read more Atom Format Link Relation Extensions 21
  • 22.
    Link Headers Style HTTP/1.1200 OK Content-Type: application/xml Link: </articles/123/>; rel=self; Link: </articles/123/>; rel=update; Link: </articles/123/>; rel=delete; Link: </articles/>; rel=list; ! <article id="123"> <title>Hypermedia and JAX-RS 2.0</title> <content>JAX-RS 2.0 supports Hypermedia …</content> </article> Read more Web Linking:The Link Header Field 22
  • 23.
    How to ImagingHATEOAS 23
  • 24.
    How to ImagingHATEOAS 24
  • 25.
    JAX-RS 2.0 HATEOAS @POST @Consumes({"application/json","application/xml"}) @Produces({"application/json", "application/xml"}) public Response create(Article article) { Article created = articleDao.create(article); return Response .ok(created) .link("link-URI", “link-rel") .links(produceLinks(created)) .build(); } ! private Link[] produceLinks(Article article) {...} Read more javax.ws.rs.core.Link 25
  • 26.
    Jersey 2.x HATEOAS publicclass Article { @InjectLinks({ @InjectLink(resource = ArticleResource.class, rel = "self", method = "read"), @InjectLink(resource = ArticleResorce.class, rel = "edit", method = "update"), @InjectLink(resource = ArticleResource.class, rel = "delete", method = "delete"), @InjectLink(resource = ArticleResource.class, rel = "list", method = “list") }) private List<Link> links; ! Read more Jersey 2.x Chapter 12. Declarative Hyperlinking 26
  • 27.
    Let's try $ curl-X GET “http://localhost:8080/articles/123" { "id": 123, "title": "Hypermedia and JAX-RS 2.0", "content": "JAX-RS 2.0 supports Hypermedia …", "links": [ { "uri": "/articles/", "rel": "self" }, { "uri": "/articles/", "rel": "edit" }, { "uri": "/articles/", "rel": "delete" }, { "uri": "/articles", "rel": “list"}] } 27
  • 28.
    Use standard HTTPmethods Method Purpose GET Read representation of the specified resource POST Create or Update without a know ID PUT Update or Create with a know ID DELETE Remove HEAD GET with no response, just metadata OPTIONS Supported methods for the specified URL. 28
  • 29.
    HTTP methods andJAX-RS 2.0 Method Annotation POST @POST GET @GET PUT @PUT DELETE @DELETE HEAD @HEAD OPTIONS @OPTIONS 29
  • 30.
  • 31.
    Content Negotiation GET http://example.com/stuff Accept:application/xml, application/json, text/* Give me resource contents as (in priority): 1. XML 2. or JSON 3. or any text content type you can 4. or return 406 Not Acceptable Error 
 otherwise 31
  • 32.
    Content Negotiation Example curl-X POST "http://localhost:8080/articles" -H "Content-Type: application/xml" -d "<article> <title>Conneg and JAX-RS 2.0</title> <content> JAX-RS 2.0 supports Conneg… </content> </article>" -H "Accept: application/json" { "id": 7, "title": "Conneg and JAX-RS 2.0", "content": "JAX-RS 2.0 supports Conneg …" } 32
  • 33.
    Content Negotiation Example curl-X POST "http://localhost:8080/articles" -H "Content-Type: application/xml" -d "<article> <title>Conneg and JAX-RS 2.0</title> <content> JAX-RS 2.0 supports Conneg… </content> </article>" -H "Accept: application/json" { "id": 7, "title": "Conneg and JAX-RS 2.0", "content": "JAX-RS 2.0 supports Conneg …" } 33
  • 34.
    Content Negotiation Example @POST @Consumes({"application/json","application/xml"}) @Produces({"application/json", "application/xml"}) public Article create(Article article) { return articleDao.create(article); } 34
  • 35.
    Language Negotiation GET http://example.com/stuff Accept-Language:en-us, en, ru Encoding Negotiation GET http://example.com/stuff Accept-Encoding: gzip, deflate 35
  • 36.
  • 37.
    State is Bad Client Load Balancer Server1 Sessions Server 3 Sessions Server 2 Sessions 37
  • 38.
    State is Bad Client Load Balancer Server1 Sessions Server 3 Sessions Server 2 Sessions Replication Replication 38
  • 39.
    State is Bad Client Load Balancer Server1 Sessions Server 3 Sessions Server 2 Sessions Replication Replication ItD oesN otScale 39
  • 40.
  • 41.
    Caching Support “The bestrequests are those that not even reach me” - Anonymous overloaded Server 41
  • 42.
    Caching Benefits - Reducebandwidth - Reduce latency - Reduce load on servers - Hide network failures 42
  • 43.
  • 44.
    HTTP Caching GET http://example.com/stuff ! <HTTP/1.1 200 OK < Cache-Control: max-age=60 Cache-Control: max-age=<delta-seconds>
 | s-max-age=<delta-seconds>
 | no-cache
 | no-store
 | … Read more Caching in HTTP 44
  • 45.
    JAX-RS 2.0 CacheControl Directive Usage max-age cache.setMaxAge(int maxAge) s-max-age cache.setSMaxAge(int maxAge) no-cache cache.setNoCache(boolean noCache) no-store cache.setNoStore(boolean noStore) … … CacheControl cache = new CacheControl(); Read more javax.ws.rs.core.CacheControl 45
  • 46.
    Caching and JAX-RS2.0 @GET @Path("{id}") public Response read(@PathParam("id") int id) { Article article = articleDao.findById(id); CacheControl cacheControl = new CacheControl(); cacheControl.setMaxAge(60); ! return Response.ok(article) .cacheControl(cacheControl) .build(); } 46
  • 47.
    Let's try curl -XGET "http://localhost:8081/rest/articles/8" -H "Accept: application/json" -v < HTTP/1.1 200 OK < Cache-Control: max-age=60 < Content-Type: application/json < { "id": 8, "title": "HTTP Caching and JAX-RS 2.0", "content": "JAX-RS 2.0 supports HTTP Caching" } 47
  • 48.
    Wrapping Up JAX-RS 2.0is a POJO-based HTTP-centric annotation-driven specification for for RESTful Web Services.
 Makes the developer focus on URLs, HTTP methods and Media Types. Implementations: - Apache CXF - Jersey - RESTeasy - Restlet - others 48
  • 49.
  • 50.
  • 51.