0% found this document useful (0 votes)
27 views29 pages

Ch-5 - Building RESTful Web Services-1

Chapter 5 discusses building RESTful web services using the REST architectural style, highlighting its principles such as stateless communication and the use of standard HTTP methods. It covers the development of RESTful services with JAX-RS, including annotations for mapping URLs to Java methods and handling request parameters. The chapter also emphasizes customizing services through clean URIs, HTTP headers, and status codes to enhance functionality and communication between clients and servers.

Uploaded by

Bereket Mebratu
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
27 views29 pages

Ch-5 - Building RESTful Web Services-1

Chapter 5 discusses building RESTful web services using the REST architectural style, highlighting its principles such as stateless communication and the use of standard HTTP methods. It covers the development of RESTful services with JAX-RS, including annotations for mapping URLs to Java methods and handling request parameters. The chapter also emphasizes customizing services through clean URIs, HTTP headers, and status codes to enhance functionality and communication between clients and servers.

Uploaded by

Bereket Mebratu
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
You are on page 1/ 29

Chapter 5: Building RESTful Web Services

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…

3. HTTP Methods (Verbs):


• REST uses standard HTTP methods (or verbs) to perform operations on resources:
o GET: Retrieve a resource.
o POST: Create a new resource.
o PUT: Update an existing resource.
o DELETE: Remove a resource.
o These methods map directly to CRUD (Create, Read, Update, Delete) operations,
making REST intuitive and straightforward.

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

• SOAP (Simple Object Access Protocol):


o A protocol based on XML messaging.
o SOAP services are tightly coupled with WSDL (Web Services Description
Language) contracts and require additional overhead for security, transactions, and
reliability.
o SOAP is useful in enterprise environments where more formal, structured, and
transactional communication is needed.

7
Cont’d…

• REST (Representational State Transfer):


o A lightweight, flexible architecture that leverages the simplicity of HTTP without
the overhead of SOAP's XML-based messaging.
o RESTful services use simple URLs and standard HTTP methods, making them
more suitable for web applications, mobile apps, and systems where simplicity,
performance, and scalability are key.

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…

o @Produces: Specifies the content type returned by the resource (e.g.,


application/json, application/xml).
o @Consumes: Specifies the content type expected by the resource (e.g.,
application/json, application/xml).

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…

• In the previous example:


o @Path("/temperature") maps this class to the /temperature URI.
o @GET indicates that this method will handle HTTP GET requests.
o @PathParam("celsius") extracts the {celsius} value from the URI and binds it to
the method argument.
o @Produces(MediaType.TEXT_PLAIN) specifies that the response will be returned
as plain text.

12
Cont’d…

2. Configuring Result Types Using HTTP Request Headers:


• The @Produces annotation allows the service to respond with different content types,
depending on what the client requests through the Accept header.

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

• Customizing a RESTful service involves adapting the service to interact efficiently


with client requests by leveraging various URI patterns, HTTP methods, headers, and
request parameters.
1. Interacting with Request URLs
• In RESTful services, the URL (Uniform Resource Locator) is crucial as it identifies the
resource being interacted with.
• A well-designed REST API uses clean, meaningful, and predictable URLs to represent
resources.

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…

2. Mapping URLs to Java Classes and Methods


• Mapping URLs to Java classes and methods in a RESTful service is done using JAX-
RS annotations.
• The mapping allows for handling different types of requests (like GET, POST, PUT,
and DELETE) in different methods, which correspond to different CRUD operations
(Create, Read, Update, Delete).

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…

• @Path("/{id}"): Maps a specific product ID in the URL to the Java method.


• @GET: Maps the method to an HTTP GET request, which is used for fetching
resources.
• @POST: Maps the method to an HTTP POST request, used for creating resources.

20
Cont’d…

3. Binding URL Components to Method Arguments


• URL components can be bound to method arguments using various annotations
provided by JAX-RS.
• The most common annotations for extracting parts of the request include:
o @PathParam: Extracts a dynamic value from the URL.
o @QueryParam: Extracts query parameters from the URL (after the ?).
o @HeaderParam: Extracts values from HTTP headers.
o @FormParam: Extracts form data sent in HTTP POST requests.

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);

In this case, return


the URLResponse.ok(products).build();
might look like: http://example.com/products?
}
category=electronics
• @QueryParam("category"): Extracts the value of the query parameter category from the
URL (electronics) and binds it to the method argument category.
22
Cont’d…
Example with @HeaderParam:
@GET
@Path("/products")
@Produces(MediaType.APPLICATION_JSON)
public Response getProducts(@HeaderParam("X-Client-ID") String clientId)
{
List<Product> products =
productService.getProductsForClient(clientId);

In this case, return Response.ok(products).build();


the client can send a request with a custom header: X-Client-ID: ABC123
}
• @HeaderParam("X-Client-ID"): Binds the value of the X-Client-ID header to the method
parameter clientId.

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

client and server.


Cont’d…
Example with @HeaderParam:
@GET
@Path("/secure-data")
@Produces(MediaType.APPLICATION_JSON)
public Response getSecureData(@HeaderParam("Authorization") String
authHeader) {
if (securityService.isAuthorized(authHeader)) {
return Response.ok("Secure Data").build();
} else {
return Response.status(Response.Status.UNAUTHORIZED).build();
}
}

• 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

You might also like