0% found this document useful (0 votes)
19 views26 pages

Ch-7 - Developing RESTful Clients

Chapter 7 discusses the development of RESTful clients, which communicate with RESTful web services using HTTP requests to perform CRUD operations. It covers key features such as stateless interactions, resource identification, and the use of JAX-RS for dispatching messages, marshalling JavaBeans with JAXB, and processing asynchronous messages. The chapter also highlights the benefits of RESTful clients, including simplicity, interoperability, scalability, flexibility, and reusability.

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)
19 views26 pages

Ch-7 - Developing RESTful Clients

Chapter 7 discusses the development of RESTful clients, which communicate with RESTful web services using HTTP requests to perform CRUD operations. It covers key features such as stateless interactions, resource identification, and the use of JAX-RS for dispatching messages, marshalling JavaBeans with JAXB, and processing asynchronous messages. The chapter also highlights the benefits of RESTful clients, including simplicity, interoperability, scalability, flexibility, and reusability.

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/ 26

Chapter 7: Developing RESTful Clients

Contents:
• Dispatching REST messages using JAX–RS
o Building the client’s request
o Handling the service’s response code and exceptions
• Marshalling JavaBeans with JAXB
o Mapping XML with Java API for XML Binding (JAXB)
o Converting Java arguments with JAXB and JAX–RS
• Processing asynchronous messages
o Implementing server–push with JAX–RS
o Delivering asynchronous client requests

1
RESTful Clients

• A RESTful client is a software component or application that communicates with a


RESTful web service by sending HTTP requests and processing the responses.
• RESTful clients allow applications to interact with REST APIs over the web, enabling
them to perform CRUD (Create, Read, Update, Delete) operations on resources
exposed by a server.

2
Cont’d…
Key Features of RESTful Clients:
1. Communication Protocol: RESTful clients use HTTP/HTTPS as the communication
protocol.
• HTTP methods like GET, POST, PUT, DELETE, etc., correspond to actions on
resources.
2. Resource Identification: Resources on the server are identified by URIs (Uniform
Resource Identifiers).
• Example: https://api.example.com/products/123 identifies a specific product
resource.
3
Cont’d…
3. Stateless Interaction: RESTful interactions are stateless, meaning each request from
the client contains all necessary information (like authentication tokens) for the server to
process it.
4. Data Formats: RESTful clients exchange data with servers using standard formats like
JSON, XML, or others.
• Clients specify the data format they expect using Content-Type and Accept
headers.
5. Platform Independence: RESTful clients can be written in any programming
language (e.g., Java, Python, JavaScript).
• They are interoperable with REST APIs irrespective of the platform or language used.
4
Cont’d…
Components of a RESTful Client:
• HTTP Client: A library or API to send HTTP requests and receive responses.
• Request Builder: Helps build HTTP requests by specifying the URI, HTTP method,
headers, query parameters, and body.
• Response Processor: Handles server responses, including status codes, headers, and
payloads.
• Serialization/Deserialization: Converts objects into a format suitable for transmission
(e.g., JSON or XML) and vice versa.

5
Dispatching REST Messages Using JAX-RS
• Dispatching RESTful messages involves building and sending HTTP requests, as well
as processing server responses.
Building the Client's Request:
• A REST client request includes HTTP methods, headers, and optionally a request body.
Steps to Build a REST Request:
1. Create a Client object using ClientBuilder.
2. Define the target URL with client.target(url).
3. Build the HTTP request using .request() and specify the media type (e.g.,
MediaType.APPLICATION_JSON).
4. Send the request using the appropriate HTTP method (e.g., .get(), .post()). 6
Cont’d…

Example:
Client client = ClientBuilder.newClient();
WebTarget target =
client.target("http://example.com/api/resource");
Response response =
target.request(MediaType.APPLICATION_JSON).get();
String result = response.readEntity(String.class);
System.out.println(result);

7
Cont’d…
Handling the Service’s Response Code and Exceptions:
• Responses may return different HTTP status codes:
 200 (OK): Request successful.
 400 (Bad Request): Client error.
 500 (Internal Server Error): Server error.
• Use Response to read status codes and message bodies.
• Handle exceptions such as ClientErrorException or ServerErrorException.

8
Cont’d…
Example:
try {
Response response = target.request().get();
if (response.getStatus() == 200) {
System.out.println("Success: " +
response.readEntity(String.class));
} else {
System.out.println("Error: " + response.getStatus());
}
} catch (ProcessingException e) {
System.out.println("Request failed: " + e.getMessage());
}

9
Marshalling JavaBeans with JAXB
• JAXB (Java Architecture for XML Binding) is used to convert Java objects to XML or
JSON (marshalling) and vice versa (unmarshalling).
Mapping XML with Java API for XML Binding (JAXB):
• JAXB annotations bind Java classes to XML or JSON structure.
• Key annotations:
 @XmlRootElement: Defines the root element.
 @XmlElement: Maps fields to XML elements.

10
Cont’d…
Example:
@XmlRootElement
public class Employee {
@XmlElement
private String name;
@XmlElement
private int id;

// Getters and Setters


}

11
Cont’d…
Converting Java Arguments with JAXB and JAX-RS:
• Marshalling: Converts Java objects to XML/JSON for requests.
• Unmarshalling: Converts XML/JSON responses to Java objects.
Example:
// Marshalling: Sending JSON
Entity<Employee> entity = Entity.entity(new Employee("John", 101),
MediaType.APPLICATION_JSON);
Response response = target.request().post(entity);

// Unmarshalling: Receiving JSON


Employee employee = response.readEntity(Employee.class);
System.out.println(employee.getName());

12
Processing Asynchronous Messages
• Processing asynchronous messages typically involves handling communication or data
exchange where messages are sent and received independently of the sender's or
receiver's availability.
• This is commonly implemented in distributed systems, applications with background
tasks, or systems requiring real-time updates.
• Modern applications often rely on asynchronous processing for better performance and
responsiveness.
• JAX-RS provides APIs for asynchronous client requests.

13
Cont’d…
Steps to Process Asynchronous Messages:
1. Choose a Messaging Protocol/Service:
• Use a messaging service like RabbitMQ, Kafka, AWS SQS, Azure Service Bus, or
Google Pub/Sub.
• For in-app communication, frameworks like Celery (Python), Sidekiq (Ruby), or
Akka (Scala/Java) are popular.
2. Publish Messages:
• A sender (producer) generates messages and sends them to a message broker or a
queue.
• Ensure the message includes the necessary data or metadata for processing. 14
Cont’d…
3. Consume Messages:
• A consumer retrieves messages from the broker/queue and processes them.
• Consumers can process messages in batches or individually, depending on the
system's requirements.
4. Acknowledge Processing:
• Once the message is processed successfully, acknowledge it to the broker to
remove it from the queue.
• If processing fails, retry mechanisms can be implemented to reprocess messages.

15
Cont’d…
5. Handle Errors:
• Implement retry logic for transient errors.
• Use a dead-letter queue to store messages that cannot be processed after multiple
retries for later inspection.
7. Ensure Idempotency:
• Design the system to handle duplicate messages gracefully, ensuring processing the
same message multiple times does not cause errors or inconsistencies.
8. Scaling:
• Scale consumers horizontally to handle high-throughput systems.
• Use features like partitioning (in Kafka) to divide the workload among multiple consumers.
16
Cont’d…
8. Monitoring:
• Monitor the queue length, processing time, and error rates.
• Use tools like Prometheus, Grafana, or integrated dashboards from messaging
services.

17
Cont’d…
Example:
from celery import Celery

# Create a Celery app


app = Celery('tasks', broker='redis://localhost:6379/0')

# Define a task
@app.task
def process_message(message):
print(f"Processing: {message}")
# Simulate processing
return f"Processed: {message}"
# Producer: Send a message
process_message.delay("Hello, Asynchronous World!")
In this example:
• Producer sends a task to a Redis-backed broker.
• Consumer (worker) fetches and processes the task asynchronously. 18
Cont’d…
Implementing Server-Push with JAX-RS:
• Server-push mechanisms allow servers to push updates to clients when changes
occur.
• JAX-RS leverages technologies like WebSockets or EventSource to achieve server-
push communication.

19
Cont’d…
Example:
@Path("/events")
public class ServerPushResource {
private ExecutorService executor = Executors.newSingleThreadExecutor();
@GET
@Produces(MediaType.SERVER_SENT_EVENTS)
public void pushEvents(@Context SseEventSink eventSink, @Context Sse sse) {
executor.execute(() -> {
try (SseEventSink sink = eventSink) {
for (int i = 1; i <= 10; i++) {
OutboundSseEvent event = sse.newEventBuilder()
.name("message")
.data("Event " + i)
.build();
sink.send(event);
Thread.sleep(1000); }// Simulate delay
}
} catch (Exception e) { •SseEventSink: Manages the connection to stream events to the
e.printStackTrace(); client.
} •Sse: Creates and configures server-sent events.
}); •Use @Produces(MediaType.SERVER_SENT_EVENTS) to
} specify streaming data format. 20
}
Cont’d…

Delivering Asynchronous Client Requests:


• This refers to handling client requests in a non-blocking manner, enabling the server to
process them without waiting for the response to complete.
 Clients can send asynchronous requests using async() methods.
 Use Future or CompletionStage to process responses once they arrive.

21
Cont’d…
Example:
@Path("/async")
public class AsyncRequestResource {
private ExecutorService executor = Executors.newFixedThreadPool(10);
@GET
@Path("/process")
public void processRequest(@Suspended AsyncResponse asyncResponse) {
executor.submit(() -> {
try {
Thread.sleep(2000); // Simulate processing delay
asyncResponse.resume("Request processed successfully!");
} catch (Exception e) {

asyncResponse.resume(Response.status(Response.Status.INTERNAL_SERVER_ERROR)
.entity("Error processing request").build());
}
});
}
} 22
Cont’d…
• @Suspended: Indicates the response is handled asynchronously.
• AsyncResponse.resume(): Completes the request with a response when ready.
• Exception handling ensures the client gets appropriate feedback.

23
Benefits of RESTful Clients
• Simplicity: RESTful clients are straightforward to implement, using HTTP methods
and URIs.
• Interoperability: Work across various platforms and programming languages.
• Scalability: The stateless nature of REST makes it easier to scale the client-server
architecture.
• Flexibility: RESTful clients can interact with any API that adheres to REST principles.
• Reusability: A well-designed RESTful client can be reused across multiple
applications consuming the same APIs.

24
Quiz (10%)
1. What is AJAX, and what is its primary purpose?
2. What is RESTful client?
3. What HTTP methods are commonly used in RESTful web services?
4. What is the purpose of the @Produce annotation in JAX-RS?
5. What is the role of HTTP headers in RESTful communication?

25
THE END!!
26

You might also like

pFad - Phonifier reborn

Pfad - The Proxy pFad of © 2024 Garber Painting. All rights reserved.

Note: This service is not intended for secure transactions such as banking, social media, email, or purchasing. Use at your own risk. We assume no liability whatsoever for broken pages.


Alternative Proxies:

Alternative Proxy

pFad Proxy

pFad v3 Proxy

pFad v4 Proxy