Spring Boot is a popular choice for building Web APIs in Java, offering a wide array of features that simplify development and enhance productivity. This comprehensive tutorial will guide you through the process of creating a Web API using Spring Boot, from setting up the project to testing your API endpoints.

Whether you're a seasoned Java developer or new to the Spring ecosystem, this tutorial will provide you with a solid foundation for building robust and scalable Web APIs. So, let's dive right in and start creating!

Setting Up Your Spring Boot Project
Before we dive into creating our API, we need to set up a new Spring Boot project. You can use the Spring Initializr, an online tool that generates a ready-to-use Spring Boot project with the dependencies you need.

For this tutorial, we'll add the following dependencies: Spring Web, Lombok, and OpenFeign. Spring Web allows us to create RESTful web services, Lombok simplifies our code by reducing boilerplate, and OpenFeign is a declarative HTTP client.
Maven or Gradle?

Spring Initializr allows you to choose between Maven and Gradle as your build tool. Both are capable and have their own strengths, but for this tutorial, we'll use Maven. Once you've generated your project, import it into your favorite IDE for a smooth development experience.
Now that our project is set up, let's create our first API endpoint.
Creating Your First API Endpoint

In Spring Boot, creating a REST controller is as simple as annotating a class with @RestController and defining API endpoints with the @GetMapping, @PostMapping, @PutMapping, and @DeleteMapping annotations. Let's create a simple "Hello, World!" API endpoint.
Create a new class called "HelloWorldController" under the "com.example.demo.controller" package and add the following code:
```java import org.springframework.web.bind.annotation.GetMapping; import org.springframework.web.bind.annotation.RestController; @RestController public class HelloWorldController { @GetMapping("/api/hello-world") public String sayHello() { return "Hello, World!"; } } ```
The @RestController annotation tells Spring that this class is a controller and to handle incoming HTTP requests. The @GetMapping annotation defines that the sayHello method should handle HTTP GET requests to the "/api/hello-world" path.

Handling HTTP Requests and Responses
Spring Boot makes it easy to handle various HTTP methods and return different types of responses. In this section, we'll explore how to handle different HTTP methods and return various data types from our API endpoints.









Let's extend our previous example to handle multiple HTTP methods and return different data types.
Handling Different HTTP Methods
To handle different HTTP methods, we can use the appropriate Spring annotations like @PostMapping, @PutMapping, and @DeleteMapping. Let's extend our "HelloWorldController" class to handle these methods:
```java import org.springframework.web.bind.annotation.*; @RestController public class HelloWorldController { @GetMapping("/api/hello-world") public String sayHello() { return "Hello, World!"; } @PostMapping("/api/hello-world") public String sayHelloPost(@RequestParam(value = "name", defaultValue = "World") String name) { return "Hello, " + name + "!"; } @PutMapping("/api/hello-world") public String sayHelloPut(@RequestParam(value = "name", defaultValue = "World") String name) { return "Hello, " + name + "!"; } @DeleteMapping("/api/hello-world") public String sayGoodbye(@RequestParam(value = "name", defaultValue = "World") String name) { return "Goodbye, " + name + "!"; } } ```
In this example, we've added POST, PUT, and DELETE methods that accept a "name" parameter and return a personalized greeting or farewell.
Now, let's explore how to return different data types from our API endpoints.
Returning Different Data Types
Spring Boot allows us to return various data types from our API endpoints, from simple strings to complex objects. Let's create a new class called "Greeting" under the "com.example.demo.model" package and define its properties:
```java import lombok.AllArgsConstructor; import lombok.Data; @Data @AllArgsConstructor public class Greeting { private final long id; private final String content; } ```
The Lombok annotations @Data and @AllArgsConstructor generate getters, setters, toString, hashCode, and equals methods automatically, reducing boilerplate code.
Now, let's create a new API endpoint that returns a Greeting object:
```java import org.springframework.web.bind.annotation.GetMapping; import org.springframework.web.bind.annotation.PathVariable; import org.springframework.web.bind.annotation.RestController; import java.util.concurrent.atomic.AtomicLong; @RestController public class GreetingController { private AtomicLong counter = new AtomicLong(); @GetMapping("/api/greeting") public Greeting sayHello(@RequestParam(value = "name", defaultValue = "World") String name) { return new Greeting(counter.incrementAndGet(), "Hello, " + name + "!"); } @GetMapping("/api/greeting/{name}") public Greeting sayHelloWithName(@PathVariable String name) { return new Greeting(counter.incrementAndGet(), "Hello, " + name + "!"); } } ```
In this example, we have two API endpoints that return a Greeting object. The first one accepts a "name" query parameter, and the second one accepts a "name" path variable.
With these examples, you now have a solid foundation for creating Web APIs with Spring Boot.
Testing Your API Endpoints
Testing our API endpoints is crucial to ensure they behave as expected. In this section, we'll explore how to test our API endpoints using Spring Boot's testing support and the popular Postman tool.
Before we dive into testing, make sure your API is running by starting your Spring Boot application and accessing http://localhost:8080/api/hello-world in your browser or using a tool like cURL.
Testing with Spring Boot
Spring Boot provides convenient testing support through its testing framework. To add testing dependencies to your project, update your Maven or Gradle configuration file to include the Spring Boot testing starter dependency:
```xml
Now, let's create a test class for our HelloWorldController. Create a new class called "HelloWorldControllerTest" under the "com.example.demo.controller" package and add the following code:
```java
import org.junit.jupiter.api.Test;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.boot.test.web.client.TestRestTemplate;
import org.springframework.http.HttpStatus;
import org.springframework.http.RequestEntity;
import org.springframework.http.ResponseEntity;
import static org.assertj.core.api.Assertions.assertThat;
@SpringBootTest(webEnvironment = SpringBootTest.WebEnvironment.RANDOM_PORT)
class HelloWorldControllerTest {
@Autowired
private TestRestTemplate restTemplate;
@Test
void testSayHello() {
ResponseEntity The @SpringBootTest annotation tells Spring Boot to load and initialize the application context for the test, and the webEnvironment attribute tells it to start a new instance of the application within the test.
The TestRestTemplate class is a الحضارة Spring HTTP client that simplifies testing of HTTP services. In this example, we're making a GET request to "/api/hello-world" and asserting that the response has a status code of 200 OK and a body containing "Hello, World!".
Now that we've covered testing with Spring Boot, let's explore testing our API endpoints using the Postman tool.
Testing with Postman
Postman is a popular API testing tool that allows us to send HTTP requests and view the response data. To test our API endpoints with Postman, follow these steps:
- Start your Spring Boot application and open Postman.
- Enter http://localhost:8080/api/hello-world in the address bar and send a GET request. You should see the response containing "Hello, World!".
- To test the other HTTP methods, add the appropriate HTTP verb prefix (GET, POST, PUT, or DELETE) and send the request with the desired parameters.
- You can also use Postman to test the GreetingController API endpoints and verify that the response data matches your expectations.
Congratulations! You now have a solid understanding of creating and testing Web APIs with Spring Boot. You can use this knowledge to build robust and scalable APIs for your applications.
As a next step, consider exploring more advanced topics like API security, handling errors, and implementing pagination and sorting for your API responses. Happy coding!