Creating a REST Service in Springboot -CRUD Operations

gautham
Eat-Sleep-Code-Repeat
5 min readSep 4, 2020

While we created a simple helloworld GET method in our previous article, we will now see a simple implementation of how can we return back a JSON object from our springboot application.

Most of the code needed we will generate in via eclipse.

Step 1: We need to create a sample java object. I will create a new Order.java within a new package com.springboot.demo.webservices.order. Lets define few basic elements of an order like an order number, description, quantity, order date, customer name, order total amount as shown below

package com.springboot.demo.webservices.order;
import java.util.Date;
public class Order {
private int OrderNumber;
private String ProductDescription;
private int ProductQuantity;
private Date OrderDate;
private String CustomerName;
private double OrderAmount;
}

Step 2 : Lets generate the default constructors, the getters and setters and toString methods from eclipse

  • To generate Constructors right click , select Source → Generate constructor using fields , Select all → Generate
  • To generate Getters & Setters right click, select Source → Generate Getters and setters, Select all → Generate
  • To generate Getters & Setters right click, select Source → Generate toString, Select all → Generate

A sample constructor generation is shown in the images below

this is how my order.java class looks like after generating the default methods

package com.springboot.demo.webservices.order;
import java.util.Date;

public class Order {
private int OrderNumber;
private String ProductDescription;
private int ProductQuantity;
private Date OrderDate;
private String CustomerName;
private double OrderAmount;
public Order() {}public Order(int orderNumber, String productDescription, int productQuantity, Date orderDate, String customerName,double orderAmount) {
super();
OrderNumber = orderNumber;
ProductDescription = productDescription;
ProductQuantity = productQuantity;
OrderDate = orderDate;
CustomerName = customerName;
OrderAmount = orderAmount;
}public int getOrderNumber() {
return OrderNumber;
}
public void setOrderNumber(int orderNumber) {
OrderNumber = orderNumber;
}
public String getProductDescription() {
return ProductDescription;
}
public void setProductDescription(String productDescription) {
ProductDescription = productDescription;
}
public int getProductQuantity() {
return ProductQuantity;
}
public void setProductQuantity(int productQuantity) {
ProductQuantity = productQuantity;
}
public Date getOrderDate() {
return OrderDate;
}
public void setOrderDate(Date orderDate) {
OrderDate = orderDate;
}
public String getCustomerName() {
return CustomerName;
}
public void setCustomerName(String customerName) {
CustomerName = customerName;
}
public double getOrderAmount() {
return OrderAmount;
}
public void setOrderAmount(int orderAmount) {
OrderAmount = orderAmount;
}
@Override
public String toString() {
return "Order [OrderNumber=" + OrderNumber + ", ProductDescription=" + ProductDescription + ", ProductQuantity="+ ProductQuantity + ", OrderDate=" + OrderDate + ", CustomerName=" + CustomerName + ", OrderAmount="+ OrderAmount + "]";}}

Step 3: Creating OrderServiceController.java

Lets now create a new OrderServicecontroller.java class and assign @RestController annotation to the class. Inside this class we will define methods to do basic CRUD operations like on Order object. We will create methods like
→QueryOrder
→CreateOrder
→UpdateOrder

Create GET method

Since we don’t have any database for now, we will create some sample data.

// Creating Sample data
int orderSequence = 1;

Order sampleOrder1 = new Order(orderSequence, "AmazonFirestickTV",2,new Date(),"Gautham", 199.98);
Order sampleOrder2 = new Order(++orderSequence, "AmazonFirestickTV",1,new Date(),"Ravi", 99.99);

We will also create a queryOrderInfo() method which will return a list of Order objects. Also assign an annotation @GetMapping(“/query/allorders”) of to make this method avialable as a GET service.

// Get method to query all orders
@GetMapping("/query/allorders")
public List<Order> queryOrderInfo() {
return Arrays.asList(sampleOrder1, sampleOrder2);
}

Now save the file and run the Application and you should be able to see the orders in a JSON format in the browser url

http://localhost:8080/query/allorders

Create PUT Method

Lets create a PUT method for updating customer name on one of the sample orders that we have created previously. The important thing here to notice is that we can pass the values in the request URL.

In the below code snippet {customername} is the variable in the url path.

We use an annotation @PathVariable to receive the inputs via the url path into our methods.

// Put method to update information in existing order
@PutMapping(“/update/order/customername/{customername}”)
public Order CreateOrder(@PathVariable String customername) {
sampleOrder1.setCustomerName(customername);
return sampleOrder1;
}

We would need a tool like POSTMAN to run the PUT method, when i load this url in POSTMAN as shown below and i pass a customer name i wanted to update, the customer name gets updated from Gautham to Aditya in the output.

Now since the data is not persistent, the updates that we do are not persisted and hence wont be available on the next call. We will in one of the future posts when we work with databases, we will update and persist the data.

Create POST Method

we will define a CreateOrder method and use the POST operation to do this. To define a POST method, we use the annotation @PostMapping. We also leverage the @PathVariable annotation to receive the values from the path URL as shown below.

In the below method, we create a new order object, calculate the total amount based on the quantity and return the new order in the response.

@PostMapping(“/create/order/{productname}/quantity/{qty}”)
public Order CreateOrder(@PathVariable String productname, @PathVariable int qty ) {

Order sampleOrder = new Order(++orderSequence,productname,qty,new Date(),”Random Customer”, 99.00*qty);

return sampleOrder;

}

You will need the POSTMAN tool to test this url. When you load the url http://localhost:8080/create/order/AmazonFirestickTV/quantity/10 and method POST then you should be able to see the new order with a new order sequence and the total amount ( which qty * 99.99 ) on the output as show below.

My OrderServiceController.java looks as below

package com.springboot.demo.webservices;

import java.util.Arrays;
import java.util.Date;
import java.util.List;

import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.PutMapping;
import org.springframework.web.bind.annotation.RestController;

import com.springboot.demo.webservices.order.Order;

@RestController
public class OrderServiceController {

// Creating Sample data
int orderSequence = 1;
Order sampleOrder1 = new Order(orderSequence, "AmazonFirestickTV",2,new Date(),"Gautham", 199.98);
Order sampleOrder2 = new Order(++orderSequence, "AmazonFirestickTV",1,new Date(),"Ravi", 99.99);


// Get method to query all orders
@GetMapping("/query/allorders")
public List<Order> queryOrderInfo() {
return Arrays.asList(sampleOrder1, sampleOrder2);
}

// Put method to update information in existing order
@PutMapping("/update/order/customername/{customername}")
public Order CreateOrder(@PathVariable String customername) {
sampleOrder1.setCustomerName(customername);
return sampleOrder1;
}

// Post method to create a new order
@PostMapping("/create/order/{productname}/quantity/{qty}")
public Order CreateOrder(@PathVariable String productname, @PathVariable int qty ) {

Order sampleOrder = new Order(++orderSequence,productname,qty,new Date(),"Random Customer", 99.00*qty);
return sampleOrder;

}

}

Congratulations , you have created the first basic create, update services in your springboot applications.

--

--

gautham
Eat-Sleep-Code-Repeat

Avid Reader || Blogger || Tech Enthusiast || Working as an Engineering Manager at Atlassian