Searching...
Wednesday, 11 December 2013

Spring Boot JSON Restful web service example

10:10
Spring  Boot API provides easy way of creating stand alone applications with minimum effort and very less configurations. It contains embedded tomcat or jetty to run web applications. Using this API no need to worry about creating war and other configuration. See more about Spring boot
Here is one simple web service which is returning state name and capital as JSON format upon passing state code.

1. Create a Maven Project and add below dependencies 

 

<parent>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-parent</artifactId>
        <version>1.3.1.RELEASE</version>
    </parent>
    <dependencies>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-web</artifactId>
        </dependency>
    </dependencies>
 

2. Create a Resource Controller class (StateController.java)


This is a controller class which is handling web service requests, here we are adding @EnableAutoConfiguration to take up auto configuration and in the main method using SpringApplication.run to create instance of the controller class.
package com.vinod.test;

import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.EnableAutoConfiguration;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;

@Controller
@RequestMapping("/state")
@EnableAutoConfiguration
public class StateController {
    @RequestMapping(value = "/{code}", method = RequestMethod.GET)
    public @ResponseBody State getState(@PathVariable String code) {
        if (code.equals("KL")) {
            return new State("Kerala", "Trivandrum");
        } else {
            return new State("Default State", "Default Capital");
        }
    }
    public static void main(String[] args) throws Exception {
        SpringApplication.run(StateController.class, args);
    }
}

class State {
    private String name;
    private String capital;

    public State(String name, String capital) {
        super();
        this.name = name;
        this.capital = capital;
    }

    public String getName() {
        return name;
    }

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

    public String getCapital() {
        return capital;
    }

    public void setCapital(String capital) {
        this.capital = capital;
    }

}

3. Run it

Run the above main program, your web service started via spring boot. Let us test this with below url http://localhost:8080/state/KL



0 comments: