Java RESTful API using Jersey

Loading

Jersey is a popular framework for building RESTful web services in Java. It is the reference implementation of JAX-RS (Java API for RESTful Web Services), which is a set of APIs to create REST web services in Java. Jersey simplifies the process of building RESTful APIs by providing annotations, automatic content negotiation, and support for various data formats like JSON, XML, and others.

Let’s explore how to create a simple RESTful API using Jersey.


1. Setting Up the Jersey Project

There are different ways to set up a Jersey project, but we’ll focus on a simple Maven-based setup for this example.

1.1. Maven Setup

To use Jersey in your Java project, you need to include the following dependencies in your pom.xml (for Maven projects):

<dependencies>
    <!-- Jersey Framework Dependencies -->
    <dependency>
        <groupId>org.glassfish.jersey.core</groupId>
        <artifactId>jersey-server</artifactId>
        <version>2.35</version> <!-- Use latest version -->
    </dependency>
    <dependency>
        <groupId>org.glassfish.jersey.media</groupId>
        <artifactId>jersey-media-json-jackson</artifactId>
        <version>2.35</version> <!-- Use latest version -->
    </dependency>
    <dependency>
        <groupId>org.glassfish.jersey.container</groupId>
        <artifactId>jersey-container-servlet</artifactId>
        <version>2.35</version> <!-- Use latest version -->
    </dependency>
    <dependency>
        <groupId>javax.ws.rs</groupId>
        <artifactId>javax.ws.rs-api</artifactId>
        <version>2.1.1</version> <!-- Use latest version -->
    </dependency>
</dependencies>

1.2. Maven Plugin (for building and running the server)

<build>
    <plugins>
        <plugin>
            <groupId>org.apache.maven.plugins</groupId>
            <artifactId>maven-compiler-plugin</artifactId>
            <version>3.8.1</version>
            <configuration>
                <source>1.8</source>
                <target>1.8</target>
            </configuration>
        </plugin>
    </plugins>
</build>

2. Create a Simple Jersey Application

Once the project is set up with the necessary dependencies, you can start creating a RESTful API using Jersey.

2.1. Create a REST Resource Class

A REST resource class is a Java class that defines the REST endpoints using Jersey annotations such as @Path, @GET, @POST, etc. Each method in this class corresponds to an HTTP request method (GET, POST, PUT, DELETE, etc.).

Here’s an example of a simple PersonResource class:

import javax.ws.rs.GET;
import javax.ws.rs.Path;
import javax.ws.rs.Produces;
import javax.ws.rs.core.MediaType;

@Path("/person")
public class PersonResource {

    @GET
    @Produces(MediaType.APPLICATION_JSON)
    public Person getPerson() {
        // Return a sample Person object as JSON
        return new Person("John Doe", 30);
    }
}

In this example:

  • @Path("/person"): This annotation specifies the path of the resource (i.e., the URL that accesses this resource).
  • @GET: This annotation indicates that this method will handle HTTP GET requests.
  • @Produces(MediaType.APPLICATION_JSON): This annotation specifies that the response should be in JSON format.

2.2. Create a POJO for the Response

To match the response data, you need a Java POJO (Plain Old Java Object) for the Person class:

public class Person {
    private String name;
    private int age;

    // Constructor, getters, and setters
    public Person(String name, int age) {
        this.name = name;
        this.age = age;
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public int getAge() {
        return age;
    }

    public void setAge(int age) {
        this.age = age;
    }
}

3. Configure Jersey Application

To configure Jersey, you need to create a main application class that extends javax.ws.rs.core.Application. This class will specify which resources Jersey should load.

Here’s how you can configure Jersey:

import javax.ws.rs.ApplicationPath;
import javax.ws.rs.core.Application;

@ApplicationPath("/api") // The base URI for your REST service
public class JerseyApplication extends Application {
    // Jersey will automatically discover resources in the same package
}

The @ApplicationPath("/api") annotation tells Jersey to expose your REST resources at the /api path. So, the full URL for the PersonResource will be /api/person.


4. Deploying the Jersey Application

To run the application, you need to deploy it to a web container like Apache Tomcat or use an embedded server like Jetty or Grizzly. If you are using Maven, you can configure the maven-jetty-plugin to run it directly from the command line during development.

4.1. Example with Embedded Jetty (optional)

You can set up an embedded Jetty server in your project. Below is an example of setting up Jetty in the pom.xml for running the Jersey application locally:

<plugins>
    <plugin>
        <groupId>org.mortbay.jetty</groupId>
        <artifactId>jetty-maven-plugin</artifactId>
        <version>8.1.16.v20140903</version>
        <configuration>
            <scanIntervalSeconds>10</scanIntervalSeconds>
            <webAppConfig>
                <contextPath>/</contextPath>
                <warSourceDirectory>src/main/webapp</warSourceDirectory>
            </webAppConfig>
        </configuration>
    </plugin>
</plugins>

You can now start the application by running the following command:

mvn jetty:run

5. Testing the Jersey API

Once the application is deployed, you can test the endpoint using Postman, curl, or any HTTP client.

For example, to test the /person endpoint, use the following curl command:

curl -X GET http://localhost:8080/api/person

The output should be a JSON response like this:

{
  "name": "John Doe",
  "age": 30
}

6. Enhancing the Application

You can extend this basic application to include other HTTP methods like POST, PUT, and DELETE by using corresponding Jersey annotations like @POST, @PUT, @DELETE, and handling request bodies for creating or updating resources.

Example of a POST method in the PersonResource class:

import javax.ws.rs.POST;
import javax.ws.rs.Path;
import javax.ws.rs.Consumes;
import javax.ws.rs.Produces;

@Path("/person")
public class PersonResource {

    @POST
    @Consumes(MediaType.APPLICATION_JSON)
    @Produces(MediaType.APPLICATION_JSON)
    public Person createPerson(Person person) {
        // Simulate saving the person (e.g., to a database)
        return person; // Return the created person as a response
    }
}

With this, a client can send a POST request with a JSON body containing the name and age of a person.


  • Advantages:
    • It’s based on the official JAX-RS API, so it follows standard specifications for building RESTful web services.
    • It provides out-of-the-box support for converting Java objects to JSON or XML using media-type support like Jersey Media JSON Jackson.
    • It’s highly extensible and integrates well with other Java frameworks like Spring or JPA for persistence.
  • When to Use:
    • When building RESTful web services in Java.
    • When working in environments that require high interoperability with different data formats like JSON, XML, and YAML.

Leave a Reply

Your email address will not be published. Required fields are marked *