What is RESTful Web service
- (REST) Representational State Transfer gives access to data on demand.
- Web service work on a stateless protocol HTTP
- To send or receive data between two application over a network.
- The data contains a String of JSON or array of JSON .
- The data can be XML or CSV
Refer to Wiki link for RESTful definition.
Requirement to build Spring boot web service example
1. JDK
2. Eclipse or STS (Spring Tool Suite)
3. Web Browser or Postman
4. A Spring boot application (if not Created) . Use the process of how to create spring boot application by visiting the following Link.
How to create spring boot project in STS using maven
Code Required to complete a Sample Spring boot web service example
- Add a class as a POJO(Plain Old Java Class) to represent data.
- Add a Rest Controller class to create end point of Web Service and to return JSON
View the following video to complete the code creation for Spring boot web service example
Code for POJO(Plain Old Java Class) to represent data.
Create a package inside parent package.
Eg: If following is the parent package of Spring Boot project where main method’s class exist
com.cyber.deb.demosts
Then create a package as follows named models
com.cyber.deb.demosts.models
Process: Right click of existing package and click on New then click on Create Package to give the above package name.
Person.java
package com.cyber.deb.demosts.models; public class Person { String name; int age; public String getName() { return name; } public void setName(String name) { this.name = name; } public int getAge() { return age; } public void setAge(int age) { this.age = age; } }
Create a Rest Controller class to create end point of Web Service and to return JSON
Create another package inside parent package for controller.
Eg: If following is the parent package of Spring Boot project where main method’s class exist
com.cyber.deb.demosts
Then create a package as follows named controller
com.cyber.deb.demosts.controller
Process: Right click of existing package and click on New then click on Create Package to give the above package name.
PersonsController.java
package com.cyber.deb.demosts.controller;
import java.util.ArrayList;
import java.util.List;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import com.cyber.deb.demosts.models.Person;
@RestController
public class PersonsController {
@RequestMapping("/showPersons")
public List getPersons()
{
List personsList=new ArrayList();
Person p1=new Person();
p1.setName("John");
p1.setAge(24);
Person p2=new Person();
p2.setName("Stalin");
p2.setAge(24);
personsList.add(p1);
personsList.add(p2);
return personsList;
}
}
After creating the above two files then the project explorer of STS will look as follows.
Run the code to view JSON in web browser or Postman
Right click on Project ——- Run As——Spring Boot App (In STS)
Or
Right click on Main class’s java file — Run As– Java Application