DEV Community

Cover image for How to Build a REST API Using Spring Boot: A Beginner-Friendly Guide
Tech Of Town
Tech Of Town

Posted on

How to Build a REST API Using Spring Boot: A Beginner-Friendly Guide

Backend development is one of the most important skills for becoming a software developer.

Almost every modern application needs a backend to handle business logic, manage data, authenticate users and communicate with other services.

One of the most popular Java technologies for building backend applications is Spring Boot.

In this tutorial, we'll understand how REST APIs work and build a simple Employee Management API using Spring Boot.

1. What Is a REST API?

REST stands for Representational State Transfer.

A REST API allows different applications to communicate over HTTP.

For example, imagine an employee management application.

The frontend might be built using React, while the backend uses Spring Boot.

When a user wants to view employees, React sends an HTTP request to the backend. Spring Boot processes the request and returns the response, usually in JSON format.

Common HTTP methods include:

  • GET: Retrieve data.
  • POST: Create new data.
  • PUT: Update existing data.
  • PATCH: Partially update data.
  • DELETE: Remove data.

2. Create a Spring Boot Project

Start by creating a project using Spring Initializr.

Website: https://start.spring.io/

Choose the following configuration:

  • Project: Maven
  • Language: Java
  • Packaging: Jar
  • Java: 21

Add these dependencies:

  • Spring Web
  • Spring Boot DevTools

Generate the project and open it in your preferred IDE.

3. Create an Employee Model

First, create a Java class called Employee.

public class Employee {

    private Long id;
    private String name;
    private String email;
    private String department;

    public Employee() {
    }

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

    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;
    }

    public String getDepartment() {
        return department;
    }

    public void setDepartment(String department) {
        this.department = department;
    }
}
Enter fullscreen mode Exit fullscreen mode

This class represents the employee data that our API will manage.

For this beginner example, we'll temporarily store data in memory instead of connecting a database.

4. Create a REST Controller

Create a class called EmployeeController.

import org.springframework.web.bind.annotation.*;
import java.util.*;

@RestController
@RequestMapping("/api/employees")
public class EmployeeController {

    private final List<Employee> employees =
            new ArrayList<>();

    private Long nextId = 1L;

    @GetMapping
    public List<Employee> getEmployees() {
        return employees;
    }

    @PostMapping
    public Employee createEmployee(
            @RequestBody Employee employee) {

        employee.setId(nextId++);
        employees.add(employee);

        return employee;
    }

    @GetMapping("/{id}")
    public Employee getEmployee(@PathVariable Long id) {
        return employees.stream()
                .filter(emp -> emp.getId().equals(id))
                .findFirst()
                .orElseThrow(() ->
                    new RuntimeException("Employee not found"));
    }

    @DeleteMapping("/{id}")
    public String deleteEmployee(@PathVariable Long id) {

        boolean removed = employees.removeIf(
                emp -> emp.getId().equals(id)
        );

        if (!removed) {
            throw new RuntimeException("Employee not found");
        }

        return "Employee deleted successfully";
    }
}
Enter fullscreen mode Exit fullscreen mode

Let's understand some important annotations:

@RestController

Tells Spring Boot that this class handles REST API requests and returns response data.

@RequestMapping

Defines the common URL path for the controller.

@GetMapping

Handles HTTP GET requests.

@PostMapping

Handles HTTP POST requests.

@RequestBody

Converts incoming JSON request data into a Java object.

@PathVariable

Extracts a value from the URL.

5. Test Your REST API

Start your Spring Boot application.

By default, it runs on port 8080.

You can test the endpoints using Postman or curl.

Create an employee

POST:

http://localhost:8080/api/employees
Enter fullscreen mode Exit fullscreen mode

JSON request:

{
  "name": "Prasanth",
  "email": "prasanth@example.com",
  "department": "Engineering"
}
Enter fullscreen mode Exit fullscreen mode

Get all employees

GET:

http://localhost:8080/api/employees
Enter fullscreen mode Exit fullscreen mode

Get one employee

GET:

http://localhost:8080/api/employees/1
Enter fullscreen mode Exit fullscreen mode

Delete an employee

DELETE:

http://localhost:8080/api/employees/1
Enter fullscreen mode Exit fullscreen mode

Congratulations! You've created your first basic Employee Management REST API using Spring Boot.

6. What Should You Learn Next?

This example uses an in-memory list to keep the code simple.

A production-ready application needs much more.

Continue learning:

  1. Spring Data JPA and Hibernate.
  2. PostgreSQL or MySQL integration.
  3. DTOs and validation.
  4. Global exception handling.
  5. Spring Security and JWT authentication.
  6. Unit testing with JUnit and Mockito.
  7. API documentation using Swagger.
  8. Docker and application deployment.

Try extending this project by adding employee updates, database persistence, authentication and pagination.

Final Thoughts

Learning Spring Boot is not just about understanding annotations. It's about understanding how backend applications are designed, developed, tested and deployed.

Start with small APIs, understand the request-response lifecycle, and gradually build complete applications.

At Tech Of Town, we believe the best way to learn software development is by writing code, solving problems and building real-world projects.

Our goal is to help students and aspiring developers develop practical skills and become confident software engineers.

Learn the tech. Build the career.

Explore more programming and software engineering resources:

Website: https://techoftown.com/

Instagram: https://www.instagram.com/techoftown_/

Top comments (0)