Create a Java REST API with JAX-RS and Jersey

I will explain how to create a Java REST API with JAX-RS and Jersey. We will use the common methods to publish the services on our local machine.

What is JAX-RS? Java API for RESTful web services. It is a specification for creating REST web services that is based on annotations to simplify the development and implementation of clients.
What is Jersey? It is a RESTFUL client and implements JAX-RS.

The operations of a REST system and the HTTP specification are four:

  • GET (read)
  • POST (create)
  • PUT (edit)
  • DELETE (delete)

The first thing to do is create a dynamic Java web project (better the latest Java JDK 1.8 version) and configure it to work with Maven. I have used Eclipse as a development environment. If you have questions about how to do it, you can consult the tutorial Create Web Project.

Modify pom.xml file

We will introduce the dependencies in the Maven configuration file.

pom.xml

<project xmlns="http://maven.apache.org/POM/4.0.0"
	xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
	xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
	<modelVersion>4.0.0</modelVersion>
	<groupId>API_REST_WS-RS</groupId>
	<artifactId>API_REST_WS-RS</artifactId>
	<version>0.0.1-SNAPSHOT</version>
	<packaging>war</packaging>
	<build>
		<sourceDirectory>src</sourceDirectory>
		<plugins>
			<plugin>
				<artifactId>maven-compiler-plugin</artifactId>
				<version>3.8.0</version>
				<configuration>
					<source>1.8</source>
					<target>1.8</target>
				</configuration>
			</plugin>
			<plugin>
				<artifactId>maven-war-plugin</artifactId>
				<version>3.2.1</version>
				<configuration>
					<warSourceDirectory>WebContent</warSourceDirectory>
				</configuration>
			</plugin>
		</plugins>
	</build>

	<dependencies>
		<dependency>
			<groupId>javax.ws.rs</groupId>
			<artifactId>javax.ws.rs-api</artifactId>
			<version>2.1.1</version>
		</dependency>

		<dependency>
			<groupId>org.glassfish.jersey.containers</groupId>
			<artifactId>jersey-container-servlet</artifactId>
			<version>2.25.1</version>
		</dependency>
		<dependency>
			<groupId>org.glassfish.jersey.media</groupId>
			<artifactId>jersey-media-json-jackson</artifactId>
			<version>2.25.1</version>
		</dependency>
	</dependencies>
</project>


Create the rest of classes

User.java

package es.rosamarfil.modelo;

import java.io.Serializable;

public class User implements Serializable {

	private static final long serialVersionUID = 1L;

	public String name;

	public String username;

	public User() {
		super();
	}
	
	public User(String name, String username) {
		super();
		this.name = name;
		this.username = username;
	}

	public String getName() {
		return name;
	}

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

	public String getUsername() {
		return username;
	}

	public void setUsername(String username) {
		this.username = username;
	}

}

ServicioUsers.java

package es.rosamarfil.services;

import java.util.ArrayList;
import java.util.List;

import javax.ws.rs.BeanParam;
import javax.ws.rs.Consumes;
import javax.ws.rs.DELETE;
import javax.ws.rs.GET;
import javax.ws.rs.POST;
import javax.ws.rs.PUT;
import javax.ws.rs.Path;
import javax.ws.rs.PathParam;
import javax.ws.rs.Produces;
import javax.ws.rs.client.Entity;
import javax.ws.rs.core.MediaType;
import javax.ws.rs.core.Response;
import javax.ws.rs.core.Response.Status;

import es.rosamarfil.modelo.User;

@Path("/users")
public class ServicioUsers {

	private static List<User> listaUsuarios = new ArrayList<User>() {
		{
			add(new User("Rosa", "Marfil"));
			add(new User("Pepito", "Grillo"));
			add(new User("Manuela", "Lago"));
		}
	};

	/**
	 * URL: http://localhost:8080/API_REST_WS-RS/api/users
	 * @return Response list Users
	 */
	@GET
	@Produces(MediaType.APPLICATION_JSON)
	public Response getUsers() {
		return Response.ok(listaUsuarios).build();
	}


	/**
	 * URL: http://localhost:8080/API_REST_WS-RS/api/users/Rosa
	 * 
	 * @param name String
	 * @return Response
	 */
	@GET
	@Path("/{name}")
	@Consumes(MediaType.APPLICATION_JSON)
	@Produces(MediaType.APPLICATION_JSON)
	public Response getUserById(@PathParam("name") String name) {
		User found = null;
		for (int i = 0; i < listaUsuarios.size(); i++) {
			if (listaUsuarios.get(i).getName().equalsIgnoreCase(name)) {
				found = listaUsuarios.get(i);
			}
		}
		if (found == null) {
			return Response.status(Status.BAD_REQUEST).entity("User not found").build();
		} else {
			return Response.ok(found).build();
		}
	}

	/**
	 * URL: http://localhost:8080/API_REST_WS-RS/api/users/createUser Parameters in
	 * Postman: {"name":"Rosa3333","username":"Marfi3333l"}
	 * 
	 * @param User
	 * @return Response list NOTA: Si no existe el constructor vacío de User, da un
	 *         error y el userRequest viene null.
	 */
	@POST
	@Path("/createUser")
	@Consumes(MediaType.APPLICATION_JSON)
	@Produces(MediaType.APPLICATION_JSON)
	public Response createUser(User userRequest) {

		this.listaUsuarios.add(userRequest);
		//return Response.status(Status.CREATED).build();
		return Response.ok(listaUsuarios).build();

	}

	/**
	 * URL: http://localhost:8080/API_REST_WS-RS/api/users/updateUser Parameters in
	 * Postman: {"name":"Rosa","username":"Marfil3333"}
	 * 
	 * @param User
	 * @return user modified NOTA: Si no existe el constructor vacío de User, da un
	 *         error y el userRequest viene null.
	 */
	@PUT
	@Path("/updateUser")
	@Consumes(MediaType.APPLICATION_JSON)
	@Produces(MediaType.APPLICATION_JSON)
	public Response updateUser(User userUpdate) {
		User found = null;
		for (int i = 0; i < listaUsuarios.size(); i++) {
			if (listaUsuarios.get(i).getName().equalsIgnoreCase(userUpdate.getName())) {
				found = listaUsuarios.get(i);
			}
		}

		if (found == null) {
			return Response.status(Status.BAD_REQUEST).entity("User not found").build();
		} else {
			found.setUsername(userUpdate.getUsername());
			return Response.ok(found).build();
		}
	}

	/**
	 * URL: http://localhost:8080/API_REST_WS-RS/api/users/deleteUser/Rosa
	 * 
	 * @param User
	 * @return Response
	 */
	@DELETE
	@Path("/deleteUser/{name}")
	@Produces(MediaType.APPLICATION_JSON)
	public Response deleteUser(@PathParam("name") String name) {
		User found = null;
		for (int i = 0; i < listaUsuarios.size(); i++) {
			if (listaUsuarios.get(i).getName().equalsIgnoreCase(name)) {
				found = listaUsuarios.get(i);
				listaUsuarios.remove(found);
			}
		}

		if (found == null) {
			return Response.status(Status.BAD_REQUEST).entity("User not found").build();
		} else {
			return Response.ok(listaUsuarios).build();
		}
	}

}

Configuration.java

package es.rosamarfil.services;

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


@ApplicationPath("api")
public class Configuration extends Application {
	
}

Try our Services

The first thing is to lift the application. To do this, select the project and run it on a previously configured Apache server. If you do not know how to configure it, you can see the tutorial Configure Web Project and see the section Add Apache Tomcat Server to Eclipse.

Create a Java REST API with JAX-RS and Jersey

Once the server is started with our application, we can test the services either from the address bar of a browser or from a client program such as Postman. The base address of our application is: http://localhost:8080/API_REST_WS-RS

Let’s see the parameters to introduce:

GET (read)

In the address bar enter:

http://localhost:8080/API_REST_WS-RS/api/users


GET (read) from a parameter. In this case we will search for a user by name.

In the address bar enter:

http://localhost:8080/API_REST_WS-RS/api/users/Rosa


POST (create)

In Postman, enter: http://localhost:8080/API_REST_WS-RS/api/users/createUser

And in the Body section, enter a user in json format, as shown in the image:

Create a Java REST API with JAX-RS and Jersey

PUT (edit)

In Postman, enter: http://localhost:8080/API_REST_WS-RS/api/users/updateUser

And in the Body section of Postman enter:

{“name”:”Rosa”,”username”:”Marfil3333″}


DELETE (delete)

In the address bar enter:

http://localhost:8080/API_REST_WS-RS/api/users/deleteUser/Rosa


And that’s all!! This is a simple way to start creating JAVA REST services and create a Java REST API with JAX-RS and Jersey.

I hope it was a useful tutorial and we’ll see you next time.

Share if you liked it !!

You may also like...

Leave a Reply

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