Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Rest API Example

Tags:

I have an implementation of a simple REST server written in Java. Every API call return data in XML format, what should i do if i wanted the format to be JSON? Do i need external libraries? Here's my code:

User.java:

package com.leo;

import java.io.Serializable;

import javax.xml.bind.annotation.XmlElement;
import javax.xml.bind.annotation.XmlRootElement;

@XmlRootElement(name = "user")
public class User implements Serializable
{

private static final long serialVersionUID = 1L;
private int id;
private String name;
private String profession;

public User()
{
}

public User(int id, String name, String profession)
{
    this.id = id;
    this.name = name;
    this.profession = profession;
}

public int getId()
{
    return id;
}

@XmlElement
public void setId(int id)
{
    this.id = id;
}

public String getName()
{
    return name;
}

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

public String getProfession()
{
    return profession;
}

@XmlElement
public void setProfession(String profession)
{
    this.profession = profession;
}
}

UserDao.java

    package com.leo;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.util.ArrayList;
import java.util.List;

public class UserDao
{
    public List<User> getAllUsers()
    {
        List<User> userList = null;
        try
        {
            File file = new File("Users.dat");
            if (!file.exists())
            {
                User user = new User(1, "Mahesh", "Teacher");
                userList = new ArrayList<User>();
                userList.add(user);
                saveUserList(userList);
            }
            else
            {
                FileInputStream fis = new FileInputStream(file);
                ObjectInputStream ois = new ObjectInputStream(fis);
                userList = (List<User>) ois.readObject();
                ois.close();
            }
        }
        catch (IOException e)
        {
            e.printStackTrace();
        }
        catch (ClassNotFoundException e)
        {
            e.printStackTrace();
        }
        return userList;
    }

    public User getUser(int id){
          List<User> users = getAllUsers();

          for(User user: users){
             if(user.getId() == id){
                return user;
             }
          }
          return null;
       }

    public int addUser(User pUser)
    {
        List<User> userList = getAllUsers();
        boolean userExists = false;
        for (User user : userList)
        {
            if (user.getId() == pUser.getId())
            {
                userExists = true;
                break;
            }
        }
        if (!userExists)
        {
            userList.add(pUser);
            saveUserList(userList);
            return 1;
        }
        return 0;
    }

    public int updateUser(User pUser)
    {
        List<User> userList = getAllUsers();

        for (User user : userList)
        {
            if (user.getId() == pUser.getId())
            {
                int index = userList.indexOf(user);
                userList.set(index, pUser);
                saveUserList(userList);
                return 1;
            }
        }
        return 0;
    }

    public int deleteUser(int id)
    {
        List<User> userList = getAllUsers();

        for (User user : userList)
        {
            if (user.getId() == id)
            {
                int index = userList.indexOf(user);
                userList.remove(index);
                saveUserList(userList);
                return 1;
            }
        }
        return 0;
    }

    private void saveUserList(List<User> userList)
    {
        try
        {
            File file = new File("Users.dat");
            FileOutputStream fos;

            fos = new FileOutputStream(file);

            ObjectOutputStream oos = new ObjectOutputStream(fos);
            oos.writeObject(userList);
            oos.close();
        }
        catch (FileNotFoundException e)
        {
            e.printStackTrace();
        }
        catch (IOException e)
        {
            e.printStackTrace();
        }
    }
}

UserService.java

    package com.leo;

import java.io.IOException;
import java.util.List;

import javax.servlet.http.HttpServletResponse;
import javax.ws.rs.Consumes;
import javax.ws.rs.DELETE;
import javax.ws.rs.FormParam;
import javax.ws.rs.GET;
import javax.ws.rs.OPTIONS;
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.core.Context;
import javax.ws.rs.core.MediaType;

@Path("/UserService")
public class UserService {

   UserDao userDao = new UserDao();
   private static final String SUCCESS_RESULT="<result>success</result>";
   private static final String FAILURE_RESULT="<result>failure</result>";

   @GET
   @Path("/users")
   @Produces(MediaType.APPLICATION_XML)
   public List<User> getUsers(){
      return userDao.getAllUsers();
   }    

   @GET
   @Path("/users/{userid}")
   @Produces(MediaType.APPLICATION_XML)
   public User getUser(@PathParam("userid") int userid){
      return userDao.getUser(userid);
   }

   @PUT
   @Path("/users")
   @Produces(MediaType.APPLICATION_XML)
   @Consumes(MediaType.APPLICATION_FORM_URLENCODED)
   public String createUser(@FormParam("id") int id,
      @FormParam("name") String name,
      @FormParam("profession") String profession,
      @Context HttpServletResponse servletResponse) throws IOException{
      User user = new User(id, name, profession);
      int result = userDao.addUser(user);
      if(result == 1){
         return SUCCESS_RESULT;
      }
      return FAILURE_RESULT;
   }

   @POST
   @Path("/users")
   @Produces(MediaType.APPLICATION_XML)
   @Consumes(MediaType.APPLICATION_FORM_URLENCODED)
   public String updateUser(@FormParam("id") int id,
      @FormParam("name") String name,
      @FormParam("profession") String profession,
      @Context HttpServletResponse servletResponse) throws IOException{
      User user = new User(id, name, profession);
      int result = userDao.updateUser(user);
      if(result == 1){
         return SUCCESS_RESULT;
      }
      return FAILURE_RESULT;
   }

   @DELETE
   @Path("/users/{userid}")
   @Produces(MediaType.APPLICATION_XML)
   public String deleteUser(@PathParam("userid") int userid){
      int result = userDao.deleteUser(userid);
      if(result == 1){
         return SUCCESS_RESULT;
      }
      return FAILURE_RESULT;
   }

   @OPTIONS
   @Path("/users")
   @Produces(MediaType.APPLICATION_XML)
   public String getSupportedOperations(){
      return "<operations>GET, PUT, POST, DELETE</operations>";
   }
}

EDIT: i included the jackson jars in my project, specifically jackson-core-2.7.0.jar, jackson-databind-2.7.0.jar, jackson-annotations-2.2.1.jar but now i get this exception from Tomcat:

javax.servlet.ServletException: org.glassfish.jersey.server.ContainerException: java.lang.NoClassDefFoundError: Could not initialize class com.fasterxml.jackson.databind.ObjectMapper
    org.glassfish.jersey.servlet.WebComponent.serviceImpl(WebComponent.java:489)
    org.glassfish.jersey.servlet.WebComponent.service(WebComponent.java:427)
    org.glassfish.jersey.servlet.ServletContainer.service(ServletContainer.java:388)
    org.glassfish.jersey.servlet.ServletContainer.service(ServletContainer.java:341)
    org.glassfish.jersey.servlet.ServletContainer.service(ServletContainer.java:228)
    org.apache.tomcat.websocket.server.WsFilter.doFilter(WsFilter.java:53)
like image 685
leqo Avatar asked Jul 10 '16 13:07

leqo


People also ask

What is REST API used for?

A RESTful API is an architectural style for an application program interface (API) that uses HTTP requests to access and use data. That data can be used to GET, PUT, POST and DELETE data types, which refers to the reading, updating, creating and deleting of operations concerning resources.

What is REST with example?

REST is a way to access resources which lie in a particular environment. For example, you could have a server that could be hosting important documents or pictures or videos. All of these are an example of resources.

What is REST API in simple terms?

A REST API (also known as RESTful API) is an application programming interface (API or web API) that conforms to the constraints of REST architectural style and allows for interaction with RESTful web services. REST stands for representational state transfer and was created by computer scientist Roy Fielding.


1 Answers

I'm answering interpreting your question as pertaining to the REST service (UserService.java), please comment if that is not what was intended.

You must first ensure that the calls in the methods do in fact return results as JSON. This will require the appropriate changes to User.java and UserDao.java to return JSON instead of XML.

The User class example you have is using the Java JAXB library, based on those annotations @XMLRootElement, @XMLElement.

You would need to rewrite this class using a Java library that supports creating JSON objects.

A good choice is the Jackson library. Here is the home page for Jackson wiki which is pretty well documented.

As far as the REST service itself goes, in your UserService.java, you would need to change the media type that the service produces.

Change all instances of method annotations where you want to produce JSON from

@Produces(MediaType.APPLICATION_XML)

to

@Produces(MediaType.APPLICATION_JSON)
like image 61
paisanco Avatar answered Sep 28 '22 01:09

paisanco