Building RESTful APIs with Spring Boot: A Step-by-Step Guide to Custom Software Development
Learn to build RESTful APIs with Spring Boot in this comprehensive step-by-step guide for effective custom software development. Master Spring Boot today!
![](https://res.cloudinary.com/jerrick/image/upload/d_642250b563292b35f27461a7.png,f_jpg,fl_progressive,q_auto,w_1024/665f0fef89c048001d3d7e3c.jpg)
Web services depend on APIs, and effective ones are key ingredients for creating connected applications. RESTful APIs have emerged as the backbone of modern web applications. Its architectural principles ensure efficient and scalable communication between applications.
Spring Boot is a popular Java framework that streamlines the custom software development process for these APIs. Thus, a top software development company must leverage RESTful APIs. This guide discusses a step-by-step process of building RESTful APIs with Spring Boot.
What are RESTful APIs?
RESTful APIs are architectural-style APIs that leverage HTTP methods (GET, POST, PUT, DELETE) to interact with resources (data) on a server. They focus on stateless communication and use JSON or XML for data exchange.
Leveraging Spring Boot to build RESTful APIs in Custom Software Development
Reliable custom software development services leverage Spring Boot to build RESTful APIs. Here’s a guide:
Step 1: Set Up Development Environment
Construct a development environment conducive to Spring Boot API creation. Prerequisite software includes:
Java Development Kit (JDK):
This runtime environment executes Java bytecode, which is essential for running Spring Boot applications. Download and install a recent JDK version from the official Oracle website.
Integrated Development Environment (IDE):
Enhance your development experience with an IDE like IntelliJ IDEA or Eclipse. These offer code completion, debugging tools, and project management functionalities to streamline the development process.
PostgreSQL server:
For persistence, leverage a relational database management system (RDBMS) like PostgreSQL Server. This will store and manage data accessed by your RESTful API. Ensure the PostgreSQL version aligns with the Spring Data JPA dependency you'll utilize later.
Step 2: Create a Spring Boot Project
The first step in building RESTful APIs with Spring Boot is to create a new Boot project using the Spring Initializr. Open any web browser and go to Spring Initializr.
Project Metadata:
Set the following options:
Project: Gradle Project or Maven Project (preference-specific)
Language: Java
Spring Boot: The latest version, such as 3.0.2
Group: com.example
Artifact: custom-software-API (or any preferred information)
Name: Custom Software API (or any preferred name)
Description: Custom Software API project for Spring Boot
Packaging: Jar
Java: 11
Now, click on “Add Dependencies” and add the dependencies as follows:
Spring Web
Spring Data JPA
PostgreSQL Driver
After selecting these dependencies, click on “Generate.” Then, transfer the downloaded project's ZIP file to the desired destination.
Dependency management in pom.xml:
Add the required dependencies to the pom.xml file for custom software development:
<dependencies>
<!-- Spring Boot Web -->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<!-- Spring Data JPA -->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-jpa</artifactId>
</dependency>
<!-- PostgreSQL Driver -->
<dependency>
<groupId>org.postgresql</groupId>
<artifactId>postgresql</artifactId>
<scope>runtime</scope>
</dependency>
<!-- Spring Boot Starter Test -->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
<scope>test</scope>
</dependency>
</dependencies>
Here is the complete pom.xml file:
<?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>custom-software-api</artifactId>
<version>0.0.1-SNAPSHOT</version>
<name>custom-software-api</name>
<description>Custom Software API project for Spring Boot</description>
<parent>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-parent</artifactId>
<version>3.0.2</version>
<relativePath/> <!-- lookup parent from repository -->
</parent>
<properties>
<java.version>11</java.version>
</properties>
<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>org.postgresql</groupId>
<artifactId>postgresql</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
<scope>test</scope>
</dependency>
</dependencies>
<build>
<plugins>
<plugin>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-maven-plugin</artifactId>
</plugin>
</plugins>
</build>
</project>
The above pom.xml file contains all the necessary Maven dependencies required for our Spring Boot application. This setup will allow us to build a robust RESTful API with a PostgreSQL database in custom software development.
Step 3: Configure Database Settings
Next, configure your database connection by editing the application.properties or application.yml file in your Spring Boot project. For application.properties, add the following lines:
spring.datasource.url=jdbc:postgresql://localhost:3306/your_database_name
spring.datasource.username=your_database_username
spring.datasource.password=your_database_password
spring.jpa.hibernate.ddl-auto=update
server.port=8080
This configuration specifies the MySQL database URL, username, and password for your application. The spring.jpa.hibernate.ddl-auto=update setting ensures the database schema is automatically updated according to your JPA entities. The server.port=8080 setting defines the port on which your application will run.
Step 4: Create the Entity Class
Define a data model:
Create a new Java class for your project to represent the “Product” entity. Place this class in the com.example.entity package.
package com.example.entity;
import javax.persistence.*;
@Entity
@Table(name = "product")
public class Product {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private Long id;
@Column(nullable = false)
private String name;
@Column(nullable = false)
private double price;
@Column(nullable = false)
private int quantity;
// Getters and Setters
}
Explanation of the Code
Package Declaration: This line specifies the package in which the Product class is located.
package com.example.entity;
Imports: these import statements bring in the necessary JPA annotations.
import javax.persistence.*;
Entity annotation: This annotation marks the class as a JPA entity, meaning it is mapped to a database table.
@Entity
Table annotation: This annotation specifies the name of the database table to which this entity is mapped. Here, it maps to a table named product.
@Table(name = "product")
Fields and column annotations:
ID field: The @Id annotation denotes the entity's primary key. @GeneratedValue(strategy = GenerationType.IDENTITY) indicates that the database should generate the ID automatically.
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private Long id;
Name field: The @Column(nullable = false) annotation specifies that this column cannot be null in the database.
@Column(nullable = false)
private String name;
Price field: Similarly, this field is mapped to a non-nullable column named price.
@Column(nullable = false)
private double price;
Quantity Field: This field is mapped to a non-nullable column named quantity.
@Column(nullable = false)
private int quantity;
Getters and Setters:
These methods are standard in Java to allow for encapsulation. They provide access to private fields. Below is how you might define these methods:
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 double getPrice() {
return price;
}
public void setPrice(double price) {
this.price = price;
}
public int getQuantity() {
return quantity;
}
public void setQuantity(int quantity) {
this.quantity = quantity;
}
This class defines the structure of the Product entity, which the Spring Data JPA will use to interact with the product table in the database. The fields id, name, price, and quantity correspond to the columns in the product table. On the other hand, the annotations ensure the appropriate mappings and constraints are applied in custom software development.
Step 5: Create the Repository Interface
To interact with the database, we need to define a repository interface. This interface will extend JpaRepository to provide CRUD operations for the Product entity.
Interface for database operations:
Create a new interface in the com.example.repository package.
package com.example.repository;
import com.example.entity.Product;
import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.stereotype.Repository;
@Repository
public interface ProductRepository extends JpaRepository<Product, Long> {
}
Explanation
Package declaration: Specifies the package location for the repository.
package com.example.repository;
Imports: These import statements include the “Product” entity, JpaRepository for CRUD operations, and “Repository” for Spring’s component scanning.
import com.example.entity.Product;
import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.stereotype.Repository;
Repository annotation: Marks the interface as a Spring Data repository.
@Repository
Extending JpaRepository: Provides CRUD operations for “Product” entities with “Long” type IDs.
public interface ProductRepository extends JpaRepository<Product, Long> {
}
Step 6: Create the Service Class
In the Spring Boot application, the ProductService class manages the business logic for Product entities. It utilizes the ProductRepository to perform CRUD (Create, Read, Update, Delete) operations and applies business rules before interacting with the database. Below is the implementation of the ProductService class custom software development.
package com.example.service;
import com.example.entity.Product;
import com.example.repository.ProductRepository;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import java.util.List;
import java.util.Optional;
@Service
public class ProductService {
@Autowired
private ProductRepository productRepository;
public Product saveProduct(Product product) {
return productRepository.save(product);
}
public List<Product> getAllProducts() {
return productRepository.findAll();
}
public Optional<Product> getProductById(Long id) {
return productRepository.findById(id);
}
public Product updateProduct(Long id, Product updatedProduct) {
Optional<Product> existingProduct = productRepository.findById(id);
if (existingProduct.isPresent()) {
Product product = existingProduct.get();
product.setName(updatedProduct.getName());
product.setPrice(updatedProduct.getPrice());
product.setQuantity(updatedProduct.getQuantity());
return productRepository.save(product);
} else {
throw new ProductNotFoundException("Product not found");
}
}
public void deleteProduct(Long id) {
productRepository.deleteById(id);
}
}
Step 7: Create the Controller Class
The ProductController class acts as the entry point for handling HTTP requests related to product management. It receives incoming requests, delegates them to the corresponding methods in the ProductService, and returns appropriate responses. This controller defines endpoints for creating, retrieving, updating, and deleting products in custom software development.
package com.example.controller;
import com.example.entity.Product;
import com.example.service.ProductService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;
import java.util.List;
import java.util.Optional;
@RestController
@RequestMapping("/api/v1")
public class ProductController {
@Autowired
private ProductService productService;
@PostMapping("/product")
public ResponseEntity<Product> saveProduct(@RequestBody Product product) {
Product newProduct = productService.saveProduct(product);
return ResponseEntity.ok(newProduct);
}
@GetMapping("/products")
public List<Product> getAllProducts() {
return productService.getAllProducts();
}
@GetMapping("/products/{id}")
public ResponseEntity<Product> getProductById(@PathVariable Long id) {
Optional<Product> product = productService.getProductById(id);
return product.map(ResponseEntity::ok).orElseGet(() -> ResponseEntity.notFound().build());
}
@PutMapping("/products/{id}")
public ResponseEntity<Product> updateProduct(@PathVariable Long id, @RequestBody Product product) {
Product updatedProduct = productService.updateProduct(id, product);
return ResponseEntity.ok(updatedProduct);
}
@DeleteMapping("/products/{id}")
public ResponseEntity<String> deleteProduct(@PathVariable Long id) {
productService.deleteProduct(id);
return ResponseEntity.ok("Product deleted successfully");
}
}
Step 8: Run and Test the Application
Run the Spring Boot application:
Locate the main application class (annotated with @SpringBootApplication) and run it.
Test endpoints using cURL or Postman:
Create a product: curl -X POST -H "Content-Type: application/json" -d '{"name":"Sample Product", "price":10.0, "quantity":100}' http://localhost:8080/api/v1/product
Get all products: curl http://localhost:8080/api/v1/products
Get a product by ID: curl http://localhost:8080/api/v1/products/{id}
Update a product: curl -X PUT -H "Content-Type: application/json" -d '{"name":"Updated Product", "price":20.0, "quantity":50}' http://localhost:8080/api/v1/products/{id}
Delete a product: curl -X DELETE http://localhost:8080/api/v1/products/{id}
Conclusion
This is a thorough step-by-step process for building RESTful APIs with Spring Boot. This guide covers everything from the essential tools required to code samples to demonstrate each process. Spring Boot's simplicity allows businesses to focus on core functionalities rather than getting bogged down in configurations. Thus, the best custom software development agency must utilize Spring Boot to build RESTful APIs.
About the Creator
Jessica Bennett
Jessica is an individual contributor for various leading publications. Writing about technology, design and the latest innovations is her primary knack. She also works for Unified Infotech, a technology service provider serving startups.
Enjoyed the story? Support the Creator.
Subscribe for free to receive all their stories in your feed. You could also pledge your support or give them a one-off tip, letting them know you appreciate their work.
Comments
There are no comments for this story
Be the first to respond and start the conversation.