Spring boot rest example

Source: Internet
Author: User
Tags representational state transfer spring initializr

Spring boot rest example

Introduction: This article will help you use Spring Boot to create simple REST services.

You will learn

  1. What is a REST service?
  2. How to Use Spring Initializr to guide the creation of Rest service applications?
  3. How do I create a REST service to retrieve student-registered courses?
  4. How do I create Post REST services for student registration courses?
  5. How can I use postman to execute the rest service?

The rest service used in this tutorial

In this tutorial, we will use the appropriate URI and HTTP methods to create three services:

@ GetMapping ("/students/{studentId}/courses"): You can use the Request Method Get and example uri/students/Student1/courses to query the registered courses of a specific student.

@ GetMapping ("/students/{studentId}/courses/{courseId }"): you can use the Request Method Get and example uri/students/Student1/courses/Course1 to obtain specific courses for specific students.

@ PostMapping ("/students/{studentId}/courses"): You can register a course for students by sending a POST request to UURI/students/Student1/courses

You will need the tool

  1. Maven 3.0 + is your build tool
  2. Your favorite IDE. We use Eclipse.
  3. JDK 1.8 +

 Complete sample code for spring booot rest Maven Project

Our Github repository contains all code examples-https://github.com/in28minutes/in28minutes.github.io/tree/master/code-zip-files

REST services with unit and integration tests

Website-springbootrestservices-simplerestserviceswithunitandintegrationtests.zip

 What is REST?

REST stands for REpresentational State Transfer. REST specifies a set of architecture constraints. Any service that meets the following conditions is called a RESTful service.

Five important conditions for RESTful Web Service:

  1. Client-server: there should be a service producer and a service user.
  2. Interfaces (URLs) are uniform and resources are exposed.
  3. This service is stateless.
  4. Service results should be cacheable. For example, HTTP cache.
  5. Services should adopt a layered architecture. The client should not directly connect to the server-it may obtain information from the intermediate layer-cache.

 Richards Maturity Model

The Richard dson maturity model is used to identify the maturity level of Restful Web Services. The following are different levels and features:

Level 0: Expose SOAP Web Services in the rest style. Public operations use the REST Service (http: // server/getPosts, http: // server/deletePosts, http: // server/doThis, http: // server/doThat ).

Level 1: use the correct URI (using nouns) to publish resources. For example, http: // server/accounts, http: // server/accounts/10. However, the HTTP method is not used.

Level 2: The resource uses the correct URI + HTTP method. For example, to update an account, you need to make a PUT. Create an account and make a POST. Uri looks like posts/1/comments/5 and accounts/1/friends/1.

Level 3: HATEOAS (Hypermedia as the engine of application state ). You can understand not only the requested information, but also the next possible operation that a service consumer can take. When requesting information about a Facebook user, the REST service can return the user's details and how to obtain his recent post, how to get his recent comments and how to retrieve the list of his friends.

Use appropriate request methods

Always use the HTTP method. The best practices for each HTTP method are described as follows:

GET: nothing should be updated. It should be idempotent (the same result is called multiple times ). Possible return code 200 (OK) + 404 (NOT FOUND) + 400 (BAD REQUEST)

POST: create a resource. Ideally, JSON is returned and linked to the newly created resource. Use the same return code as much as possible. In addition, the return code 201 (create) is possible.

PUT: Update known resources. For example, update customer details. Possible return code: 200 (OK)

DELETE: Used to DELETE a resource.

Project Structure

The following screen shows the structure of the project we will create.

Some details:

  1. StudentController. java-rest Controller provides all three service methods discussed above.
  2. Course. java, Student. java, StudentService. java-business logic of the application. StudentService provides some methods we consume from the Rest controller.
  3. StudentControllerIT. java-rest service integration test.
  4. StudentControllerTest. java-test service unit test.
  5. The starter of the StudentServicesApplication. java-Spring Boot application. To run the application, you only need to start the file as a Java application.
  6. Pom. xml-contains all dependencies required to build this project. We will use Spring Boot Starter Web.

Use Spring Initializr to guide creation of REST services

Using Spring Initializr to create a REST service is very easy. We will use Spring Web MVC as our web layer framework.

Spring Initializr http://start.spring.io/is a good tool to guide the creation of Spring Boot projects.

As shown in, perform the following steps:

Start Spring Initializr and select the following content

Select com. in28minutes. springboot as Group.

Select student-services as Artifact

Select the following Dependencies

  1. Web
  2. Actuator
  3. DevTools

Click Generate project.

Import the project to Eclipse. File> Import> existing Maven project.

If you want to know all the files of this project, you can continue to read down.

Application business layer implementation

All applications require data. We will use memory data storage like ArrayList instead of interacting with real databases.

One student can attend multiple courses. The course has an ID, name, description, and list of steps to complete the course. The student has an ID card, name, description, and list of courses he/she currently registered. StudentService provides the following public methods:

Public List retrieveAllStudents ()-retrieve details of all students

Public Student retrieveStudent (String studentId)-retrieve specific Student details

Public List retrieveCourses (String studentId)-retrieve all student-registered courses

Public Course retrieveCourse (String studentId, String courseId)-retrieve details of a specific Course registered by a student

Public Course addCourse (String studentId, Course course)-add courses for existing students

See the following files for details about the implementation service class StudentService and model class Course and Student.

  1. Src/main/java/com/in28minutes/springboot/model/Course. java
  2. Src/main/java/com/in28minutes/springboot/model/Student. java
  3. Src/main/java/com/in28minutes/springboot/service/StudentService. java

Add several GET Rest services

The Rest service StudentController exposes several get services.

  1. @ Autowired private StudentService studentService: We use Spring Autowiring to automatically inject the student service to StudentController.
  2. @ GetMapping ("/students/{studentId}/courses"): Use studentId as the PATH variable to publicly obtain the service
  3. @ GetMapping ("/students/{studentId}/courses/{courseId}"): Public access to services to retrieve specific courses of students.
  4. @ PathVariable String studentId: the value of studentId from uri will be mapped to this parameter.
package com.in28minutes.springboot.controller;import java.util.List;import org.springframework.beans.factory.annotation.Autowired;import org.springframework.web.bind.annotation.GetMapping;import org.springframework.web.bind.annotation.PathVariable;import org.springframework.web.bind.annotation.RestController;import com.in28minutes.springboot.model.Course;import com.in28minutes.springboot.service.StudentService;@RestControllerpublic class StudentController {@Autowiredprivate StudentService studentService;@GetMapping("/students/{studentId}/courses")public List<Course> retrieveCoursesForStudent(@PathVariable String studentId) {return studentService.retrieveCourses(studentId);}@GetMapping("/students/{studentId}/courses/{courseId}")public Course retrieveDetailsForCourse(@PathVariable String studentId,@PathVariable String courseId) {return studentService.retrieveCourse(studentId, courseId);}}

Use Postman to obtain the service

We will initiate a request to http: // localhost: 8080/students/Student1/courses/Course1 to test the service. The response is as follows.

{ "id": "Course1", "name": "Spring", "description": "10 Steps", "steps": [  "Learn Maven",  "Import Project",  "First Example",  "Second Example" ]}

The following figure shows how to execute the Postman Get Service-my favorite tool to run the rest Service.

 

Add POST Rest Service

When a resource is successfully created, the POST Service returns the created status (201 ).

  1. @ PostMapping ("/students/{studentId}/courses"): ing url for the post request
  2. @ RequestBody Course newCourse: bind the Request body to the Course object.
  3. ResponseEntity. created (location). build (): returns the created status. The location of the created resource is returned as the response title.
@PostMapping("/students/{studentId}/courses")public ResponseEntity<Void> registerStudentForCourse(@PathVariable String studentId, @RequestBody Course newCourse) {Course course = studentService.addCourse(studentId, newCourse);if (course == null)return ResponseEntity.noContent().build();URI location = ServletUriComponentsBuilder.fromCurrentRequest().path("/{id}").buildAndExpand(course.getId()).toUri();return ResponseEntity.created(location).build();}

Execute POST Rest Service

The sample request is as follows. It contains all the details of the student registration course.

{ "name": "Microservices", "description": "10 Steps", "steps": [  "Learn How to Break Things Up",  "Automate the hell out of everything",  "Have fun" ]}

Shows how we run the Post Service from Postman-my favorite tool for running the rest service. Make sure you go to the Body tab and select raw. Select JSON from the drop-down menu. Copy the preceding request to the body.

The URL we use is http: // localhost: 8080/students/Student1/courses.

Complete code example

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.in28minutes.springboot</groupId><artifactId>student-services</artifactId><version>0.0.1-SNAPSHOT</version><packaging>jar</packaging><name>student-services</name><description>Demo project for Spring Boot</description><parent><groupId>org.springframework.boot</groupId><artifactId>spring-boot-starter-parent</artifactId><version>1.4.4.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-actuator</artifactId></dependency><dependency><groupId>org.springframework.boot</groupId><artifactId>spring-boot-starter-web</artifactId></dependency><dependency><groupId>org.springframework.boot</groupId><artifactId>spring-boot-devtools</artifactId><scope>runtime</scope></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>

Src/main/java/com/in28minutes/springboot/controller/StudentController. java

import java.net.URI;import java.util.List;import org.springframework.beans.factory.annotation.Autowired;import org.springframework.http.ResponseEntity;import org.springframework.web.bind.annotation.GetMapping;import org.springframework.web.bind.annotation.PathVariable;import org.springframework.web.bind.annotation.PostMapping;import org.springframework.web.bind.annotation.RequestBody;import org.springframework.web.bind.annotation.RestController;import org.springframework.web.servlet.support.ServletUriComponentsBuilder;import com.in28minutes.springboot.model.Course;import com.in28minutes.springboot.service.StudentService;@RestControllerpublic class StudentController {@Autowiredprivate StudentService studentService;@GetMapping("/students/{studentId}/courses")public List<Course> retrieveCoursesForStudent(@PathVariable String studentId) {return studentService.retrieveCourses(studentId);}@GetMapping("/students/{studentId}/courses/{courseId}")public Course retrieveDetailsForCourse(@PathVariable String studentId,@PathVariable String courseId) {return studentService.retrieveCourse(studentId, courseId);}@PostMapping("/students/{studentId}/courses")public ResponseEntity<Void> registerStudentForCourse(@PathVariable String studentId, @RequestBody Course newCourse) {Course course = studentService.addCourse(studentId, newCourse);if (course == null)return ResponseEntity.noContent().build();URI location = ServletUriComponentsBuilder.fromCurrentRequest().path("/{id}").buildAndExpand(course.getId()).toUri();return ResponseEntity.created(location).build();}}

Src/main/java/com/in28minutes/springboot/model/Course. java

import java.util.List;public class Course {private String id;private String name;private String description;private List<String> steps;// Needed by Caused by: com.fasterxml.jackson.databind.JsonMappingException:// Can not construct instance of com.in28minutes.springboot.model.Course:// no suitable constructor found, can not deserialize from Object value// (missing default constructor or creator, or perhaps need to add/enable// type information?)public Course() {}public Course(String id, String name, String description, List<String> steps) {super();this.id = id;this.name = name;this.description = description;this.steps = steps;}public String getId() {return id;}public void setId(String id) {this.id = id;}public String getDescription() {return description;}public String getName() {return name;}public List<String> getSteps() {return steps;}@Overridepublic String toString() {return String.format("Course [id=%s, name=%s, description=%s, steps=%s]", id, name,description, steps);}@Overridepublic int hashCode() {final int prime = 31;int result = 1;result = prime * result + ((id == null) ? 0 : id.hashCode());return result;}@Overridepublic boolean equals(Object obj) {if (this == obj)return true;if (obj == null)return false;if (getClass() != obj.getClass())return false;Course other = (Course) obj;if (id == null) {if (other.id != null)return false;} else if (!id.equals(other.id))return false;return true;}}

Src/main/java/com/in28minutes/springboot/model/Student. java

package com.in28minutes.springboot.model;import java.util.List;public class Student {private String id;private String name;private String description;private List<Course> courses;public Student(String id, String name, String description,List<Course> courses) {super();this.id = id;this.name = name;this.description = description;this.courses = courses;}public String getId() {return id;}public void setId(String id) {this.id = id;}public String getName() {return name;}public void setName(String name) {this.name = name;}public String getDescription() {return description;}public void setDescription(String description) {this.description = description;}public List<Course> getCourses() {return courses;}public void setCourses(List<Course> courses) {this.courses = courses;}@Overridepublic String toString() {return String.format("Student [id=%s, name=%s, description=%s, courses=%s]", id,name, description, courses);}}

Src/main/java/com/in28minutes/springboot/service/StudentService. java

package com.in28minutes.springboot.service;import java.math.BigInteger;import java.security.SecureRandom;import java.util.ArrayList;import java.util.Arrays;import java.util.List;import org.springframework.stereotype.Component;import com.in28minutes.springboot.model.Course;import com.in28minutes.springboot.model.Student;@Componentpublic class StudentService {private static List<Student> students = new ArrayList<>();static {//Initialize DataCourse course1 = new Course("Course1", "Spring", "10 Steps", Arrays.asList("Learn Maven", "Import Project", "First Example","Second Example"));Course course2 = new Course("Course2", "Spring MVC", "10 Examples",Arrays.asList("Learn Maven", "Import Project", "First Example","Second Example"));Course course3 = new Course("Course3", "Spring Boot", "6K Students",Arrays.asList("Learn Maven", "Learn Spring","Learn Spring MVC", "First Example", "Second Example"));Course course4 = new Course("Course4", "Maven","Most popular maven course on internet!", Arrays.asList("Pom.xml", "Build Life Cycle", "Parent POM","Importing into Eclipse"));Student ranga = new Student("Student1", "Ranga Karanam","Hiker, Programmer and Architect", new ArrayList<>(Arrays.asList(course1, course2, course3, course4)));Student satish = new Student("Student2", "Satish T","Hiker, Programmer and Architect", new ArrayList<>(Arrays.asList(course1, course2, course3, course4)));students.add(ranga);students.add(satish);}public List<Student> retrieveAllStudents() {return students;}public Student retrieveStudent(String studentId) {for (Student student : students) {if (student.getId().equals(studentId)) {return student;}}return null;}public List<Course> retrieveCourses(String studentId) {Student student = retrieveStudent(studentId);if (student == null) {return null;}return student.getCourses();}public Course retrieveCourse(String studentId, String courseId) {Student student = retrieveStudent(studentId);if (student == null) {return null;}for (Course course : student.getCourses()) {if (course.getId().equals(courseId)) {return course;}}return null;}private SecureRandom random = new SecureRandom();public Course addCourse(String studentId, Course course) {Student student = retrieveStudent(studentId);if (student == null) {return null;}String randomId = new BigInteger(130, random).toString(32);course.setId(randomId);student.getCourses().add(course);return course;}}

Src/main/java/com/in28minutes/springboot/StudentServicesApplication. java

package com.in28minutes.springboot;import org.springframework.boot.SpringApplication;import org.springframework.boot.autoconfigure.SpringBootApplication;@SpringBootApplicationpublic class StudentServicesApplication {public static void main(String[] args) {SpringApplication.run(StudentServicesApplication.class, args);}}

The above is all the content of this article. I hope it will be helpful for your learning and support for helping customers.

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.