0% found this document useful (0 votes)
6 views41 pages

Lecture_Week05

The document provides an overview of RESTful web services and JAX-RS, detailing the architecture, key principles, and features of REST, as well as the role of JAX-RS in developing RESTful services in Java. It discusses annotations for defining resources and handling HTTP methods, along with examples of media types and request parameters. Additionally, it covers dependencies, tools for JAX-RS, and popular servers like Apache Tomcat and GlassFish.
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
6 views41 pages

Lecture_Week05

The document provides an overview of RESTful web services and JAX-RS, detailing the architecture, key principles, and features of REST, as well as the role of JAX-RS in developing RESTful services in Java. It discusses annotations for defining resources and handling HTTP methods, along with examples of media types and request parameters. Additionally, it covers dependencies, tools for JAX-RS, and popular servers like Apache Tomcat and GlassFish.
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 41

5COSC022W

Lecture Week 05
REST API (JAX-RS)
Dr. Hamed Hamzeh
Travel Agency
Application

GET /airline/booking
Deploying a Airline
flight booking Web service Booking
service { Search
“flight_no: 2234”
}

/booking /search

Question!
What kind of web service is suitable for this architecture? RESTful service
What is REST?

REST stands for


Representational State It's an architectural style, not a Key principles of REST:
Transfer. strict standard.

Uniform Interface: Standard


Resources: Everything is a Representations: Resources Statelessness: No client
HTTP methods
resource are represented in various session data stored on the
(GET, POST, PUT, DELETE) to
(e.g., customer, product) formats (XML, JSON, etc.) server.
manipulate resources
Defining a RESTful resource
A REST resource can be defined as an object that is of a specific type with the associated data and is
optionally associated to other resources.
We can do the HTTP requests against a resource such as the HEAD, GET, POST, PUT, and DELETE methods.

End point

http:// localhost:9999/ Restfulservices/ V1/users/{id}

protocol Version
Port
Domain number Application Parameter
name Context
Resource
What is JAX-RS?

Definition: • JAX-RS, or Java API for RESTful Web Services, is a set of Java APIs
that facilitate the development of RESTful web services.

• Originally part of Java EE (Enterprise Edition), it is now a key


Integration: component of Jakarta EE, emphasizing its role in enterprise-level
Jakarta EE

Java applications.

Simplifying • JAX-RS simplifies the creation of RESTful services, allowing


developers to focus on building scalable and interoperable web
Development: services without getting bogged down by low-level details.
Key Features of JAX-RS

Annotation-driven:

• Use annotations to define resources, methods, and parameters.

HTTP Methods:

• Support for common HTTP methods - GET, POST, PUT, DELETE, etc.

URI Mapping:

• Map URIs to resource classes and methods.

Content Negotiation:

• Handle different data formats (XML, JSON, etc.).

Exception Handling:

• Graceful handling of exceptions.


Resource Classes

Java Classes as Web Resources: @Path Annotation: HTTP Methods and Annotations:

In JAX-RS, a resource class is a Java class that The @Path annotation is used to associate a Resource methods within the class are
models a web resource. resource class or method with a URI path. annotated with HTTP methods like @GET,
It encapsulates the functionality of a specific It defines the base URI for the resource, @POST, @PUT, etc.
resource or a collection of related resources. making it accessible via HTTP. These annotations define the type of HTTP
request the method can handle.
Jersey
Jersey is the official reference implementation of JAX-RS.
Jersey

Developed by Sun Microsystems (now Oracle) and maintained by the Eclipse Foundation.

Provides a standard and consistent approach to building RESTful services.

Provides a comprehensive set of APIs that implement JAX-RS, simplifying the development of RESTful services in Java.

Leverages annotations to define resources, HTTP methods, and other aspects

Well-documented

Jersey integrates seamlessly with Java EE (Enterprise Edition) and Jakarta EE, making it suitable for enterprise-level applications.
@Path
• Defines the base URI for the resource class or
method.

@GET, @POST, @PUT, @DELETE


Annotations in • Specifies the HTTP method for the resource
method.
JAX-RS @PathParam
• Binds method parameters to a path segment.

@Produces, @Consumes
• Specify the media types the resource can produce
or consume.
Dependencies

Dependencies refer to external libraries or modules that your project relies


on to implement the functionality provided by the JAX-RS API.

These dependencies are typically required to compile, run, and deploy JAX-
RS applications.

The most common dependency for JAX-RS applications is the


implementation of the JAX-RS specification itself, and Jersey is a popular
choice as the reference implementation.
Jersey Dependency:
• If you choose Jersey as the implementation for JAX-RS in your
project, you need to include the Jersey libraries as dependencies.
• For Maven projects, you can add the following dependency in your
pom.xml:
<dependencies>
<dependency>
<groupId>org.glassfish.jersey.containers</groupId>
<artifactId>jersey-container-servlet</artifactId>
<version>2.35</version> <!-- Use the latest version -->
</dependency>
</dependencies>
If you are deploying your JAX-RS
application as a servlet, you'll need
a servlet container (e.g., Apache
Tomcat, Jetty) as a dependency.
Dependencies
Additional

This is necessary for hosting and


running your JAX-RS application.
Servlet

Handles HTTP requests


Servlet

Web Server
servlet

Servlets are Java classes that


extend the capabilities of a Have well-defined lifecycle.
server. They are part of the Java Web server initialises servlet.
EE or Jakarta EE platform.

Servlets process HTTP


requests and generate HTTP It supports multi-threading
responses.
How to get the plugins and
dependencies
JAX-RS annotations- Path

• The @javax.ws.rs.Path annotation indicates


the URI path to which a resource class or a
class method will respond.
• The value that you specify for the @Path
annotation is relative to the URI of the server
where the REST resource is hosted.
• This annotation can be applied at both the
class and the method levels.
• The following code snippet illustrates how
you can make a class respond to a URI path
template containing the /departments path
fragment:
JAX-RS annotations- Path

• For an annotated method, the base


URI is the effective URI of the
containing class.
• For instance, you will use the URI of
the following form to invoke the
getTotalDepartments() method
defined in the DepartmentService
class:
Specifying variables in the URI path template

The URI path template allows you to define variables that appear as placeholders in the URI. These
variables would be replaced at runtime with the values set by the client.
The URI path template looks like /departments/{id}.
At runtime, the client can pass an appropriate value for the id parameter to get the desired resource from
the server.
For instance, the URI path of the /departments/10 format returns the IT department details to the caller.

Specifying variable in URI path


Restricting values for path variables with regular
expressions
AX-RS lets you use regular expressions in the URI path template for restricting the values set for
the path variables at runtime by the client.
For example, you can set the regular expression as given in the following code snippet in order
to ensure that the department name variable present in the URI path consists only of lowercase
and uppercase alphanumeric characters:
Strict the resource name to
upper case and lowercase

Answer: the system reports the status back to the caller with
Q: What happens if a specified name does not an appropriate HTTP status code, such as 404 Not Found,
match with the regular expression? which tells the caller that the requested resource could not be
found at this moment.
Media Types

Media types define the format of the data being transmitted between the client and server in RESTful web
services.

They enable the client and server to understand the structure and encoding of the data being exchanged.

Media types can be specified using the @Produces and @Consumes annotations in JAX-RS resource
classes and methods.

@Produces

• is used to specify the media types that the resource method can produce (i.e., send back to the client).

@Consumes

• is used to specify the media types that the resource method can consume (i.e., accept from the client).
Example Media Types

application/json:

• Represents JSON (JavaScript Object Notation) data format.

application/xml:

• Represents XML (Extensible Markup Language) data format.

text/plain:

• Represents plain text data format.

multipart/form-data:

• Represents form data as submitted in HTML forms.

application/x-www-form-urlencoded:

• Represents form data encoded as a query string.


Negotiation and Content-Type Header

During communication, the client and server negotiate the media


type to be used based on the Accept and Content-Type headers.

The Accept header in the client request specifies the media types
that the client is willing to accept.

The Content-Type header in the request payload specifies the


media type of the data being sent by the client.
@Produces Annotation

• The following example uses the @Produces annotation at the class level in order to set the
default response media type as JSON for all resource methods in this class.
• At runtime, the binding provider will convert the Java representation of the return value to the
JSON format.

Import necessary requirements

We use media/content
type as JSON format
@Consumes Annotation

• The following example illustrates how you can use the @Consumes attribute to designate a
method in a class to consume a payload presented in the JSON media type.
• The binding provider will copy the JSON representation of an input message to the Department
parameter of the createDepartment() method.

Specifying the media type for the


consumer
Annotations for processing HTTP request methods - GET

• A RESTful system uses the HTTP GET method type for retrieving the resources referenced in the URI path.
• The @javax.ws.rs.GET annotation designates a method of a resource class to respond to the HTTP GET
requests.
• In the following example, the REST URI for accessing the findAllDepartments() method may look like
/departments. The complete URI path may take the following URI pattern:

Specify the Path


Which Specify the HTTP request type
represents the
base URI
Specify the media type
Annotations for processing HTTP request methods - PUT

• The HTTP PUT method is used for updating or creating the resource pointed by the URI.
• The @javax.ws.rs.PUT annotation designates a method of a resource class to respond to the HTTP PUT requests.
• When a request reaches a server, the framework intercepts the request and directs it to the appropriate method
that matches the URI path and the HTTP method type.
• The following code snippet shows how you can use the @PUT annotation to designate the editDepartment()
method to respond to the HTTP PUT request.

Specify the HTTP request type


Specify the parameter that
you want to update

As you are updating the information based


on the id, you need to specify it inside
@PathParam annotation
Annotations for processing HTTP request methods - POST

• The HTTP POST method posts data to the server. Typically, this method type is used for creating a
resource.
• The @javax.ws.rs.POST annotation designates a method of a resource class to respond to the
HTTP POST requests.
• The following code snippet shows how you can use the @POST annotation to designate the
createDepartment() method to respond to the HTTP POST request.

Specify the HTTP request type


Annotations for accessing request parameters -
PathParam

If we want to match the parameter


used inside the method with one
specified in the Path, it must be
included in the PathParam annotation

The REST API call to remove the department resource identified by id=10 looks like:
DELETE /departments/10 HTTP/1.1.
Annotations for accessing request parameters - PathParam

• We can also use multiple variables in a URI path template.


• For example, we can have the URI path template embedding the path variables to query a list of departments from
a specific city and country, which may look like /departments/{country}/{city}.
• The following code snippet illustrates the use of @PathParam to extract variable values from the preceding URI
path template:

We can fetch the information of all


departments according to a specific
city

Inside the method, we need to pass


both parameters using @PathParam
Annotations for accessing request parameters - QueryParam

• The @javax.ws.rs.QueryParam annotation injects the value(s) of a HTTP query parameter into a class field, a resource class
bean property (the getter method for accessing the attribute), or a method parameter.
• The following example illustrates the use of @QueryParam to extract the value of the desired query parameter present in the
URI.
• This example extracts the value of the query parameter, name, from the request URI and copies the value into the deptName
method parameter.
• The URI that accesses the IT department resource looks like /departments?name=IT:

Here we specify a parameter to get


the name of a specific department
using @QueryParam
Annotations for accessing request
parameters – MatrixParam
Provide a way to pass additional information within a URI, typically used to provide additional details about
a resource.

@Path("/products/{category}/{productId}")
public class ProductResource {
@GET
public Response getProductDetails( Example URI:
@PathParam("category") String category, •/products/electronics/123;color=red;size=medium
@PathParam("productId") int productId,
@MatrixParam("color") String color,
@MatrixParam("size") String size
) {
// Implementation logic
}
}
Annotations for accessing
request parameters -
FormParam

• In JAX-RS, the @FormParam annotation is used to


inject values submitted through an HTML form as
part of an HTTP request.
• The @javax.ws.rs.FormParam annotation injects
the matching HTML form parameters present in
the request body into a class field.
• Note that the @FormParam annotation can only
be used with HTTP POST requests that have the
application/x-www-form-urlencoded media type.
• Consider the following HTML form that contains
the data capture form for a department entity. This
form allows the user to enter the department
entity details
Annotations for accessing
request parameters -
FormParam

• Upon clicking on the submit button


on the HTML form, the department
details that you entered will be
posted to the REST URI,
/resources/departments.
• The following code snippet shows
the use of the @FormParam
annotation for extracting the HTML
form fields and copying them to the
resource class method parameter:
Tools for JAX-RS
Apache Tomcat

• Apache Tomcat is an open-source web server and servlet container developed by the
Apache Software Foundation.
• Tomcat is lightweight and easy to use, making it a popular choice for developing and
deploying Java-based web applications.
Glassfish

• GlassFish is an open-source application server project that provides a robust and scalable
platform for developing, deploying, and managing Java EE (Enterprise Edition) and
Jakarta EE (the successor to Java EE) applications.
• It is developed by the Eclipse Foundation and has a long history, initially being a project
sponsored by Sun Microsystems and later Oracle.
Wildfly server

• WildFly is a free and open-source application server written in Java, originally


developed by Red Hat.
• It provides a runtime environment for Java-based applications and supports a wide
range of Java EE (Enterprise Edition) technologies, including web services, messaging,
and security.
• WildFly is known for its speed, flexibility, and high-performance capabilities, and is
often used in enterprise-level applications that require robust and scalable
infrastructure.
Which one is better?

Lightweight application
Scalability
development

Integration Administration
Postman

• Postman is a popular collaboration platform for building, testing, and documenting


Application Programming Interfaces (APIs).
• It provides a user-friendly interface for making HTTP requests to APIs
• Using Postman, developers can create requests with different HTTP methods (such as
GET, POST, PUT, DELETE, etc.), add headers and parameters, and send data in different
formats (such as JSON, XML, form data, etc.).
Postman - example

You might also like