In Spring Boot, you can create RESTful APIs using the Spring Web module, which provides convenient annotations and classes for building RESTful endpoints. Here’s a step-by-step guide to creating a REST API in Spring Boot:
1. Set up a new Spring Boot project or use an existing one. You can use Spring Initializr (https://start.spring.io/) to generate a basic project structure with the required dependencies.
2. Create a new Java class for your REST controller. This class will handle incoming HTTP requests and define the API endpoints. Annotate the class with `@RestController` to indicate that it’s a REST controller.
“`java@RestControllerpublic class MyRestController { // API endpoints will be defined here}“`
3. Define your API endpoints as methods within the controller class. Use appropriate annotations to specify the HTTP method (`@GetMapping`, `@PostMapping`, `@PutMapping`, `@DeleteMapping`, etc.) and the URL path for each endpoint.
“`java@RestControllerpublic class MyRestController { @GetMapping(“/api/greeting”) public String getGreeting() { return “Hello, World!”; } @PostMapping(“/api/user”) public User createUser(@RequestBody User user) { // Process the user object and return a response }}“`
4. In the example above, the `getGreeting()` method handles GET requests to `/api/greeting` and returns a simple greeting string. The `createUser()` method handles POST requests to `/api/user`, expecting a JSON payload in the request body representing a `User` object. You can define your own custom classes like `User` to model the request and response payloads.
5. Within each endpoint method, you can implement the necessary business logic and return the desired response. The response can be a simple string, an object, or a collection of objects. Spring Boot automatically serializes objects to JSON (or XML) based on the request’s `Accept` header.
6. Run your Spring Boot application. By default, Spring Boot will start an embedded Tomcat server that listens for incoming HTTP requests.
7. You can now test your REST API endpoints using a tool like cURL, Postman, or any web browser. For example, to test the `getGreeting()` endpoint, open a browser and navigate to `http://localhost:8080/api/greeting`. You should see the “Hello, World!” message returned.That’s it! You’ve created a basic REST API using Spring Boot. You can add more endpoints, handle request parameters, implement data persistence, and perform other advanced operations as per your application’s requirements.