RESTEasy - A guide to implement CRUD Rest API

  •        0
  

We aggregate and tag open source projects. We have collections of more than one million projects. Check out the projects section.



RESTEasy is a JBoss project that provides various frameworks to help you build RESTful Web Services and RESTful Java applications. It is a fully certified and portable implementation of the JAX-RS 2.1 specification, a JCP specification that provides a Java API for RESTful Web Services over the HTTP protocol. It is licensed under the Apache 2.0.

In this article, we will look on developing CRUD services for product domain through RESTEasy 3 framework. All the examples can be deployed in Tomcat even though it is closely integrated with JBOSS WildFly as Resteasy framework is portable.

Start a simple web application maven project and add the following dependency. Resteasy-jaxrs is the RESTEasy framework jar, programmatic way of registering restlet is provided by resteasy-servlet-initializer and all marshalling/unmarshalling are done by jettison provider.


<properties>
  <resteasy-version> 3.7 <resteasy-version>
</properties>

<dependency>
    <groupId>org.jboss.resteasy</groupId>
    <artifactId>resteasy-jaxrs</artifactId>
<version>${resteasy-version}</version>
</dependency>
<dependency>
    <groupId>org.jboss.resteasy</groupId>
    <artifactId>resteasy-servlet-initializer</artifactId>
    <version>${resteasy-version}</version>
</dependency>
<dependency>
    <groupId>org.jboss.resteasy</groupId>
    <artifactId>resteasy-jettison-provider</artifactId>
    <version>${resteasy-version}</version>
</dependency>

Application main class need to be created to initialize the path for rest services and enable auto scanning by returning null in getSingletons method.

 @ApplicationPath("/rest")
 public class ApplicationMain extends Application {

   @Override
   public Set<Object> getSingletons() {
       return null;
   }
 }

Instead you can have empty class with @ApplicationPath annotation.

 @ApplicationPath("/rest")
 public class ApplicationMain extends Application {

 }

Domain model of product defined as below. It has been JAXB annotated with XMLRootElement and date field is made transient so marshalling or unmarshalling is skipped.

 @XmlRootElement
 public class Product {
    @XmlAttribute
    private Integer id;
    private String name;
    private Integer availableQty;
    private String brand;
  

    @XmlTransient
    private Date modifiedDate;

    public Product() {
       this.modifiedDate = new Date();
    }

    public Product(Integer id, String name, Integer availableQty, String brand) {
         this.id = id;
         this.name = name;
         this.availableQty = availableQty;
         this.brand = brand;
         this.modifiedDate = new Date();
    }

    public Product(Integer id, Product product) {
        this.id = id;
        this.name = product.getName();
        this.availableQty = product.getAvailableQty();
        this.brand = product.getBrand();
        this.modifiedDate = new Date();
   }

   public Integer getId() {
       return id;
   }

   public void setId(Integer id) {
       this.id = id;
   }

   public String getName() {
       return name;
   }

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

   public int getAvailableQty() {
      return availableQty;
   }

   public void setAvailableQty(Integer availableQty) {
      this.availableQty = availableQty;
   }

   public String getBrand() {
      return brand;
   }

   public void setBrand(String brand) {
      this.brand = brand;
   }

   public Date getModifiedDate() {
      return modifiedDate;
   }

   public void setModifiedDate(Date modifiedDate) {
      this.modifiedDate = modifiedDate;
   }
 }

CRUD Services

All CRUD services are built from service class, each method doing one kind of operation. Request entity and Response entity are automatically marshalled by jettison provider. The methods below just returns the entity and RESTEasy framework builds the reponse with entity.

Post request to create Product

Create a JAX-RS service class and @POST annotation is used for creating new product. Id has been assigned based on product id availability and intialized with date. For simplicity, we will use Map to store the product informtion. 

@Path annotation defines the URL path for this API. 

@Path("products")
public class ProductService {

    Logger logger = Logger.getLogger(ProductService.class);

    private static Map<Integer, Product> inventory = new HashMap<>();
    static {
       inventory.put(1, new Product(1, "Inspiron Laptop", 5, "Dell"));
       inventory.put(2, new Product(2, "Power X", 3, "LG"));
       inventory.put(3, new Product(3, "Thumbdrive", 3, "Kingston"));
   }
   private static int maxProductId = 4;

   @POST
   @Path("/")
   @Consumes("application/json")
   @Produces("application/text")
   public String createProduct(Product productDetails) {
         Product newproduct = new Product(maxProductId++, productDetails);
         inventory.put(newproduct.getId(), newproduct);
         return "product created successfully";
   }

}

Build this project and create "resteasyexamples.war". Deploy the WAR file under Tomcat webapps folder. 

We will test the API using CURL command, post JSON product message body.

 curl -X POST -H 'Authorization: Basic YWRtaW46YWRtaW4=' -H 'Content-Type:application/json' -v http://localhost:8080/resteasyexamples/rest/products -d   '{"product": {"name":"headset","availableQty":7,"brand":"Sony"}}'

  < HTTP/1.1 200
  < Content-Type: application/text
  < Content-Length: 28
  < Date: Sun, 26 May 2019 16:56:15 GMT
  <
  * Connection #0 to host localhost left intact
   product created successfully

Retrieve all products

Get method with same slash can return all the products in the inventory. Below method is part of ProductService class.

 @GET
 @Path("/")
 @Produces("application/json")
 public Collection<Product> getProducts() {
     return inventory.values();
 }

Below curl method returns product list.

 curl -H 'Authorization: Basic YWRtaW46YWRtaW4=' -i http://localhost:8080/resteasyexamples/rest/products   
 HTTP/1.1 200
 Content-Type: application/json
 Transfer-Encoding: chunked
 Date: Sun, 26 May 2019 17:03:58 GMT

 [{"product":{"@id":1,"name":"Inspiron Laptop","availableQty":5,"brand":"Dell"}},{"product":{"@id":2,"name":"Power X","availableQty":3,"brand":"LG"}},{"product":{"@id":5,"name":"Keyboard","availableQty":4,"brand":"HP"}},{"product":{"@id":6,"name":"headset","availableQty":7,"brand":"Sony"}}]

Get Products By Id

Get method with id passed as path param is used to fetch the product for that id. Below method returns product object, Framework will take care of making it as HTTP response.

 @GET
 @Path("/{id}")
 @Produces("application/json")
 public Product getProduct(@PathParam("id") Integer id) {
    return inventory.get(id);
 }

 If you want more control on building your response and sending different HTTP status code then below function will help.

  @GET
  @Path("/{id}")
  @Produces("application/json")
  public Response getProduct(@PathParam("id") Integer id) {
     Product productEntity = inventory.get(id);
     return (productEntity != null) ?
               Response.status(200).entity(productEntity).build() :
               Response.status(404).entity("Product not found").build();
  }
 curl -H 'Authorization: Basic YWRtaW46YWRtaW4=' -i http://localhost:8080/resteasyexamples/rest/products/1 
 HTTP/1.1 200
 Content-Type: application/json
 Transfer-Encoding: chunked
 Date: Sun, 26 May 2019 17:17:46 GMT

 {"product":{"@id":1,"name":"Inspiron Laptop","availableQty":5,"brand":"Dell"}}


Update a Product for given ID

To modify a product, PUT method should be used. Send the modified product information as message body and its respective Id as path parameter. 

 @PUT
 @Path("/{id}")
 @Consumes("application/json")
 @Produces("application/text")
 public String updateProduct(@PathParam("id") Integer id, Product productDetails) {
     inventory.remove(id);
     Product updatedproduct = new Product(maxProductId++, productDetails);
     inventory.put(updatedproduct.getId(), updatedproduct);
     return "product updated successfully and new id - " + updatedproduct.getId();
 }

 

curl command with PUT method, send modified product json details with its Id in the URL

curl -X PUT -H 'Authorization: Basic YWRtaW46YWRtaW4=' -H 'Content-Type:application/json' -v http://localhost:8080/resteasyexamples/rest/products/4 -d '{"product":{"name":"Keyboard","availableQty":4,"brand":"HP"}}'
* Trying 127.0.0.1...
* TCP_NODELAY set
* Connected to localhost (127.0.0.1) port 8080 (#0)
> PUT /resteasyexamples/rest/products/4 HTTP/1.1
> Host: localhost:8080
> User-Agent: curl/7.58.0
> Accept: */*
> Authorization: Basic YWRtaW46YWRtaW4=
> Content-Type:application/json
> Content-Length: 61
>
* upload completely sent off: 61 out of 61 bytes
< HTTP/1.1 200
< Content-Type: application/text
< Content-Length: 42
< Date: Sun, 26 May 2019 16:43:43 GMT
<
* Connection #0 to host localhost left intact
product updated successfully and new id - 5

 

Delete product

 Delete JAX-RS method is annotated and the path parameter provided as product id will be used to remove the product.

  @DELETE
  @Path("/{id}")
  @Produces("application/text")
  public String deleteProduct(@PathParam("id") Integer id) {
     inventory.remove(id);
     return "product deleted successfully";
  }

curl command with delete method, product gets deleted which can be confirmed by invoking get all products.

curl -X DELETE -H 'Authorization: Basic YWRtaW46YWRtaW4=' -i http://localhost:8080/resteasyexamples/rest/products/6
HTTP/1.1 200
Content-Type: application/text
Content-Length: 28
Date: Sun, 26 May 2019 17:23:15 GMT

product deleted successfully

 

Finally get call to verify the update and delete happened successfully.

curl -H 'Authorization: Basic YWRtaW46YWRtaW4=' -v http://localhost:8080/resteasyexamples/rest/products 
* Trying 127.0.0.1...
* TCP_NODELAY set
* Connected to localhost (127.0.0.1) port 8080 (#0)
> GET /resteasyexamples/rest/products HTTP/1.1
> Host: localhost:8080
> User-Agent: curl/7.58.0
> Accept: */*
> Authorization: Basic YWRtaW46YWRtaW4=
>
< HTTP/1.1 200
< Content-Type: application/json
< Transfer-Encoding: chunked
< Date: Sun, 26 May 2019 17:23:22 GMT
<
* Connection #0 to host localhost left intact
[{"product":{"@id":1,"name":"Inspiron Laptop","availableQty":5,"brand":"Dell"}},{"product":{"@id":2,"name":"Power X","availableQty":3,"brand":"LG"}},{"product":{"@id":5,"name":"Keyboard","availableQty":4,"brand":"HP"}}]

 

Reference:

RESTEasy Framework - https://resteasy.github.io/index.html

Code samples - https://github.com/nagappan080810/resteasy_workbook

 


Sponsored:
To find embedded technology information about MCU, IoT, AI etc Check out embedkari.com.


   

Nagappan is a techie-geek and a full-stack senior developer having 10+ years of experience in both front-end and back-end. He has experience on front-end web technologies like HTML, CSS, JAVASCRIPT, Angular and expert in Java and related frameworks like Spring, Struts, EJB and RESTEasy framework. He hold bachelors degree in computer science and he is very passionate in learning new technologies.

Subscribe to our newsletter.

We will send mail once in a week about latest updates on open source tools and technologies. subscribe our newsletter



Related Articles

ETag Easy With RESTEasy

  • resteasy etag http-header rest-api

RESTEasy is a JBoss project that provides various frameworks to help you build RESTful Web Services and RESTful Java applications. It comprises of frameworks for mock, embeddable server, rest client, proxy servers, logging and so on.In this article, we will walk-through ETag implementation and show the behaviour related to ETag done by rest easy framework. Example is developed using RESTEasy 3.7 and deployed in tomcat as RESTEasy framework is portable.

Read More


RESTEasy Advanced Guide - Filters and Interceptors

  • resteasy rest-api filters interceptors java

RESTEasy is JAX-RS 2.1 compliant framework for developing rest applications. It is a JBoss project that provides various frameworks to help you build RESTful Web Services and RESTful Java applications. It is a fully certified and portable implementation of the JAX-RS 2.1 specification, a JCP specification that provides a Java API for RESTful Web Services over the HTTP protocol.

Read More


RESTEasy Advanced guide - File Upload

  • resteasy rest-api file-upload java

RESTEasy is a JBoss project that provides various frameworks to help you build RESTful Web Services and RESTful Java applications. It is a fully certified and portable implementation of the JAX-RS 2.1 specification, a JCP specification that provides a Java API for RESTful Web Services over the HTTP protocol. It is licensed under the ASL 2.0.

Read More


Light4j Cookbook - Rest API, CORS and RDBMS

  • light4j sql cors rest-api

Light 4j is a fast, lightweight and cloud-native microservices framework. In this article, we will see what and how hybrid framework works and integrate with RDMS databases like MySQL, also built in option of CORS handler for in-flight request.

Read More


Introduction to Light 4J Microservices Framework

  • light4j microservice java programming framework

Light 4j is fast, lightweight, secure and cloud native microservices platform written in Java 8. It is based on pure HTTP server without Java EE platform. It is hosted by server UnderTow. Light-4j and related frameworks are released under the Apache 2.0 license.

Read More



Getting Started on Angular 7

  • angular ui-ux front-end-framework

Angular is a platform for building responsive web, native desktop and native mobile applications. Angular client applications are built using HTML, CSS and Typescript. Typescript is a typed superset of Javascript that compiles to plain Javascript. Angular core and optional modules are built using Typescript. Code has been licensed as MIT License.

Read More


Push Notifications using Angular

  • angular push-notifications notifications

Notifications is a message pushed to user's device passively. Browser supports notifications and push API that allows to send message asynchronously to the user. Messages are sent with the help of service workers, it runs as background tasks to receive and relay the messages to the desktop if the application is not opened. It uses web push protocol to register the server and send message to the application. Once user opt-in for the updates, it is effective way of re-engaging users with customized content.

Read More


Getting Started on Undertow Server

  • java web-server undertow rest

Undertow is a high performing web server which can be used for both blocking and non-blocking tasks. It is extermely flexible as application can assemble the parts in whatever way it would make sense. It also supports Servlet 4.0, JSR-356 compliant web socket implementation. Undertow is licensed under Apache License, Version 2.0.

Read More


Angular Service Workers Usage Guide

  • angular service-worker offline-app

Web developers come across scenarios like web application completely breaks when workstation goes offline. Likewise to get into our application, every time we need to open a browser and then access it. Instead if it is in app, it will be easy to access for end-user. Push notifications similar to email client need to be done through web application. All these are addressed by a magic called service worker.

Read More


JWT Authentication using Auth0 Library

  • java jwt authentication security

Json Web Token shortly called as JWT becomes defacto standard for authenticating REST API. In a traditional web application, once the user login credentials are validated, loggedin user object will be stored in session. Till user logs out, session will remain and user can work on the web application without any issues. Rest world is stateless, it is difficult to identify whether the user is already authenticated. One way is to use authenticate every API but that would be too expensive task as the client has to provide credentials in every API. Another approach is to use token.

Read More


Caching using Ehcache Java Library

  • ehcache cache java map key-value

Ehcache from Terracotta is one of Java's most widely used Cache. It is concurrent and highly scalable. It has small footprint with SL4J as the only dependencies. It supports multiple strategies like Expiration policies, Eviction policies. It supports three storage tiers, heap, off-heap, disk storage. There are very few caching products supports multiple tier storage. If you want to scale, you cannot store all items in heap there should be support for off-heap and disk storage. Ehcache is licensed under Apache 2.0. In this article, we can see about basic usage of Ehcache.

Read More


Connect to MongoDB and Perform CRUD using Java

  • java mongodb database programming

MongoDB is a popular and widely used open source NoSQL database. MongoDB is a distributed database at its core, so high availability, horizontal scaling, and geographic distribution is quite possible. It is licensed under Server Side Public License. Recently they moved to Server Side Public License, before that MongoDB was released under AGPL. This article will provide basic example to connect and work with MongoDB using Java.

Read More


Exonum Blockchain Framework by the Bitfury Group

  • blockchain bitcoin hyperledger blockchain-framework

Exonum is an extensible open source blockchain framework for building private blockchains which offers outstanding performance, data security, as well as fault tolerance. The framework does not include any business logic, instead, you can develop and add the services that meet your specific needs. Exonum can be used to build various solutions from a document registry to a DevOps facilitation system.

Read More


JHipster - Generate simple web application code using Spring Boot and Angular

  • jhipster spring-boot angular web-application

JHipster is one of the full-stack web app development platform to generate, develop and deploy. It provides the front end technologies options of React, Angular, Vue mixed with bootstrap and font awesome icons. Last released version is JHipster 6.0.1. It is licensed under Apache 2 license.

Read More


MailHog - Web and API based SMTP testing

  • smtp-testing testing-tool smtp test automation email-server email

Most of the projects will have a requirement of sending and receiving mails. We have mentioned about GreenMail - Email Test Framework, in our previous article about API based SMTP testing. In this article, we discuss about MailHog - Web and API based SMTP testing. You send out a mail from your code and you can check it via web visually and also via API. Those who do API testing can check via API. Developers may want to visually verify the format of the mail. MailHog is a best bet for SMTP testing.

Read More


Solr vs Elastic Search

  • full-text-search search-engine lucene solr elastic-search

Solr and Elastic Search are built on top of Lucene. Both are open source and both have extra features which makes programmer life easy. This article explains the difference and the best situation to choose between them.

Read More


GreenMail - Email Test Framework in Java

  • email email-server test automation

In any project there will be a need to send mail out to users. It could be an alert mail, forget password or authentication related mail. Mail is the default communication between the software and the users. As a developer, we can write code, to send out a mail but we need to make sure whether it got successfully received and how the body of mail, Is it the same like what we have sent. GreenMail is a Email test framework which helps to send and receive mails. It is a test framework which supports SMTP, POP3, IMAP including SSL.

Read More


Best open source Text Editors

  • text-editor editor tools dev-tools

Text editors are mainly used by programmers and developers for manipulating plain text source code, editing configuration files or preparing documentation and even viewing error logs. Text editors is a piece of software which enables to create, modify and delete files that a programmer is using while creating website or mobile app.In this article, we will discuss about top 7 all-round performing text editors which is highly supportive for programmers.

Read More


Quick Start Programming Guide for redis using java client Jedis

  • redis jedis redis-client programming database java

Redis is an open source (BSD licensed), in-memory data structure store, used also as a database cache and message broker. It supports data structures such as strings, hashes, lists, sets, sorted sets with range queries, bitmaps, hyperloglogs, geospatial indexes with radius queries and streams. This article explains about how to communicate with Redis using Java client Jedis.

Read More


Enhancing The Experience With Android TV: Briefly About One Developer's Impressions

  • android android-tv

In my software development career, I have always been attracted to new technologies and innovative solutions. Project by project, I have been exploring something new, discovering and implementing different approaches and trying new solutions. When Android TV showed up, I set a new personal goal. I described my impressions and the overall opinion on the application development for Android TV right here. Hope you will find it useful and interesting.

Read More