Ch-5 - Building RESTful Web Services-1
Ch-5 - Building RESTful Web Services-1
Contents:
• Introduction to REST (Representational State Transfer)
o Describing the REST architectural style
o Comparing SOAP and RESTful web services
• Developing RESTful web services using JAX–RS
o Adding JAX–RS annotations to a POJO
o Configuring result types using HTTP request headers
o Deploying a JAX–WS service
• Customizing a RESTful Service Implementation
o Interacting with request URLs
o Mapping URLs to Java classes and methods
o Binding URL components to method arguments
1
RESTful Web Services
• RESTful web services are based on the principles of REST (Representational State
Transfer), a lightweight and flexible architectural style that uses standard HTTP
methods (GET, POST, PUT, DELETE) to access and manipulate resources, typically
represented in formats like JSON or XML.
• RESTful services have become widely adopted due to their simplicity, scalability, and
ease of integration with various client applications like mobile apps and web browsers.
2
REST Architectural Style
• REST is an architectural style designed for networked applications. Its key concepts
include:
1. Resources:
• In REST, everything is treated as a resource (e.g., a user, a product, a blog post).
• These resources are identified by Uniform Resource Identifiers (URIs).
o A URI is a unique string that represents the resource.
• Example of a URI: http://example.com/users/123
• Here, /users/123 identifies a specific user resource with ID 123.
3
Cont’d…
2. Stateless Communication:
• RESTful services are stateless, meaning each request from a client contains all the
necessary information for the server to fulfill the request.
• The server does not retain session information between requests.
• This stateless nature makes REST services more scalable and easier to maintain,
especially in distributed environments.
4
Cont’d…
5
Cont’d…
4. Representation of Resources:
• Resources in REST can be represented in different formats like JSON, XML, HTML,
or plain text.
• The client specifies the desired format using the Accept header, and the server responds
accordingly.
• Example: Accept: application/json
6
Comparing SOAP and RESTful Web Services
7
Cont’d…
8
Developing RESTful Web Services Using JAX-RS
• JAX-RS is a set of APIs provided by Java EE for building RESTful services. It uses
annotations to reduce boilerplate code and streamline development.
1. Adding JAX–RS Annotations to a POJO:
• JAX-RS uses a set of annotations to define resources and map HTTP requests to Java
methods.
• The main annotations include:
o @Path: Defines the URI path for a resource.
o @GET, @POST, @PUT, @DELETE: Define the HTTP method (verb) associated
with a resource.
9
Cont’d…
10
Cont’d…
Example:
@Path("/temperature")
public class TemperatureService {
@GET
@Path("/celsiusToFahrenheit/{celsius}")
@Produces(MediaType.TEXT_PLAIN)
public String convertCelsiusToFahrenheit(@PathParam("celsius")
double celsius) {
double fahrenheit = (celsius * 9/5) + 32;
return "Fahrenheit: " + fahrenheit;
}
}
11
Cont’d…
12
Cont’d…
Example:
@GET
@Path("/temperature")
@Produces({MediaType.APPLICATION_JSON,
MediaType.APPLICATION_XML})
public Temperature getTemperatureInBothFormats() {
return new Temperature(37.0);
13
}
Cont’d…
• In this case, the method can return either JSON or XML, depending on the Accept
header in the request:
o Accept: application/json
o Accept: application/xml
3. Deploying a JAX–RS Service:
• To deploy the RESTful service, package the application into a WAR (Web Application
Archive) file and deploy it to a web server (e.g., Apache Tomcat, GlassFish, or
WildFly).
• Alternatively, Java SE applications can use the javax.xml.ws.Endpoint class to publish
14
the service.
Customizing a RESTful Service Implementation
15
Cont’d…
• For instance:
a) A URL might represent a specific entity (e.g., a product or user):
• http://example.com/products/123. This URL represents a resource (product) with
the ID 123.
b) A URL might also specify an action, such as listing all products or filtering them:
• http://example.com/products?category=electronics
• JAX-RS provides the @Path annotation, which maps URL paths to specific methods in
the Java class handling the request. The path can be static or dynamic (with
placeholders for variables).
16
Cont’d…
Example of Dynamic Path:
@Path("/users")
public class UserService {
@GET
@Path("/{id}")
@Produces(MediaType.APPLICATION_JSON)
public Response getUserById(@PathParam("id") int userId) {
// Logic to fetch user by ID
User user = userService.getUserById(userId);
return Response.ok(user).build();
}
}
• @Path("/{id}"): The {id} portion is a placeholder for the dynamic part of the URL. When a client sends
a request like http://example.com/users/42, the 42 is mapped to the id parameter.
• @PathParam("id"): This annotation is used to bind the URL path variable (id) to the method parameter
17
(userId).
Cont’d…
18
Cont’d…
Example:
@Path("/products")
public class ProductService {
// GET request to retrieve a product by ID
@GET
@Path("/{id}")
@Produces(MediaType.APPLICATION_JSON)
public Response getProductById(@PathParam("id") int productId) {
Product product = productService.findProductById(productId);
return Response.ok(product).build();
}
// POST request to create a new product
@POST
@Consumes(MediaType.APPLICATION_JSON)
@Produces(MediaType.APPLICATION_JSON)
public Response createProduct(Product product) {
productService.createProduct(product);
return
Response.status(Response.Status.CREATED).entity(product).build();
} 19
}
Cont’d…
20
Cont’d…
21
Cont’d…
Example with @QueryParam:
@GET
@Path("/products")
@Produces(MediaType.APPLICATION_JSON)
public Response getProductsByCategory(@QueryParam("category") String
category) {
List<Product> products =
productService.getProductsByCategory(category);
23
Cont’d…
4. Configuring HTTP Request Headers
• In RESTful web services, HTTP request headers allow clients and servers to
exchange additional metadata about the request or response.
• Some commonly used HTTP headers include:
o Accept: Indicates the media type(s) that the client can process (e.g., application/json,
application/xml).
o Content-Type: Specifies the media type of the request body when data is being sent to
the server.
o Authorization: Contains authentication credentials (like API keys or tokens).
o Custom Headers: You can define custom headers to pass extra information between the
24
• In this example, the Authorization header is used to pass security credentials. The
server checks the header and returns either secure data or an UNAUTHORIZED
response based on the authentication. 25
Cont’d…
5. Returning Custom HTTP Status Codes
• RESTful services can return different HTTP status codes depending on the result of
the operation. For example:
o 200 OK: The request was successful.
o 201 Created: A new resource was created (usually in response to a POST
request).
o 400 Bad Request: The client sent an invalid request.
o 404 Not Found: The requested resource was not found.
26
Cont’d…
• In JAX-RS, you can use the Response class to return a response with a specific status
code:
Example:
@POST
@Path("/products")
@Consumes(MediaType.APPLICATION_JSON)
public Response createProduct(Product product) {
boolean created = productService.createProduct(product);
if (created) {
return Response.status(Response.Status.CREATED).build();
} else {
return Response.status(Response.Status.BAD_REQUEST).entity("Product
creation failed").build();
}
}
27
Summary
• Customizing RESTful services involves designing clean and intuitive URIs, mapping
them to Java methods, and using annotations like @PathParam, @QueryParam, and
@HeaderParam to bind URL components, query parameters, and headers to method
arguments.
• HTTP headers and status codes can be leveraged to convey additional information
and responses.
• RESTful services can be customized to handle different request/response types,
dynamically route requests, and control data flow using headers and parameters
effectively.
28
THE END!!
29