Building Your First REST API in Spring Boot

Spring Boot offers a powerful and minimalistic way to build modern REST APIs in Java. Whether you’re just getting started with backend development or coming from a different stack, Spring Boot simplifies a lot of the boilerplate code.

In this guide, you’ll learn how to create First REST API in Spring Boot :

  • Set up a Spring Boot project
  • Create a simple RESTful controller
  • Handle basic CRUD operations (GET, POST, PUT, DELETE)
  • Test the API using Postman or curl

Let’s begin! πŸš€

Building Your First REST API in Spring Boot

βœ… What is a REST API?

REST (Representational State Transfer) is an architectural style that uses standard HTTP methods like:

  • GET β€” retrieve data
  • POST β€” create new data
  • PUT β€” update existing data
  • DELETE β€” remove data

Spring Boot makes it easy to implement these with annotations like @RestController, @GetMapping, @PostMapping, etc.

βš™οΈ Step 1: Project Setup Using Spring Initializr

Go to https://start.spring.io and configure:

  • Project: Maven
  • Language: Java
  • Spring Boot: Latest stable version
  • Group: com.kscodes.springboot
  • Artifact: firstapp
  • Dependencies:

Click Generate, unzip the file, and open the project in your IDE (IntelliJ or Eclipse).

πŸ—‚οΈ Step 2: Project Structure



src/
└── main/
    β”œβ”€β”€ java/
    β”‚   └── com/kscodes/springboot/firstapp/
    β”‚       β”œβ”€β”€ FirstAppApplication.java
    β”‚       β”œβ”€β”€ controller/
    β”‚       β”œβ”€β”€ model/
    β”‚       └── service/ (optional for future enhancements)
    └── resources/
        └── application.properties

πŸ“¦ Step 3: Create the User Model



package com.kscodes.springboot.firstapp.model;

public class User {
    private Long id;
    private String name;
    private String email;

    public User() {}

    public User(Long id, String name, String email) {
        this.id = id;
        this.name = name;
        this.email = email;
    }

    public Long getId() { return id; }
    public void setId(Long id) { this.id = id; }

    public String getName() { return name; }
    public void setName(String name) { this.name = name; }

    public String getEmail() { return email; }
    public void setEmail(String email) { this.email = email; }
}

πŸ”§ Step 4: Create the User Controller


package com.kscodes.springboot.firstapp.controller;
import com.kscodes.springboot.firstapp.model.User;
import org.springframework.web.bind.annotation.*;
import java.util.*;
@RestController
@RequestMapping("/api/users")
public class UserController {
    private Map users = new HashMap<>();
    private Long idCounter = 1L;
    // GET all users
    @GetMapping
    public List getAllUsers() {
        return new ArrayList<>(users.values());
    }
    // GET user by ID
    @GetMapping("/{id}")
    public User getUserById(@PathVariable Long id) {
        return users.get(id);
    }
    // POST new user
    @PostMapping
    public User createUser(@RequestBody User user) {
        user.setId(idCounter++);
        users.put(user.getId(), user);
        return user;
    }
    // PUT update user
    @PutMapping("/{id}")
    public User updateUser(@PathVariable Long id, @RequestBody User updatedUser) {
        User existing = users.get(id);
        if (existing != null) {
            existing.setName(updatedUser.getName());
            existing.setEmail(updatedUser.getEmail());
        }
        return existing;
    }
    // DELETE user
    @DeleteMapping("/{id}")
    public String deleteUser(@PathVariable Long id) {
        users.remove(id);
        return "User with ID " + id + " deleted.";
    }
}

▢️ Step 5: Run the Application

Run the main class:



package com.kscodes.springboot.firstapp;

import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;

@SpringBootApplication
public class FirstAppApplication {
    public static void main(String[] args) {
        SpringApplication.run(FirstAppApplication.class, args);
    }
}

πŸ§ͺ Step 6: Test the API

You can test the API using Postman, curl, or any HTTP client.

πŸ”Ή Get All Users



GET http://localhost:8080/api/users

πŸ”Ή Create a User


POST http://localhost:8080/api/users
Content-Type: application/json

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


πŸ”Ή Get User by ID



GET http://localhost:8080/api/users/1

πŸ”Ή Update a User



PUT http://localhost:8080/api/users/1
Content-Type: application/json

{
  "name": "John S Doe",
  "email": "new@example.com"
}


πŸ”Ή Delete a User



DELETE http://localhost:8080/api/users/1

βœ… Summary

You’ve successfully created your First REST API in Spring Boot that:

  • Uses an in-memory map for storing users
  • Supports full CRUD operations
  • Can be extended to use databases or services in the future