Creating a REST Controller - 18.3.2 | 18. Building RESTful APIs Using Java (Spring Boot / Java EE) | Advance Programming In Java
K12 Students

Academics

AI-Powered learning for Grades 8–12, aligned with major Indian and international curricula.

Professionals

Professional Courses

Industry-relevant training in Business, Technology, and Design to help professionals and graduates upskill for real-world careers.

Games

Interactive Games

Fun, engaging games to boost memory, math fluency, typing speed, and English skills—perfect for learners of all ages.

Interactive Audio Lesson

Listen to a student-teacher conversation explaining the topic in a relatable way.

Dependencies in Spring Boot

Unlock Audio Lesson

0:00
Teacher
Teacher

First, let's talk about how to set up a REST API in Spring Boot. What’s the very first thing you think we need to do?

Student 1
Student 1

Maybe install the software?

Teacher
Teacher

That’s a great point! But after installing, we specifically need to add a dependency called `spring-boot-starter-web` in our `pom.xml` file. This is essential as it allows us to create web applications and work with RESTful endpoints.

Student 2
Student 2

What does this dependency actually do?

Teacher
Teacher

It provides the necessary libraries to handle HTTP requests and responses. Try to remember it as 'Web Starter' so that whenever you think of web apps in Spring Boot, you remember this dependency! Now, can anyone show me how you'd add this to the `pom.xml`?

Student 3
Student 3

It would be something like `<dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-web</artifactId> </dependency>`?

Teacher
Teacher

Perfect! Excellent job! Let’s summarize this point: we need to add a specific web starter dependency to our Spring Boot project to create REST APIs.

Creating an Entity Class

Unlock Audio Lesson

0:00
Teacher
Teacher

Now that we have our dependencies ready, let’s move on to creating an entity class. Can someone tell me what an entity class is?

Student 4
Student 4

Isn’t it a class that represents a certain data model?

Teacher
Teacher

Exactly! In our case, we can create an `Employee` class. What attributes do you think this class should have?

Student 1
Student 1

It should definitely have an ID, a name, and maybe a department?

Teacher
Teacher

Great points! We’ll define the attributes `id`, `name`, and `department`. Also, we must include getter and setter methods to access and modify these properties. Let's declare this in the class!

Student 2
Student 2

So, it will look like just regular attributes in Java, right?

Teacher
Teacher

Yes! Just like any other Java class. To recap, an entity class represents the data model of our application and includes attributes along with their access methods.

Implementing the Controller Class

Unlock Audio Lesson

0:00
Teacher
Teacher

Now, let’s put everything together by creating our controller class, `EmployeeController`. What do we need this class to do?

Student 3
Student 3

To handle requests like getting and posting employee data?

Teacher
Teacher

Exactly, it’ll handle CRUD operations! We will use annotations like `@RestController` and `@RequestMapping`. Who can explain what these annotations do?

Student 4
Student 4

The `@RestController` annotation makes the class a RESTful controller, and the `@RequestMapping` specifies the base URL!

Teacher
Teacher

Correct! Now we will add methods to handle GET, POST, PUT, and DELETE requests. Can anyone provide a brief explanation of how we would implement the GET method?

Student 1
Student 1

I remember it returns a list of employees from the `employeeList`.

Teacher
Teacher

Great job! So let's highlight: we are creating a controller class that will handle HTTP methods to perform CRUD operations on our employee data.

Introduction & Overview

Read a summary of the section's main ideas. Choose from Basic, Medium, or Detailed.

Quick Overview

This section outlines the steps required to create a REST controller using Spring Boot, including adding dependencies, creating an entity class, and implementing CRUD operations.

Standard

The detailed guide shows how to create a REST controller in Spring Boot, starting from setting up necessary dependencies to defining an entity class (Employee) and developing a controller class (EmployeeController) that handles CRUD operations with appropriate HTTP methods.

Detailed

Creating a REST Controller in Spring Boot

Creating a REST controller is a crucial step when developing a RESTful API using Spring Boot. This section provides explicit instructions on how to establish a REST controller to manage resources effectively.

Key Steps Involved:

  1. Add Dependencies: You will need to include the spring-boot-starter-web dependency in your pom.xml to work with web applications effectively.
Code Editor - xml
  1. Create an Entity Class: The foundation of your API will be the entity class, which defines the data structure. For instance, an Employee class can be defined with fields like id, name, and department, along with their corresponding getters and setters.
Code Editor - java
  1. Create a Controller Class: This is where you will manage HTTP requests and responses. The EmployeeController class will include methods to manage employees, such as retrieving all employees, adding a new employee, updating an existing employee, and deleting an employee. Each operation corresponds to a specific HTTP method (GET, POST, PUT, DELETE).
Code Editor - java

Significance:

Understanding how to create a REST controller is essential for setting up an API that allows clients to interact with your server, reflecting the principles of the REST architecture effectively.

Youtube Videos

Spring Boot Project: Build a REST API for an E-commerce Platform
Spring Boot Project: Build a REST API for an E-commerce Platform
Overview of the Java Memory Model
Overview of the Java Memory Model

Audio Book

Dive deep into the subject with an immersive audiobook experience.

Step 1: Add Dependencies (pom.xml)

Unlock Audio Book

Signup and Enroll to the course for listening the Audio Book



org.springframework.boot
spring-boot-starter-web

Detailed Explanation

In this first step, you need to include the necessary dependencies for Spring Boot in your project's pom.xml file if you are using Maven as your build tool. The spring-boot-starter-web dependency is crucial as it includes everything needed to build web applications using Spring, such as RESTful services. By adding this dependency, you tell Maven to download and include all the required libraries automatically.

Examples & Analogies

Think of this step as gathering all your tools before starting a DIY project. Just like you would retrieve tools like hammers, nails, and screws to build a shelf, in programming, you need to gather the right libraries (dependencies) to build your RESTful API.

Step 2: Create Entity Class

Unlock Audio Book

Signup and Enroll to the course for listening the Audio Book

public class Employee {
private int id;
private String name;
private String department;
// Getters and setters
}

Detailed Explanation

In this step, you define an Employee class that will represent the data structure of the employee resource in your API. This class contains fields for the employee's ID, name, and department. By defining getters and setters, you make it possible to encapsulate the employee data and manipulate it. This class will serve as the template for creating and manipulating Employee objects.

Examples & Analogies

Imagine you are designing a blueprint for a house. Just like that blueprint outlines the different rooms and dimensions, this Employee class serves as a blueprint for what constitutes an employee in your application. It outlines key attributes like ID, name, and department that every employee will have.

Step 3: Create a Controller Class

Unlock Audio Book

Signup and Enroll to the course for listening the Audio Book

@RestController
@RequestMapping("/api/employees")
public class EmployeeController {
private List employeeList = new ArrayList<>();

@GetMapping
public List getAllEmployees() {
return employeeList;
}

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

@PutMapping("/{id}")
public Employee updateEmployee(@PathVariable int id, @RequestBody Employee updatedEmployee) {
for (Employee emp : employeeList) {
if (emp.getId() == id) {
emp.setName(updatedEmployee.getName());
emp.setDepartment(updatedEmployee.getDepartment());
return emp;
}
}
return null;
}

@DeleteMapping("/{id}")
public String deleteEmployee(@PathVariable int id) {
employeeList.removeIf(emp -> emp.getId() == id);
return "Employee deleted successfully.";
}
}

Detailed Explanation

In this step, you create a controller class named EmployeeController. This class is annotated with @RestController, indicating that it will handle HTTP requests and send responses. The @RequestMapping annotation specifies the base URL for all the endpoints in this controller. Inside the class, you maintain a list of employees and define several methods for handling different HTTP requests:
- getAllEmployees(): Handles GET requests to retrieve all employees.
- addEmployee(): Handles POST requests to add a new employee.
- updateEmployee(): Handles PUT requests to update an existing employee using their ID.
- deleteEmployee(): Handles DELETE requests to remove an employee by ID.

Examples & Analogies

Think of the EmployeeController as a restaurant manager who takes customer orders and interacts with the kitchen staff. Just like the manager takes different types of requests—such as asking for the menu (GET), ordering food (POST), changing an order (PUT), or canceling an order (DELETE)—the controller processes different HTTP requests and manages the employee data accordingly.

Definitions & Key Concepts

Learn essential terms and foundational ideas that form the basis of the topic.

Key Concepts

  • Entity Class: A class defining the attributes of a resource in your application.

  • Controller: Manages HTTP requests and performs CRUD operations on resources.

  • Dependencies: External libraries required for application functionality.

Examples & Real-Life Applications

See how the concepts apply in real-world scenarios to understand their practical implications.

Examples

  • The Employee entity class defining properties like id, name, and department.

  • The CRUD operations methods in EmployeeController responsible for managing employee records.

Memory Aids

Use mnemonics, acronyms, or visual cues to help remember key information more easily.

🎵 Rhymes Time

  • To create controllers, don't you see, Add dependencies first, and then you’ll agree!

📖 Fascinating Stories

  • Imagine a shopkeeper who has to manage employees. First, they set up their inventory (dependencies), then list all their employees (entity class), and finally take customer requests to manage these employees (controller).

🧠 Other Memory Gems

  • D.E.C for Dependencies (D), Entity class (E), Controller (C) - the steps to create a REST controller!

🎯 Super Acronyms

CRUD

  • Create
  • Read
  • Update
  • Delete - the four operations you must manage in your REST API.

Flash Cards

Review key concepts with flashcards.

Glossary of Terms

Review the Definitions for terms.

  • Term: REST

    Definition:

    Representational State Transfer, a web standards-based architecture for managing web resources.

  • Term: Controller

    Definition:

    A class in Spring that handles incoming HTTP requests and returns responses.

  • Term: Entity Class

    Definition:

    A class that represents the data structure of a resource in the application.

  • Term: CRUD

    Definition:

    Create, Read, Update, Delete; fundamental operations performed on resources.

  • Term: Dependency

    Definition:

    An external library or framework that your application relies on to function.