Spring RESTful Web Service with JSON using Spring Boot

  • Facebook
  • Google
  • LinkedIn
  • Twitter

Creating Spring-based application you need to lot of xml configuration required before doing actual development. But now with Spring Boot is possible to build production-ready Spring applications. Spring Boot API provides easy way of creating standalone applications with minimum effort and very less configurations. It contains embedded tomcat or jetty to run web applications. Using API no need to worry about creating war. Spring Boot`s main benefit is configuring the resources based on what it finds in the classpath. For example if POM includes JPA dependencies and a MYSQL driver, then Spring Boot will setup automatically a persistence unit based on MySQL. If you added a web dependency in POM, then you will get Spring MVC configured and no need to configure you manually.

1. Create POM with below dependencies

<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">
			<name>Spring Snapshots</name>
			<name>Spring Milestones</name>

2. Create Controller java class (CityController.java)

package com.javatutsworld.controller;
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;
import com.javatutsworld.model.*;
public class CityController {
	@RequestMapping(value = "/{code}", method = RequestMethod.GET)
	public @ResponseBody
	City getCity(@PathVariable String code) {
		if (code.equals("SRE")) {
			return new City("Saharanpur", "Uttar Pardesh");
		} else if(code.equals("PN")) {
			return new City("Panipat", "Hariyana");
			return new City("No valid code", "No valid state");
	public static void main(String[] args) throws Exception {
		SpringApplication.run(CityController.class, args);

This controller class used to handle web service requests, here you added @EnableAutoConfiguration to take up auto configuration.

3. Create Model class (City.java)

package com.javatutsworld.model;

public class City {
	private String name;
	private String capital;
	public City(String name, String capital) {
		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 this main program web service started via spring boot. Below is url


Spring Rest