Examples

Java REST API

Building a REST API

Java REST API with Spring Boot handles CRUD with JSON.

Introduction to Java REST API with Spring Boot

Spring Boot is a powerful framework for building web applications in Java. It simplifies the process of setting up a new application with its auto-configuration and starter dependencies. In this tutorial, we will explore how to create a RESTful API using Spring Boot to handle CRUD (Create, Read, Update, Delete) operations with JSON data format.

Setting Up Your Spring Boot Project

To get started, you'll need to set up a new Spring Boot project. You can use the Spring Initializr (https://start.spring.io) to generate a basic project structure. Select the following options:

  • Project: Maven Project
  • Language: Java
  • Spring Boot: Latest stable version
  • Dependencies: Spring Web, Spring Data JPA, H2 Database (or another database of your choice)

Once you've downloaded and unzipped your project, open it in your favorite IDE.

Creating the Model Class

The model class represents the data structure of our application. For this example, we'll create a simple Product class with fields for id, name, and price.

Setting Up the Repository Interface

The repository interface extends JpaRepository, providing CRUD operations for the Product entity. The interface does not require any implementation, as Spring Data JPA automatically provides the necessary code at runtime.

Creating the REST Controller

The REST controller handles HTTP requests and responses. We'll create a ProductController to manage our Product resources, enabling operations such as creating, retrieving, updating, and deleting products.

Testing Your REST API

With the API implemented, you can test it using tools like Postman or curl. Ensure your application is running, and perform the following tests:

  • Create a Product: Send a POST request to /api/products with a JSON body containing name and price.
  • Retrieve Products: Use a GET request to /api/products to fetch all products, or /api/products/{id} to fetch a specific product.
  • Update a Product: Send a PUT request to /api/products/{id} with updated data.
  • Delete a Product: Use a DELETE request to /api/products/{id} to remove a product.