JAX RS API
The JAX-RS (Java API for RESTful Web Services) API is a set of Java programming language APIs that provides support for creating RESTful web services. REST (Representational State Transfer) is an architectural style for distributed hypermedia systems, and JAX-RS simplifies the development of these services in Java by providing annotations and APIs for handling HTTP requests and responses.
Table of Contents
Explanation
- 1. Purpose :
- JAX-RS API enables developers to build RESTful web services according to the principles of REST.
- It allows resources to be identified by URIs (Uniform Resource Identifiers) and manipulated using standard HTTP methods (GET, POST, PUT, DELETE, etc.).
- 2. Features :
- Annotations such as @Path, @GET, @POST, @PUT, @DELETE are used to define resource URIs and HTTP methods.
- Supports content negotiation with @Produces and @Consumes annotations for specifying media types (JSON, XML, etc.) for both request and response.
- 3. Integration :
- JAX-RS is integrated with other Java EE technologies like Servlets, EJB (Enterprise JavaBeans), and CDI (Contexts and Dependency Injection).
- It can be deployed in various Java EE application servers and frameworks like Apache TomEE, WildFly, and Spring Boot.
Example in Java
Here’s a simple example demonstrating the use of JAX-RS annotations to create a RESTful web service endpoint.
Syntax
java
import javax.ws.rs.GET;
import javax.ws.rs.Path;
import javax.ws.rs.PathParam;
import javax.ws.rs.Produces;
import javax.ws.rs.core.MediaType;
@Path("/hello")
public class HelloResource {
@GET
@Produces(MediaType.TEXT_PLAIN)
public String sayHello() {
return "Hello, World!";
}
@GET
@Path("/{name}")
@Produces(MediaType.TEXT_PLAIN)
public String sayHelloTo(@PathParam("name") String name) {
return "Hello, " + name + "!";
}
}
In this example:
- Annotations :
- @Path(“/hello”): Specifies the base URI path for the resource class (HelloResource).
- @GET: Indicates that the method should handle HTTP GET requests.
- @Path(“/{name}”): Specifies a subpath that can accept a path parameter (name).
- @Produces(MediaType.TEXT_PLAIN): Specifies that the method produces plain text response.
- Resource Methods :
- sayHello(): Returns a simple “Hello, World!” message when accessing /hello URI.
- sayHelloTo(String name): Returns a personalized greeting based on the name path parameter when accessing /hello/{name} URI.