Featured Article

Master Java Spring Boot Tutorial: Build REST API Like a Pro

Kenneth Jul 13, 2026

Welcome to this comprehensive guide on Java Spring Boot tutorial focusing on REST APIs. Spring Boot is a powerful framework for building web services, and by the end of this tutorial, you'll have a solid understanding of how to create RESTful APIs using Spring Boot.

How To Develop REST API Using Spring Boot ?
How To Develop REST API Using Spring Boot ?

Whether you're a seasoned Java developer looking to expand your skills or a beginner eager to learn Spring Boot, this tutorial caters to all levels. So, buckle up as we dive into the world of Java Spring Boot and REST APIs!

Spring boot
Spring boot

Getting Started with Spring Boot

Before we delve into REST API development, let's ensure we have the right tools and setup. Spring Boot offers an easy way to start, with its embedded server and minimal configuration.

Building your first REST API: Java and Spring Boot
Building your first REST API: Java and Spring Boot

The first step is to install the Spring Tool Suite (STS), an intuitive development environment for Spring-based applications. Once installed, create a new Spring Boot project with the 'Spring Web' dependency, which includes REST support.

Project Structure and Dependencies

WebClient In Spring Boot
WebClient In Spring Boot

The generated project structure follows the standard Maven or Gradle format. The main dependencies include the Spring Boot starter web, along with other modules needed for RESTful services like Jackson for JSON processing.

Running the Spring Boot Application

With the project set up, let's run our application. Using STS, simply right-click on the main application class and select 'Run As' -> 'Java Application'. Alternatively, you can use your preferred IDE's run configuration or command-line build tools like Maven or Gradle.

Spring Boot Application Properties Example - Java Code Geeks
Spring Boot Application Properties Example - Java Code Geeks

The application will start on a default port (usually 8080). To verify, open your browser and navigate to http://localhost:8080/. You should see a message indicating the application is running, such as "Whitelabel Error Page".

Creating a REST API with Spring Boot

Now that we have our Spring Boot project set up, it's time to create our first REST API. We'll start with a simple 'Hello, World!' example and then move on to more complex scenarios.

Tutorial of Building Java REST API using Spring Boot and MongoDB – Djamware
Tutorial of Building Java REST API using Spring Boot and MongoDB – Djamware

To create a REST API, we need to add controllers that handle HTTP requests and respond with suitable data. Spring Boot uses annotations like @RestController and @RequestMapping to map HTTP methods to specific endpoints.

Creating a Basic REST API

Spring Boot Real-Time Project
Spring Boot Real-Time Project
Spring Boot Project Structure for Clean & Scalable Code | Raghvendra Pratap posted on the topic | LinkedIn
Spring Boot Project Structure for Clean & Scalable Code | Raghvendra Pratap posted on the topic | LinkedIn
How to Structure a Scalable Spring Boot Application | Ritesh Kumar Gupta posted on the topic | LinkedIn
How to Structure a Scalable Spring Boot Application | Ritesh Kumar Gupta posted on the topic | LinkedIn
Spring Boot, MySQL, JPA, Hibernate Restful CRUD API Tutorial
Spring Boot, MySQL, JPA, Hibernate Restful CRUD API Tutorial
How To Handle Exceptions & Errors In Spring Boot?
How To Handle Exceptions & Errors In Spring Boot?
Spring Boot Tutorial: Build an MVC Java Web App using Netbeans – Djamware
Spring Boot Tutorial: Build an MVC Java Web App using Netbeans – Djamware
Spring Boot CRUD and JPA: Your Ultimate Book Example Guide
Spring Boot CRUD and JPA: Your Ultimate Book Example Guide
Difference between application.properties vs Application.json vs Application.yml in Spring Boot
Difference between application.properties vs Application.json vs Application.yml in Spring Boot
Spring Boot With JSP and Spring MVC | Java Inspires
Spring Boot With JSP and Spring MVC | Java Inspires

Let's begin by creating a simple REST API that responds with "Hello, World!" when accessed. Create a new class named HelloWorldController and add the following code:

```java @RestController public class HelloWorldController { @GetMapping("/hello-world") public String helloWorld() { return "Hello, World!"; } } ```

The @RestController annotation indicates that this class is a REST controller, and the @GetMapping annotation maps the HTTP GET request to the helloWorld method. When you access http://localhost:8080/hello-world in your browser, you should see the message "Hello, World!".

Building a RESTful API with CRUD Operations

Now that we have a basic API, let's create a more complex REST API with CRUD (Create, Read, Update, Delete) operations. Suppose we have a simple 'User' entity with fields like id, name, and email.

First, create a 'User' class with appropriate annotations like @Entity and @Table. Then, use Spring Data JPA to create a 'UserRepository' interface that extends JpaRepository. This interface provides basic CRUD functionality out of the box.

Next, create a 'UserController' with methods annotated with @PostMapping for creation, @GetMapping for reading, @PutMapping for updating, and @DeleteMapping for deleting users.

Here's an example of what the UserController might look like:

```java @RestController @RequestMapping("/api/users") public class UserController { @Autowired private UserRepository userRepository; @PostMapping public User createUser(@RequestBody User user) { // Perform validations, if needed return userRepository.save(user); } // Implement other CRUD methods here @GetMapping("/{id}") public User getUserById(@PathVariable Long id) { return userRepository.findById(id).orElseThrow(NotFoundException::new); } // Implement other CRUD methods here } ```

You can test this API using tools like Postman or curl. For example, to create a new user, send a POST request to http://localhost:8080/api/users with a JSON payload like:

```json { "name": "John Doe", "email": "john.doe@example.com" } ```

Spring Boot will automatically parse the JSON and map it to the 'User' object. The created user will be stored in your database, and you can retrieve it using the generated ID.

Exception Handling and Validation

In a real-world application, handling exceptions and validating input is crucial. Spring Boot provides mechanisms to handle exceptions globally and validate user input using Bean Validation.

To handle exceptions, create a custom exception class (e.g., RestException) and define an adviced exception handler (e.g., RestExceptionHandler) that uses the @ExceptionHandler annotation to catch and handle specific exceptions.

Global Exception Handling

To handle exceptions globally, create an adviced exception handler with the @ControllerAdvice annotation. This allows you to handle exceptions across the entire application. Here's an example:

```java @ControllerAdvice public class GlobalExceptionHandler { @ExceptionHandler(NotFoundException.class) @ResponseStatus(HttpStatus.NOT_FOUND) public ResponseEntity handleNotFoundException(NotFoundException ex) { return new ResponseEntity<>("Resource not found", HttpStatus.NOT_FOUND); } // Implement other exception handling methods here } ```

In this example, any NotFoundException thrown within the application will be caught and responded with a 404 Not Found status.

Input Validation with Bean Validation

Spring Boot integrates with Bean Validation (JSR-303), allowing you to validate user input using annotations like @NotNull, @Size, and @Email. Add these annotations to the 'User' entity's fields to enforce validation rules.

When creating or updating a user, if validation fails, Spring Boot will return a 400 Bad Request status with a list of validation errors. You can handle and respond to these errors in your exception handler.

Securing REST API with Spring Security

To secure your REST API, you can use Spring Security to add authentication and authorization layers. Spring Security provides a set of features like securing endpoints, user role-based access control, and token-based authentication, among others.

Let's configure basic authentication for our REST API. First, add the 'Spring Security' dependency to your project. Then, create a security configuration class (e.g., SecurityConfig) and enable basic authentication using the HttpSecurity class.

Configuring Spring Security

Here's an example of a security configuration class that enables basic authentication:

```java @Configuration @EnableWebSecurity public class SecurityConfig extends WebSecurityConfigurerAdapter { @Override protected void configure(HttpSecurity http) throws Exception { http.authorizeRequests() .antMatchers("/api/users").hasRole("ADMIN") .anyRequest().authenticated() .and() .httpBasic(); } @Autowired public void configureGlobal(AuthenticationManagerBuilder auth) throws Exception { auth.inMemoryAuthentication() .withUser("admin").password("{noop}admin").roles("ADMIN"); } } ```

In this example, we've secured the '/api/users' endpoint, requiring users to have the 'ADMIN' role to access it. The withUser method in the AuthenticationManagerBuilder class configures a test user with the username 'admin' and password 'admin'.

Testing Authentication

To test basic authentication, use tools like Postman or curl to send authenticated requests. You'll need to include the 'Authorization' header with a 'Basic' scheme and the encoded username and password, like this:

```bash curl -X GET -H "Authorization: Basic YWRtaW46YWRtaW4=" http://localhost:8080/api/users ```

Replace 'YWRtaW46YWRtaW4=' with the Base64-encoded value of your username and password (e.g., 'admin:admin'). If the authentication is successful, Spring Security will grant access to the protected resource; otherwise, it will return a 401 Unauthorized status.

Our journey through Java Spring Boot and REST APIs comes to an end. You've now learned how to create, secure, and manage RESTful APIs using Spring Boot. With this knowledge, you're well-equipped to build powerful web services in your applications.

Happy coding, and remember to explore the endless possibilities of Spring Boot by experimenting with its countless features and integrations!