Explore Topics

REST APIs with Spring Boot

Spring Boot simplifies the process of building Java-based RESTful APIs with minimal configuration.

Create a Spring Boot Project in IntelliJ

  • Open IntelliJ IDEA and click on New Project.
  • Select Spring Initializr on the left panel. This option allows you to generate a Spring Boot project with necessary dependencies.
  • Choose Project SDK: Ensure that you have JDK 8 or higher installed.
  • Set Group and Artifact: This defines your project’s package and name. For example:
    • Group: com.example
    • Artifact: springboot-rest-api
  • In the Dependencies section, search for and add:
    • Spring Web (for REST API development)
    • Spring Boot DevTools (optional, for automatic restarts during development)
  • Click Next and then Finish. IntelliJ IDEA will automatically create and import the project.

Set Up REST Controller

Now that you have a Spring Boot project, let’s create a simple REST controller.

  • Navigate to the src/main/java directory of your project and create a package (e.g:com.example.springbootrestapi).

Inside the package, create a new class called HelloController.

  • @RestController: Tells Spring that this class will handle RESTful requests.
  • @GetMapping: Maps the /hello endpoint to the sayHello method, which returns a simple text message.

Run Your Application

  • Run the Application: In IntelliJ, find the class containing your main() method, typically named SpringbootRestApiApplication.java. This file is created automatically with the project.
    • @SpringBootApplication: This annotation marks the main class of the Spring Boot application and enables automatic configuration, component scanning, and more.
  • Right-click the file and select Run ‘SpringbootRestApiApplication’. IntelliJ will start your Spring Boot application.

Test Your REST API

Once your application is running, you can test it in several ways:

  • Browser: Open your browser and go to http://localhost:8080/hello. You should see “Hello, World!” as the response.
  • Postman: Use Postman or another API testing tool to send a GET request to http://localhost:8080/hello.

Handling Request Parameters

Spring Boot makes it easy to handle query parameters and path variables.

  • Request Parameter Example: Update your HelloController to accept a query parameter:

    • Test by navigating to http://localhost:8080/greet?name=John.
  • Path Variable Example: Modify the HelloController to handle path variables:

    • Test by navigating to http://localhost:8080/greet/John.

Returning JSON Responses

Spring Boot automatically converts Java objects into JSON. For example:

When you access http://localhost:8080/user, you’ll see a JSON response: