Build A Simple REST API With Spring
To get our project up and running, we use Spring Initializr.
Initializr generates spring boot project with just what you need to start quickly.
We can leave the settings for the project, Language and Spring Boot version as the default.
We search for dependencies to add and select the Spring Web dependency. That is the only dependency we need for this task.
The generate button on the bottom left is then clicked to download the project.
You open the project with your IDE (I use IntelliJIDEA) and allow the dependencies to be downloaded.
The starter code with the main method would resemble that below:
@SpringBootApplication
public class SpringrestApplication {
public static void main(String[] args) {
SpringApplication.run(SpringrestApplication.class, args);
}
}
Run the application, open your browser and navigate to localhost:8080 (it runs on port 8080 by default)
You might encounter an error page, don't panic:
Spring uses a default Whitelabel error page in case of a server error. Currently, there is not code logic to handle the "localhost:8080/" request.
We would create a Controller class to handle the "/" root path. Make sure to annotate the class with the @RestController annotation.
@RestController
public class Controller {
@GetMapping("/")
public String home() {
return "Hello";
}
@GetMapping("/{name}")
public String hello(@PathVariable String name) {
return "Hello " + name;
}
}
Let's navigate to localhost:8080 again
The @GetMapping("/{name}") allows for Path Variables, so let's say we navigate to http://localhost:8080/Lemuel
We get:
We have just brushed through the basics.
You can watch the 10 minutes in-depth tutorial below about building REST API's with Spring. In the Tutorial below you would be shown other functions you can perform in Spring and access to download the source code.
Lemuel, thanks for sharing!