Developing REST APIs with Modern Java Technologies
Using Spring Initializr, we choose latest of spring and java 22. Added three dependencies: Spring Web, Spring Data JPA, H2 Database.
Spring Web streamlines REST API creation by providing key controller support for defining endpoints, handling requests, and managing data serialization/deserialization. It supports multiple data formats and media types (e.g., JSON/XML), allowing clients to receive responses in their preferred format.
Spring Data JPA simplifies database interactions by providing high-level repository abstractions and automatic query generation. It streamlines entity management.
H2 Database serves as an in-memory or embedded database for testing and development in a Spring Boot REST API app, offering a lightweight, fast, and easily configurable data storage solution.
Spring Security provides robust authentication and authorization mechanisms for securing REST APIs in a Spring Boot application. It manages access control, protects endpoints, and integrates with various authentication providers and methods.
Create REST Controller
Now that the project is set up, let’s start with building the API. You will need a simple REST Controller, to handle the http requests.
Create a Java class named ApiController
in the package com.example.demo.controller
and add the following code to your REST Controller.
package com.example.demo.controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
@RestController
@RequestMapping("/api/hello")
public class ApiController {
@GetMapping
public String sayHello() {
return "Hello, World!";
}
}
Here, the class ApiController
is a REST Controller annotated with @RestController
, which handles the http requests. The @RequestMapping
specifies the base path for all APIs defined in this controller. In this case, the base path is /api/hello
.
Inside the ApiController
, is the sayHello()
method returning a string. Notice the @GetMapping
annotation, this denotes that the sayHello()
method shall handle the GET requests to the base path /api/hello
and return string "Hello, World!"
.
Run the application
Now that your code is ready, it’s time to run the application and test your API. Locate the the main class i.e. class containing the main()
method.
In this case, it would be the DemoApplication
class (usually located in the com.example.demo
package). Now right click and run the application.
Once the application is running, let’s test the API. Open your web browser and navigate to http://localhost:8080/api/hello
. You should see the message "Hello, World!"
displayed in the browser.
Congratulations!! You have successfully built your first REST API using Java & Spring boot.