Java Spring Boot Rest Example
In this tutorial, we will build a simple Rest Web Service with Spring Boot.
1. Project Init
a) With Spring Tool Suite or Spring Tools in Eclipse
New Spring Starter Project
Project Configuration Wizard
Select Web Starter
b) Using Spring Initializr
Generate your project using Spring Initializr
Add Web Dependancy
2. Create Resource Model
Create a Java class to represent the model. Spring (using Jackson library) will marshall instances of our class in JSON.
1 2 3 4 5 6 7 8 9 10 11 |
package com.mindsit.hello; public class Person { public String name; public Person(String name) { this.name = name; } } |
Jackson will detect public fields, so it’s optional to write private fields with accessors in this case.
3. Create Controller
Create a controller (@RestController annotation) and a method to handle the request.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 |
package com.mindsit.hello; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestParam; import org.springframework.web.bind.annotation.RestController; @RestController public class HelloController { @RequestMapping("/hello") public Person buildPerson(@RequestParam String name) { return new Person(name); } } |
The @RequestMapping annotation makes the mapping between the path (“/hello”) and the method.
The @RequestParam specifies a request parameter (“name”).
4. Run the App
a) With Spring Tools
Run Project As – Spring Boot App
Tip : How to Change the Port
b) With Maven
Run maven target : spring-boot:run
5. Consume the service
a) Test in browser
Go to http://localhost:8080/hello?name=xavier
The output should be :
1 |
{"name":"xavier"} |
b) Test in Java
See : Call a Rest Web Service in Java
c) Test in Javascript
See : Call a Rest Web Service in Javascript
Useful Links
Official Getting Started Guide
Xavier is a Freelance Innovation Solutions Architect and Technical Advisor. He has been working for 10 years in software development (Java, JEE, JavaScript, Angular, Node JS, React), and has solid experience as a Tech Lead and Technical Architect in different company sizes (Startup, SME, Large Enterprise), and in different sectors (Insurance, Risk Insurance, Transportation, Energy Management, Mobile Operator)
I am in fact grateful to the holder of this web site who has shared this
great article at at this time.