Restful Services

Developing a RESTful Web Service Using Spring Boot 1.4

Posted on

spring_mvc_rest

 

 

 

In this article, we will see the full example of developing an application using Spring boot 1.4.3 Release version. Along with MVC RESTFul example to accomplish a CURD operation.

Before we kick off in example details, we would give you some insight about Spring.boot

What is Spring Boot ?

It is a framework for developing a stand-alone application, Its provide defaults for code and annotation configuration that help us to quickly start new Spring project.

Spring Boot is nothing but a top up on existing Spring Framework with embedded Server ( Jetty + Tomcat ). The goal of Spring Boot Framework is to minimize the development and Testing ( JUnit & Integration ) time and provide production ready features like a metrics, health, logs and externalized configuration.

Features

  • Create stand-alone Spring applications
  • Embed Tomcat, Jetty or Undertow directly (no need to deploy WAR files)
  • Provide opinionated ‘starter’ POMs to simplify your Maven configuration
  • Automatically configure Spring whenever possible
  • Provide production-ready features such as metrics, health checks and externalized configuration
  • Absolutely no code generation and no requirement for XML configuration.

Advantages of Spring Boot:

  • It is very easy to develop Spring Based applications with Java or Groovy.
  • It reduces lots of development time and increases productivity.
  • It avoids writing lots of boilerplate Code, Annotations and XML Configuration.
  • It is very easy to integrate Spring Boot Application with its Spring Ecosystem like Spring JDBC, Spring ORM, Spring Data, Spring Security etc.
  • It follows “Opinionated Defaults Configuration” Approach to reduce Developer effort
  • It provides Embedded HTTP servers like Tomcat, Jetty etc. to develop and test our web applications very easily.
  • It provides CLI (Command Line Interface) tool to develop and test Spring Boot(Java or Groovy) Applications from command prompt very easily and quickly.
  • It provides lots of plugins to develop and test Spring Boot Applications very easily using Build Tools like Maven and Gradle
  • It provides lots of plugins to work with embedded and in-memory Databases very easily.

Let start with Spring Boot Example Step by Step :-

It’s is recommended to start spring.boot application using dependency management system like Maven or Gradle. Here we use Maven to build a Spring Boot application. Below are dependencies in pom.xml which can be created manually or created by SPRING INITIALIZR – recommended to use it to develop a simple Spring Boot Application.

pom.xml


<?xml version="1.0" encoding="UTF-8"?>
<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>com.spring.boot.example</groupId>
    <artifactId>Spring_Boot</artifactId>
    <version>0.0.1-SNAPSHOT</version>
    <packaging>jar</packaging>
    <!--http://start.spring.io/-->
    <name>spring_boot</name>
    <description>Demo project for Spring Boot</description>

    <parent>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-parent</artifactId>
        <version>1.4.3.RELEASE</version>
        <relativePath/> <!-- lookup parent from repository -->
    </parent>

    <properties>
        <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
        <project.reporting.outputEncoding>UTF-8</project.reporting.outputEncoding>
        <java.version>1.8</java.version>
    </properties>

    <dependencies>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-web</artifactId>
        </dependency>

        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-test</artifactId>
            <scope>test</scope>
        </dependency>
    </dependencies>

    <build>
        <plugins>
            <plugin>
                <groupId>org.springframework.boot</groupId>
                <artifactId>spring-boot-maven-plugin</artifactId>
            </plugin>
        </plugins>
    </build>
</project>

Create a RESTFul Controller that handle CURD operation using endpoints. Spring 4.3 introduced new annotations which serve the same purpose as @RequestMapping having predefined ‘method’ (HTTP verb) value. These annotations are actually themselves annotated with @RequestMapping with the related value of ‘method’ element.

Followings are those annotations:

  • @GetMapping
  • @PostMapping
  • @PutMapping
  • @DeleteMapping
  • @PatchMapping

DevOpsController.java

package com.spring.example.controller;

import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;

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

/**
 * Created by MYPC on 1/9/2017.
 */
@RestController
public class DevOpsController {

    @GetMapping
    public ResponseEntity<?> sayHello() {
        return ResponseEntity.status(HttpStatus.OK).body("Welcome to my first Sprint boot example");
    }

    @PutMapping
    public ResponseEntity<?> putMethod(@RequestBody String payload) {
        System.out.println(" Put Method Call :-> Payload " + payload);
        return ResponseEntity.ok("OK");
    }

    @PostMapping
    public ResponseEntity<?> postMethod(@RequestBody String payload) {
        System.out.println(" POST Method Call :-> Payload " + payload);
        return ResponseEntity.ok("OK");
    }

    @DeleteMapping
    public ResponseEntity<?> deleteMethod(@RequestBody String payload) {
        System.out.println(" DELETE Method Call :-> Payload " + payload);
        return ResponseEntity.ok("OK");
    }

    @GetMapping(path = "/list")
    public ResponseEntity<?> getList() {
        List list = new ArrayList<>();
        list.add("One");
        list.add("Two");
        list.add("Three");
        list.add("Four");
        return ResponseEntity.status(HttpStatus.OK).body(list);
    }
}

And Main Application class to start Spring-Boot application along with Server.


package com.spring.example;

import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.EnableAutoConfiguration;
import org.springframework.context.annotation.ComponentScan;

/**
 * list
 * Created by AJAY KUMAR on 1/9/2017.
 */
@EnableAutoConfiguration
@ComponentScan(basePackages = "com.spring.example.controller")
public class SpringBootApplication {
    public static void main(String[] args) {
        SpringApplication.run(SpringBootApplication.class, args);
    }
}


 

Run SpringBootApplication.java as normal java program, It will start embedded Tomcat on port no 8080. Below are output’s snapshot.
springboot-rest

RESTful example with Tomcat and maven

Posted on Updated on

RESTful example with Tomcat and Maven

This is a Simple example of RESTful using jersey service in eclipse which is intended to explore how to implement RESTful services in our project. In web.xml file, Full qualified package is given to scan all services class under this package it will automatically happened at deployment time also servlet-mapping defined services mapping pattern in this case /rest/* means all RESTful container will be treated all services as RESTful service that start with /rest/*. example :-

  • /rest/user
  • /rest/user/{user_id}

Create and configure a pom.xml which contains all required dependencies for RESTful.

pom.xml file under root directory in your project:-


<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/maven-v4_0_0.xsd">

<groupId>com.rest</groupId>
<modelVersion>4.0.0</modelVersion>
<artifactId>RESTfulExample1</artifactId>
<name>RESTfulExample1</name>
<version>1.1-SNAPSHOT</version>
<packaging>war</packaging>

<description>
RESTful Example1
</description>

<dependencies>
<dependency>
<groupId>org.glassfish.jersey.containers</groupId>
<!-- if your container implements Servlet API older than 3.0, use "jersey-container-servlet-core" -->
<artifactId>jersey-container-servlet</artifactId>
<version>2.17</version>
</dependency>
<!-- Required only when you are using JAX-RS Client -->
<dependency>
<groupId>org.glassfish.jersey.core</groupId>
<artifactId>jersey-client</artifactId>
<version>2.17</version>
</dependency>
<dependency>
<groupId>org.glassfish.jersey.core</groupId>
<artifactId>jersey-server</artifactId>
<version>2.17</version>
</dependency>
<dependency>
<groupId>com.fasterxml.jackson.jaxrs</groupId>
<artifactId>jackson-jaxrs-json-provider</artifactId>
<version>2.2.3</version>
</dependency>

</dependencies>
<build>
<pluginManagement>
<plugins>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-war-plugin</artifactId>
<version>2.4</version>
<configuration>
<warSourceDirectory>/web</warSourceDirectory>
<warName>RESTfulExample1</warName>
<failOnMissingWebXml>false</failOnMissingWebXml>
</configuration>
</plugin>
</plugins>
</pluginManagement>

<finalName>ITCM</finalName>
</build>
</project>


Project explorer in Eclipse : –

project-explorer

Project src files :-

com.rest.service

UserInfoService.Java :- Intended of this class is to produce and consume resources using RESTful service.


package com.rest.service;

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.core.MediaType;
import javax.ws.rs.core.Response;
import javax.ws.rs.core.Response.Status;

import com.rest.model.User;
import com.rest.repository.UserRepository;

@Path("/user")
public class UserInfoService {
private UserRepository userRepo = new UserRepository();

@GET
@Produces(MediaType.APPLICATION_JSON)
public Response getUsers(){
return Response.ok().entity(userRepo.getAllUsers()).build();
}

@GET
@Produces(MediaType.APPLICATION_JSON)
@Path("{user_id}")
public Response getUser(@PathParam("user_id") int user_id){
return Response.ok().entity(userRepo.getUser(user_id)).build();
}

@POST
@Produces(MediaType.APPLICATION_JSON)
@Consumes(MediaType.APPLICATION_JSON)
public Response postUser(User user){
userRepo.insert(user);
return Response.ok().status(Status.OK).build();
}

@PUT
@Produces(MediaType.APPLICATION_JSON)
@Consumes(MediaType.APPLICATION_JSON)
public Response putUser(User user){
userRepo.update(user);
return Response.ok().build();
}

@DELETE
@Path("/{user_id}")
@Produces(MediaType.APPLICATION_JSON)
@Consumes(MediaType.APPLICATION_JSON)
public Response deleteUser(@PathParam("user_id") int user_id){
userRepo.deleteUser(user_id);
return Response.ok().build();
}


}

 com.rest.reporitory

UserRepository.Java :- Intended of repository class to perform CRUD operation over user data.


package com.rest.repository;

import java.util.Collection;

import com.rest.factory.UserRepositoryFactory;
import com.rest.model.User;

public class UserRepository {
private UserRepositoryFactory userFactory = UserRepositoryFactory.getInstance();

public User getUser(int id){
return userFactory.getUser(id);
}

public Collection<User> getAllUsers(){
return userFactory.getListOfUsers().values();
}

public User deleteUser(int id){
return userFactory.deleteUser(id);
}

public void insert(User user){
userFactory.getUpdate(user);
}

public void update(User user){
userFactory.getUpdate(user);;
}
}

 com.rest.model

User.java :- this is a pojo/model java class this is used to wrap the User properties either user response or request parameters.


package com.rest.model;

import java.io.Serializable;

public class User implements Serializable{

/**
*
*/
private static final long serialVersionUID = 3228632501659659215L;
private int id;
private String name;
private String address;
public User(){

}

public User(int id, String name, String address) {
this.id = id;
this.name = name;
this.address = address;
}
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getAddress() {
return address;
}
public void setAddress(String address) {
this.address = address;
}

}

 com.rest.factory

UserRepositoryFactory.java:- intended of this factory class to provide User data.


package com.rest.factory;

import java.util.HashMap;
import java.util.Map;

import com.rest.model.User;

public class UserRepositoryFactory {

private static Map<Integer, User> users = new HashMap<Integer, User>();

public Map<Integer, User> getListOfUsers() {
User u1 = new User(101, "Ajay Kumar", "New Delhi");
User u2 = new User(102, "Rahul Kumar", "Goa");
User u3 = new User(103, "Santosh Kumar", "Delhi");
users.put(u1.getId(), u1);
users.put(u2.getId(), u2);
users.put(u3.getId(), u3);
return users;
}

public User getUser(Integer id) {
return users.get(id);
}

public User deleteUser(Integer id) {
return users.remove(id);
}

public void getUpdate(User user) {
if (users.containsKey(user.getId())) {
// update user here
users.put(user.getId(), user);
} else {
// add user
users.put(user.getId(), user);
}
}

private UserRepositoryFactory() {
}

private static UserRepositoryFactory userRepository = new UserRepositoryFactory();

public static UserRepositoryFactory getInstance() {
if (userRepository == null) {
synchronized (UserRepositoryFactory.class) {
userRepository = new UserRepositoryFactory();
}
}
return userRepository;
}
}

Web-description file ( web.xml ):-


<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns="http://java.sun.com/xml/ns/javaee"
xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_3_0.xsd"
id="WebApp_ID" version="3.0">
<display-name>RESTfulExample1</display-name>

<servlet>
<servlet-name>REST</servlet-name>
<servlet-class>org.glassfish.jersey.servlet.ServletContainer</servlet-class>
<init-param>
<param-name>jersey.config.server.provider.packages</param-name>
<param-value>
com.jersey.jaxb,com.fasterxml.jackson.jaxrs.json,com.rest.service
</param-value>
</init-param>
</servlet>
<servlet-mapping>
<servlet-name>REST</servlet-name>
<url-pattern>/rest/*</url-pattern>
</servlet-mapping>
</web-app>

GET method:-

  • /rest/user : – Fetch all users
  • /rest/user/101 – Fetch User which id is 101

GET-User

POST method :-

  • /rest/user :- Add User
    • Method:Post
    • Content-Type:application/json
    • JSON Request Parameter : { “id”: 107, “name”: “Rahul Kumar”, “address”: “Goa” }
    • Return Response : Response Status OK

POST-User

PUT method :-

  • /rest/user :- Update User
    • Method:PUT
    • Content-Type:application/json
    • JSON Request Parameter : { “id”: 107, “name”: “Any name”, “address”: “Any City” }
    • Return Response : Response Status OK

PUT-User

DELETE method :-

  • /rest/user/101 :- Delete User which user id is 101
    • Method:DELETE
    • Return Response : Response Status OK

DELETE-User-BY-ID

Below step’s are done using RESTful tools to fire rest services

 Download Complete source code from here

 

RESTful Service in Java

Posted on Updated on

RESTful Service in Java.

Table of Contents:-

  1. What is RESTful service in Java ?
  2. How to implement it in Web Application ?

 

What is RESTful service in Java ?

Representation state transfer(REST) is architecture style that specifies constraints i.e Uniform resource identifier(URI). REST architecture style represents data,functionality as resources that are accessed by URI. REST create a bridge between Client/Server architecture and communicate over stateless HTTP protocol and Client/Server exchange representation  resources by using standardized interface and protocol.

URL ( Uniform Resource Locator ) formation :-

URL : <Protocol> ://< Hostname> :< port>/<Context-name>/<URL>

http://localhost:8080/RESTfulExample1/rest/user/102

RESTful ( JAX-RS) annotation summary :-

  • @path : – It’s used to represents an URI path template which the resource response it.
  • @consume :- It’s used to specify MIME media type representation of a resource can consume that were sent by client.
  • @produce :- it’s used to specify MIME media type representation of a resource can produce that send back to client like “application/json”,”application/text”.
  • @ParamPath :- The @PathParam annotation is a type of parameter that you can extract for use in your resource class.URI path parameters are extracted from the request URI, and the parameter names correspond to the URI path template variable names specified in the @Path class-level annotation.
  • @QueryParam :- The @QueryParam annotation is a type of parameter that you can extract for use in your resource class. Query parameters are extracted from the request URI query parameters.
  • @Context :- @Context can be used to obtain contextual Java types related to the request or response.

How to convert an Object into Response Type (“JSON/Text/Xml”):-

Using javax.ws.rs.core.Response , contract between a returned instance and the runtime when an application needs to provide metadata to the runtime.

@GET
 @Produces(MediaType.APPLICATION_JSON)
 public Response getUsers(){
 return Response.ok().entity(userRepo.getAllUsers()).build();
 }

HTTP methods :-

  • GET : – it’s used to read a specified resource.
  • POST :- it’s used to create a specified resource.
  • PUT :-  it’s used to update a specified resources
  • DELETE :-it’s used to delete a specified resources
  • HEAD :- Same as GET but returns only HTTP headers and no document body

Key Points :-

  • It’s not a protocol.
  • It’s a architecture style that represent a resources that are accessed by URI.
  • Communication over HTTP is stateless.
  • It’s scalable,reliable and portable by nature.

Example with source code below :

  1. RESTful example with Tomcat and Maven.