Reading:
Creating a REST API in Spring Boot with Maven

Creating a REST API in Spring Boot with Maven

Metamug
Creating a REST API in Spring Boot with Maven

Spring Boot provides an excellent platform to build RESTful APIs quickly. In this article, we'll create a REST API step-by-step.

Table of Contents

  1. Prerequisites
  2. Maven Project Setup
  3. Initializing the Project
  4. Project Structure
  5. Creating the Model
  6. Creating the Repository
  7. Creating the Service
  8. Creating the Controller
  9. Testing the API
  10. Additional RESTful Operations

Prerequisites

  • Java JDK 8 or higher
  • Maven installed
  • An IDE like IntelliJ or Eclipse

Maven Project Setup

pom.xml

Create a pom.xml file and add the following dependencies:

<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0"
         xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
    <modelVersion>4.0.0</modelVersion>

    <groupId>com.example</groupId>
    <artifactId>spring-boot-rest-api</artifactId>
    <version>1.0-SNAPSHOT</version>

    <parent>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-parent</artifactId>
        <version>2.5.4</version>
    </parent>

    <dependencies>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-web</artifactId>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-data-jpa</artifactId>
        </dependency>
        <dependency>
            <groupId>com.h2database</groupId>
            <artifactId>h2</artifactId>
            <scope>runtime</scope>
        </dependency>
    </dependencies>
</project>

Run mvn clean install to download the dependencies.


Initializing the Project

Initialize your Spring Boot project through your IDE or by using the Spring Initializr website.


Project Structure

Your project structure should look like this:

src/
├── main/
│   ├── java/
│   │   └── com/
│   │       └── example/
│   │           └── demo/
│   │               └── DemoApplication.java
│   ├── resources/
│   │   └── application.properties
├── test/

Creating the Model

Create a model named Employee.

package com.example.demo.model;

import javax.persistence.Entity;
import javax.persistence.Id;

@Entity
public class Employee {

    @Id
    private int id;
    private String name;

    // Getters and Setters
}

Creating the Repository

Create an interface named EmployeeRepository.

package com.example.demo.repository;

import com.example.demo.model.Employee;
import org.springframework.data.jpa.repository.JpaRepository;

public interface EmployeeRepository extends JpaRepository<Employee, Integer> {
}

Creating the Service

Create a service class named EmployeeService.

package com.example.demo.service;

import com.example.demo.model.Employee;
import com.example.demo.repository.EmployeeRepository;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.Optional;

@Service
public class EmployeeService {

    @Autowired
    private EmployeeRepository repository;

    public List<Employee> getEmployees() {
        return repository.findAll();
    }

    public Optional<Employee> getEmployeeById(int id) {
        return repository.findById(id);
    }

    public Employee addEmployee(Employee employee) {
        return repository.save(employee);
    }
}

Creating the Controller

Create a controller named EmployeeController.

package com.example.demo.controller;

import com.example.demo.model.Employee;
import com.example.demo.service.EmployeeService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.List;
import java.util.Optional;

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

    @Autowired
    private EmployeeService service;

    @GetMapping
    public List<Employee> getAllEmployees() {
        return service.getEmployees();
    }

    @GetMapping("/{id}")
    public Optional<Employee> getEmployeeById(@PathVariable int id) {
        return service.getEmployeeById(id);
    }

    @PostMapping
    public Employee addEmployee(@RequestBody Employee employee) {
        return service.addEmployee(employee);
    }
}

Testing the API

You can now test your API using Postman or curl commands.


Additional REST

ful Operations

Collection GET Request

Fetch all employees:

curl http://localhost:8080/api/employees

Item GET Request

Fetch a single employee:

curl http://localhost:8080/api/employees/1

POST Request

Add a new employee:

curl -X POST -H "Content-Type: application/json" -d '{"id": 3, "name": "Emily"}' http://localhost:8080/api/employees

I hope this comprehensive guide helps you build a REST API using Spring Boot and Maven. Feel free to ask if you have any further questions in comments.



Icon For Arrow-up
Comments

Post a comment