Location via proxy:   [ UP ]  
[Report a bug]   [Manage cookies]                
SlideShare a Scribd company logo
July 29, 2017
Kumaraswamy Gowda
Software Architect, PSL
Build RESTful
application
with JAX-RS
Agenda
2
• What is REST
• REST principles
• Java API for RESTful Web Services (JAX-RS, defined in
JSR 311)
• HTTP Methods
• Annotations
• Client APIs
• SWAGGER – Expose and Test REST API
HTTP Example
3
Request
GET /music/artists/beatles/recordings HTTP/1.1
Host: media.example.com
Accept: application/xml
Response
HTTP/1.1 200 OK
Date: Sat, 08 Jul 2017 16:41:58 GMT
Content-Type: application/xml(or json); charset=UTF-8
<?xml version="1.0"?>
<recordings xmlns="…">
<recording>…</recording>
…
</recordings>
Method Resource
Representation
State
transfer
{
"recordings": {
"recording": [
{},
{}
]
}
}
What is REST
4
• REpresentational State Transfer is an architectural style
for building online applications
• First described by Roy Fielding in his doctoral dissertation
in 2000
• Lightweight, Scalable and maintainable
• Stateless by nature
• Client server protocol, almost always HTTP
• Clients can be any programming language
REST architecture for Web
5
Resources
Web Container
Resources
Web Container
REST Principles
6
• Everything is a resource
• Assign everything an ID
• Uniform Interface- fixed set of four
create, read, update, delete operations
o PUT, GET, POST, and DELETE
• Representation of the Resource
o JSON, XML, TEXT
/reports
--------------------
GET – list all reports
PUT – not supported
POST – create a report
DELETE – not supported
/reports/{id}
--------------------
GET – get report details
PUT – update report
POST – not supported
DELETE – delete a report
{
"recordings": {
"recording": [
{},
{}
]
}
}
<?xml version="1.0"?>
<recordings xmlns="…">
<recording>…</recording>
…
</recordings>
REST Principles contd…
7
• Stateless
• Link
o /reports to contain links to all reports like /reports/1,
/reports/2
• Pagination
o Limit data per request
o Enables clients to navigate forward or backward
• Caching
• Fields, sorting, filtering, versioning
JAX-RS (2.0)
8
• Java API for RESTful Web Services (JAX-RS, defined in
JSR 311)
• Designed to make it easy to develop applications that use
the REST architecture
• Implementations
o Jersey
o Apache CXF
o Apache Wink
o Restlet
• JAX-RS uses annotations available from Java SE 5
Annotations
9
• @Path
o Sets path to base URL +
@Path value
o https://server:port/eclipseapp
/api/reports
o @Path(“/reports”/{id})
o @Path("/username/{usernam
e : [a-zA-Z][a-zA-Z_0-9]}")
o @Path("{id : d+}")
@GET, @POST, @PUT, @DELETE
10
/reports – GET POST
/reports/{reportid} – GET, DELETE, PUT
/reports/{reportid}/templates
/reports/{reportid}/templates/{templateid}
@Produces and @Consumes
11
• MIME type content returned
• Equivalent to Content-type response header
@PathParam @QueryParam @HeaderParam
@FormDataParam @FormParam
12
• Binds values from request to the parameter
Deployment Descriptor (web.xml)
13
<servlet>
<servlet-name>JAX-RS Servlet</servlet-name>
<servlet-class>com.sun.jersey.spi.container.servlet.ServletContainer</servlet-class>
<init-param>
<param-name>com.sun.jersey.config.property.packages</param-name>
<param-value>com.abc.xyz.services</param-value>
</init-param>
<init-param>
<param-name>javax.ws.rs.Application</param-name>
<param-value>com.abc.xyz.service.MyApplication</param-value>
</init-param>
</servlet>
<servlet-mapping>
<servlet-name>JAX-RS Servlet</servlet-name>
<url-pattern>/api/*</url-pattern>
</servlet-mapping>
Client APIs
14
• Remember URLConnection? Or apache http client
libraries?
• Fluent API available from JAX-RS 2.0
Client
Builder
Client
Web
Target
Request
Building
Response..
SWAGGER
API developer tools for the OpenAPI Specification
15
What is Swagger and Why Swagger?
16
• Simple representation of your RESTFul API
• Declarative resource specification
• JSON specification
• Developers and documentation… hahaha
• Why Jersey Client / JUNIT or Rest Client (Poster /
Postman) or API document for your client or boss?
• Swagger UI to interact with the API in a sandbox UI
• Support your existing RESTFul API without change
Swagger Specification
17
Web Services
• Resource Listing
• API Description
Create Swagger Specification
• Manually - writing the JSON by hand
• Codgen - converts annotations in your code into swagger
specification
Swagger Specifications
18
19
Swagger Tools
20
Adjacent tools also provided by the
Swagger project are
Tool Description
Swagger JS Javascript library for consuming Swagger-defined APIs from both client and node.js app
Swagger Node Swagger module for node.js
Swagger-Socket expose/invoke Swagger defined APIs over WebSockets
Swagger Parser Standalone library for parsing Swagger definitions from Java
Tools for nearly every language and
allows you to deploy server instances
to get your API up and running -
Clojure, Go, JS, Java, .Net, Node,
PHP, Python, Ruby, Scala
References
21
• http://docs.oracle.com/javaee/6/tutorial/doc/giepu.html
• http://www.vogella.com/tutorials/REST/article.html
• https://jersey.java.net/documentation/latest/jaxrs-
resources.html
• https://github.com/koushikkothagal/messenger
• http://swagger.io/specification/
• https://github.com/swagger-api/swagger-spec
• https://github.com/swagger-api/swagger-core
• http://petstore.swagger.io/
22
Thanks!
Any questions?
You can find me at
➝https://www.linkedin.com/in/kumaraswamym/
➝kumaraswamy.m@gmail.com
RESTful application with JAX-RS and how to expose and test them

More Related Content

RESTful application with JAX-RS and how to expose and test them

  • 1. July 29, 2017 Kumaraswamy Gowda Software Architect, PSL Build RESTful application with JAX-RS
  • 2. Agenda 2 • What is REST • REST principles • Java API for RESTful Web Services (JAX-RS, defined in JSR 311) • HTTP Methods • Annotations • Client APIs • SWAGGER – Expose and Test REST API
  • 3. HTTP Example 3 Request GET /music/artists/beatles/recordings HTTP/1.1 Host: media.example.com Accept: application/xml Response HTTP/1.1 200 OK Date: Sat, 08 Jul 2017 16:41:58 GMT Content-Type: application/xml(or json); charset=UTF-8 <?xml version="1.0"?> <recordings xmlns="…"> <recording>…</recording> … </recordings> Method Resource Representation State transfer { "recordings": { "recording": [ {}, {} ] } }
  • 4. What is REST 4 • REpresentational State Transfer is an architectural style for building online applications • First described by Roy Fielding in his doctoral dissertation in 2000 • Lightweight, Scalable and maintainable • Stateless by nature • Client server protocol, almost always HTTP • Clients can be any programming language
  • 5. REST architecture for Web 5 Resources Web Container Resources Web Container
  • 6. REST Principles 6 • Everything is a resource • Assign everything an ID • Uniform Interface- fixed set of four create, read, update, delete operations o PUT, GET, POST, and DELETE • Representation of the Resource o JSON, XML, TEXT /reports -------------------- GET – list all reports PUT – not supported POST – create a report DELETE – not supported /reports/{id} -------------------- GET – get report details PUT – update report POST – not supported DELETE – delete a report { "recordings": { "recording": [ {}, {} ] } } <?xml version="1.0"?> <recordings xmlns="…"> <recording>…</recording> … </recordings>
  • 7. REST Principles contd… 7 • Stateless • Link o /reports to contain links to all reports like /reports/1, /reports/2 • Pagination o Limit data per request o Enables clients to navigate forward or backward • Caching • Fields, sorting, filtering, versioning
  • 8. JAX-RS (2.0) 8 • Java API for RESTful Web Services (JAX-RS, defined in JSR 311) • Designed to make it easy to develop applications that use the REST architecture • Implementations o Jersey o Apache CXF o Apache Wink o Restlet • JAX-RS uses annotations available from Java SE 5
  • 9. Annotations 9 • @Path o Sets path to base URL + @Path value o https://server:port/eclipseapp /api/reports o @Path(“/reports”/{id}) o @Path("/username/{usernam e : [a-zA-Z][a-zA-Z_0-9]}") o @Path("{id : d+}")
  • 10. @GET, @POST, @PUT, @DELETE 10 /reports – GET POST /reports/{reportid} – GET, DELETE, PUT /reports/{reportid}/templates /reports/{reportid}/templates/{templateid}
  • 11. @Produces and @Consumes 11 • MIME type content returned • Equivalent to Content-type response header
  • 12. @PathParam @QueryParam @HeaderParam @FormDataParam @FormParam 12 • Binds values from request to the parameter
  • 13. Deployment Descriptor (web.xml) 13 <servlet> <servlet-name>JAX-RS Servlet</servlet-name> <servlet-class>com.sun.jersey.spi.container.servlet.ServletContainer</servlet-class> <init-param> <param-name>com.sun.jersey.config.property.packages</param-name> <param-value>com.abc.xyz.services</param-value> </init-param> <init-param> <param-name>javax.ws.rs.Application</param-name> <param-value>com.abc.xyz.service.MyApplication</param-value> </init-param> </servlet> <servlet-mapping> <servlet-name>JAX-RS Servlet</servlet-name> <url-pattern>/api/*</url-pattern> </servlet-mapping>
  • 14. Client APIs 14 • Remember URLConnection? Or apache http client libraries? • Fluent API available from JAX-RS 2.0 Client Builder Client Web Target Request Building Response..
  • 15. SWAGGER API developer tools for the OpenAPI Specification 15
  • 16. What is Swagger and Why Swagger? 16 • Simple representation of your RESTFul API • Declarative resource specification • JSON specification • Developers and documentation… hahaha • Why Jersey Client / JUNIT or Rest Client (Poster / Postman) or API document for your client or boss? • Swagger UI to interact with the API in a sandbox UI • Support your existing RESTFul API without change
  • 17. Swagger Specification 17 Web Services • Resource Listing • API Description Create Swagger Specification • Manually - writing the JSON by hand • Codgen - converts annotations in your code into swagger specification
  • 19. 19
  • 20. Swagger Tools 20 Adjacent tools also provided by the Swagger project are Tool Description Swagger JS Javascript library for consuming Swagger-defined APIs from both client and node.js app Swagger Node Swagger module for node.js Swagger-Socket expose/invoke Swagger defined APIs over WebSockets Swagger Parser Standalone library for parsing Swagger definitions from Java Tools for nearly every language and allows you to deploy server instances to get your API up and running - Clojure, Go, JS, Java, .Net, Node, PHP, Python, Ruby, Scala
  • 21. References 21 • http://docs.oracle.com/javaee/6/tutorial/doc/giepu.html • http://www.vogella.com/tutorials/REST/article.html • https://jersey.java.net/documentation/latest/jaxrs- resources.html • https://github.com/koushikkothagal/messenger • http://swagger.io/specification/ • https://github.com/swagger-api/swagger-spec • https://github.com/swagger-api/swagger-core • http://petstore.swagger.io/
  • 22. 22 Thanks! Any questions? You can find me at ➝https://www.linkedin.com/in/kumaraswamym/ ➝kumaraswamy.m@gmail.com

Editor's Notes

  1. Today let us try to learn building RESTful application using JAX-RS
  2. We’ll understand what is REST and what are it’s principles And then know about JAX-RS Understand different HTTP methods that helps building REST services Understand annotation from JAX-RS that simplifies building REST services Look at client APIs from JAR-RS 2.0 And final on how to expose REST APIs
  3. Let’s look at a basic HTTP request and response Looking at the URI, the client is requesting to GET all the recordings from beatles band The URI is /music/…./recordings HTTP method is GET The clients ways, I’m expecting an XML as a response All of these forms a request Let’s take a looks at the response The HTTP request status code is 200, which means successful The content-type header says that response data is in xml format.. Or json format
  4. Web services are services that are exposed to the internet for programmatic access... an online API that you can call from your code it's a concept, it’s an idea, there is no specification, and no committee to tell you what is right or what is wrong it's an architectural style, set of guide lines for architecting your services… build the services as per your need following the REST principles It was first described by Roy Fielding… he is also one the principal authors of the HTTP specifications Lightweight, without unnecessary headers as in SOAP services Concepts of REST are mainly influenced by HTTP
  5. I'm sure many of you would have heard of Facebook and Twitter app... you must have seen games that would post on the Facebook wall, even though those games are not designed by Facebook themselves How do they do this? by calling online APIs
  6. Think of resources and build unique URLs for it Resources/URIs should be nouns and not verbs... the URIs should be documents, messages, reports.... and not getMessages, deleteMessages.. it should typically be nouns and not the action it's not message... it should be messages getMessages.do?id=10 deleteMessages.do?id=25 putMessages.do HTTP methods: They have specific meaning to each of these methods You are using these methods with or without your knowledge... like while post a comment or while opening a page in the web browser In the REST world, you don't make call to getReports.. you make a get request to the reports resource URI you don't call a deleteOrder, you make a delete request to the order resource URI the URI tells what entity or resource is being operated upon and the method tells what that operation is.
  7. Caching - Cache response on the service layer... for a short time - Stateless - Every request should be independent request - every request should send the state -
  8. It provide a way to map the meta-information to your methods through annotation. It’s a POJO based resource classes Injects
  9. Which resource you want to act upon In JAX-RS, you can use @Path to bind URI pattern to a Java method. The base URL + @Path parameter before the full URL URL matching with @Path pattern URI matching with parameter: The value within an open brace “{” and close brace “}”, is represents a parameter, and can be access with @PathParam URI matching with regular expression:
  10. @Path mentions that resource you want to act upon… @GET, @POST tells what action would that be… To do that, you could add annotations like… to the java method
  11. The @Produces annotation is used to specify the MIME media types or representations a resource can produce and send back to the client Can be applied to class level or method level The @Consumes annotation is used to specify which MIME media types of representations a resource can accept, or consume, from the client. Can be applied to class level or method level
  12. In the dep desc, define servlet container handling all ur jax-rs service requests….
  13. Specification - human and machine readable specification -
  14. How many of you have used HTTP URLConnection API from java? Was the experience pleasant?
  15. Let me ask you all a question. How many of you develop web services? How do you test the web services that you're developing? write junits (junits are still important to test the services for regressions) java.net.URLConnection API, use libraries like HTTP Client, Jersey Client Rest Client from the broswers like Poster, POSTMAN create a simple/sample UI app to test the APIs For someone to consume your services, you have to expose the API. How do you share/expose your APIs to others? Like what are the services are available, what parameters to be passed, is it a GET or POST document the web services in a word document when an API is updated, new service is added, a service is deprecated, you need to update the document...
  16. What is Swagger Swagger is a simple yet powerful representation of your RESTful API. It is an open source tool and has support for nearly every language like Closure, JS, Go, Scala, .Net, PHP, Python, Ruby and not to forget, JAVA. Swagger provides a declarative resource specification, allowing users to understand and consume services without knowledge of server implementation, enabling both developers and non-developers to interact with the API, providing clear insight into how the API responds to parameters and options. Why Swagger - Developer and documentation... no offense to anyone... developers usually hate documentation... we tend to avoid documentation whenever we could - Swagger provides a sandbox UI to interact with the API... wow... how is it different form POSTER or POSTMAN... let's see
  17. Specification - human and machine readable specification -