Explore Topics

REST APIs using Spring Boot

Spring Boot makes it super simple to create RESTful APIs quickly with minimal configuration. Let’s break it down step by step:

REST API

A REST API is a web service that follows REST principles and allows clients (like browsers or mobile apps) to perform operations (like GET, POST, PUT, DELETE) on resources via HTTP.

Why Spring Boot

  • Auto-configuration: Spring Boot reduces boilerplate setup.
  • Embedded server: Comes with Tomcat/Jetty, no need to deploy WAR files.
  • Production-ready: Has built-in monitoring and configuration support.

Basic Steps to Build a REST API

Create a Spring Boot project

  • Open IntelliJ IDEA.
  • Go to File → New → Project.
  • Select Spring Initializr.
  • Fill in:
    • Group: com.example
    • Artifact: restapi
  • Add dependencies:
    • Spring Web
    • (Optional) Spring Boot DevTools
  • Click Finish to generate your project.

Create a Model Class

Create a simple model class inside the model package:

Build the REST Controller

Create a controller class inside the controller package:

  • @RestController: Combines @Controller + @ResponseBody.
  • @GetMapping, @PostMapping: Map HTTP methods (GET, POST) to Java methods.
  • @RequestBody: Binds JSON payload from the request to a Java object.

Run the Application

  • Right-click the main RestapiApplication.java class.
  • Click Run ‘RestapiApplication.main()’.
  • Open your browser or use Postman:
    • GET http://localhost:8080/api/employees
    • POST http://localhost:8080/api/employees with JSON body like: