In this section, you will learn how to create a RESTful web service. The concepts explained earlier in this chapter will be used.
The following are some of the key aspects of creating a RESTful web service. Let's take the example of retrieving the doctors' list based on the specialties, location, and so on.
Create a controller representing the RESTful endpoint: In the following code, note the usage of the @RestController annotation, which is used to represent the annotation @Controller and @ResponseBody. The controller has a method, searchDoctor, for handling the request represented using the URL such as /doctors?location=xxx&speciality=yyy. Note the @RequestMapping annotation and its attributes, especially, "produces", which signifies the fact that the output sent to the user will be in the JSON format.
@RestController public class DoctorSearchController {
Create a RESTful API: For retrieving the list of doctors based on location and speciality, the URL could look like http://localhost:8080/doctors?location=xxx&speciality=yyy.
Identify the method of processing incoming requests data: @RequestParam will be used to process the incoming requests data as mentioned in the preceding URL. In the previous code, note how @RequestParam is used for processing the value of both the location and the specialty parameter. The following code represents the same:
public DoctorList searchDoctor( @RequestParam(value="location", required=false) String location, @RequestParam(value="specialty", required=false) String speciality) { // Code goes here }
Create a class representing ResponseBody: The return value is the DoctorList object, which consists of a list of Doctors. The following code represents the DoctorList object which is a list of the Doctor object:
// The class representing the list of Doctor; Returned as a response public class DoctorList { private List<Doctor> doctors;
public DoctorInfo(List<Doctor> doctors) { this.setDoctors(doctors); } public List<Doctor> getDoctors() { return doctors; } public void setDoctors(List<Doctor> doctors) { this.doctors = doctors; } }
The following represents the Doctor class which is returned as part of the response object:
public String getId() { return id; } public void setId(String id) { this.id = id; } public String getFirstName() { return firstName; } public void setFirstName(String firstName) { this.firstName = firstName; } public String getLastName() { return lastName; } public void setLastName(String lastName) { this.lastName = lastName; } public String getSpecialityCode() { return specialityCode; } public void setSpecialityCode(String specialityCode) { this.specialityCode = specialityCode; } }
Client response: The client receives the response body in the JSON format. The following is a sample response which is returned by the execution of the preceding code: