avatarPeng Cao

Summary

This web content provides a step-by-step guide to building a Java Spring Boot application with GET and POST API endpoints using Visual Studio Code (VS Code).

Abstract

The guide outlines a four-step process for Java developers to set up a Spring Boot project in VS Code, create a RESTful controller, and implement both GET and POST API endpoints. It begins with setting up the Java environment and installing necessary VS Code plugins, then moves on to creating a Java project with Spring Initializr. The tutorial further details how to add a controller to handle web requests, run the project, and test the endpoints using tools like Thunder Client or Postman. It also includes code snippets and screenshots for clarity, and encourages the use of Lombok for reducing boilerplate code.

Opinions

  • The author believes that VS Code, combined with the right plugins and Spring Boot, provides an efficient development environment for Java developers.
  • The use of Spring Initializr is recommended for quickly bootstrapping a new Spring Boot project.
  • Lombok is highlighted as a useful tool for reducing code verbosity, particularly for getters and setters.
  • The inclusion of a POST endpoint for processing JSON data indicates the author's focus on practical, real-world API development scenarios.
  • Encouraging readers to clap, follow, and join Medium through a referral link suggests the author values community engagement and support for content creators.

VS Code + Java + Spring Boot — A Step-By-Step Guide

Let’s dive into the 4 steps guide to build your first Java Spring Boot GET and POST API on VS Code!

TL;DR code repo for this guide is here

Step 0. Java Environment Setup

The setup varies based on the operating system you are using

  • Ensure java and javac command is available on your terminal

Step 1. VS code Plugins, Search `Spring Boot`

  • Spring Boot Tools
  • Sprint Boot Dashboard
  • Spring Boot Extension Pack
  • Spring Initializr Java Pack

Step 2. Create a java project

To start by bring up the vs command by Command + P or Ctrl + P, then pick the project configurations like below

Pick some dependenies, Spring Web and Lombok (Lombok is useful for templating code)

Pick a folder you want to generate your project under.

After finishing, you will have this

Bottom left ‘Java Project’ Panel is what we will use more extensively than the normal file explorer on the top left

Step 3 Adding First Controller

Expanding the java project and click the + button on the com.example.demo Then write the controller name MovieControlleron the input bar

Add first GET route the controller

package com.example.demo;

import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;

@RestController
public class MovieController {
 @GetMapping("/")
 public String first() {
  return "Hello World";
 }

 private Ticket getTicketForAge(int age) {
  Ticket ticket = new Ticket();
  if (age >= 18 && age < 65) {
   ticket.setTotalCost(25);
   ticket.setTicketType(TicketType.Adult);
   ticket.setQuantity(1);
  } else if (age >= 65) {
   ticket.setTotalCost(25 * 0.7);
   ticket.setTicketType(TicketType.Senior);
   ticket.setQuantity(1);
  } else if (age >= 11 && age < 18) {
   ticket.setTotalCost(12);
   ticket.setTicketType(TicketType.Teen);
   ticket.setQuantity(1);
  } else if (age >= 0 && age < 11) {
   ticket.setTotalCost(5);
   ticket.setTicketType(TicketType.Children);
   ticket.setQuantity(1);
  }
  // throw error
  else {
   throw new RuntimeException("Invalid age");
  }
  return ticket;
 }

 @PostMapping(path = "/", consumes = "application/json", produces = "application/json")
 @ResponseBody
 public Response post(@RequestBody Body body) {
  Response response = new Response();
  response.setTransactionId(body.getTransactionId());
  for (int i = 0; i < body.getCustomers().length; i++) {
   Customer customer = body.getCustomers()[i];
   Ticket ticket = getTicketForAge(customer.getAge());
   response.addTicket(ticket);
  }
  return response;
 }
}

Run the project and visit localhost:8080

Step 4. Add Another POST Route

Let’s assume Body is post body we want to accept. Create Customer.java andBody.java

package com.example.demo;

class Customer {
 private String name;
 private int age;
 // getters and setters
 public String getName() {
  return name;
 }
 public void setName(String name) {
  this.name = name;
 }
 public int getAge() {
  return age;
 }
 public void setAge(int age) {
  this.age = age;
 }
}
public class Body {
 private String transactionId;
 private Customer[] customers;
 
 public String getTransactionId() {
  return transactionId;
 }
 public void setTransactionId(String transactionId) {
  this.transactionId = transactionId;
 }
 public Customer[] getCustomers() {
  return customers;
 }
 public void setCustomers(Customer[] customers) {
  this.customers = customers;
 }
}

Let’s assume Response is the body we want to respond by the post endpoint. Create Response.java and add below

package com.example.demo;

import java.util.ArrayList;

public class Response {
 private String transactionId;
 private ArrayList<Ticket> tickets = new ArrayList<Ticket>();
 private double totalCost = 0;

 public String getTransactionId() {
  return transactionId;
 }

 public void setTransactionId(String transactionId) {
  this.transactionId = transactionId;
 }

 public ArrayList<Ticket> getTickets() {
  return tickets;
 }

 public void setTickets(ArrayList<Ticket> tickets) {
  this.tickets = tickets;
 }

 public double getTotalCost() {
  return totalCost;
 }

 public void setTotalCost(double totalCost) {
  this.totalCost = totalCost;
 }

 public void calculateTotalCost() {
  double temp = 0;
  for (int i = 0; i < tickets.size(); i++) {
   if (tickets.get(i).getTicketType() == TicketType.Children && tickets.get(i).getQuantity() >= 3) {
    temp += tickets.get(i).getTotalCost() * 0.75;
   } else {
    temp += tickets.get(i).getTotalCost();
   }
  }
  this.setTotalCost(temp);
 }

 private ArrayList<TicketType> getTicketTypes() {
  ArrayList<TicketType> ticketTypes = new ArrayList<TicketType>();
  for (Ticket ticket : tickets) {
   ticketTypes.add(ticket.getTicketType());
  }
  return ticketTypes;
 }

 public void addTicket(Ticket ticket) {
  ArrayList<TicketType> ticketTypes = this.getTicketTypes();
  if (ticketTypes.contains(ticket.getTicketType())) {
   for (Ticket existingTicket : tickets) {
    if (existingTicket.getTicketType() == ticket.getTicketType()) {
     existingTicket.setQuantity(existingTicket.getQuantity() + 1);
     existingTicket.setTotalCost(existingTicket.getTotalCost() + ticket.getTotalCost());
     this.calculateTotalCost();
     return;
    }
   }
  } else {
   this.tickets.add(ticket);
   this.calculateTotalCost();
  }
 }
}

Add to our controller the post route

@PostMapping(path = "/", consumes = "application/json", produces = "application/json")
 @ResponseBody
 public Response post(@RequestBody Body body) {
  Response response = new Response();
  response.setTransactionId(body.getTransactionId());
  for (int i = 0; i < body.getCustomers().length; i++) {
   Customer customer = body.getCustomers()[i];
   Ticket ticket = getTicketForAge(customer.getAge());
   response.addTicket(ticket);
  }
  return response;
 }

Run the project and make a post request using another vscode plugin Thunder client or Postman

// URL: localhost:8080
// post body
{
  "transactionId": "111",
  "customers": [
    {
      
      "name": "Alert",
      "age": 72
    }
  ]
}

If you find the guide helpful, feel free to clap and follow me. Join medium via this link to access all premium articles from me and all other awesome writers here on medium.

Programming
Coding
Java
Spring Boot
API
Recommended from ReadMedium