18.4.3 - Creating a REST Resource
Enroll to start learning
You’ve not yet enrolled in this course. Please enroll for free to listen to audio lessons, classroom podcasts and take practice test.
Interactive Audio Lesson
Listen to a student-teacher conversation explaining the topic in a relatable way.
Introduction to JAX-RS
🔒 Unlock Audio Lesson
Sign up and enroll to listen to this audio lesson
Today, we're going to learn about JAX-RS, which is the standard API for creating RESTful services in Java EE. Can anyone tell me what REST stands for?
Isn't it Representational State Transfer?
Correct! REST is a method of designing networked applications. JAX-RS helps us implement this using Java. So why do you think we need something like JAX-RS?
It probably makes it easier to handle HTTP requests.
Exactly! JAX-RS provides us with annotations that make handling requests very straightforward. Now, let's dive into how we can create a REST resource.
Creating the Employee Resource
🔒 Unlock Audio Lesson
Sign up and enroll to listen to this audio lesson
To create a REST resource, we start by defining a Java class. For our example, we'll create `EmployeeResource`. Can anyone tell me the use of the `@Path` annotation?
I think it defines the endpoint URL where the resource can be accessed?
Yes! Great! By using `@Path('/employees')`, we tell the server that this resource can be accessed at '/employees'. Now, how do we handle the retrieval of employees?
We can use the `@GET` method!
Correct! And remember to annotate with `@Produces(MediaType.APPLICATION_JSON)` to specify the response format. Now let's discuss methods to add and update employees.
Implementing CRUD Operations
🔒 Unlock Audio Lesson
Sign up and enroll to listen to this audio lesson
Now we'll implement the `@POST` method for adding new employees. What must we ensure when using this method?
We need to consume JSON data and return the created employee?
Exactly! Using `@Consumes(MediaType.APPLICATION_JSON)` helps us accept JSON input. Moving on to updates, `@PUT` is used for modifying existing employees. Why use `@PathParam` here?
So we can extract the employee ID from the URL to know which employee to update.
Correct! Finally, what's the role of `@DELETE`?
It removes an employee based on their ID.
Great! Recap: we've learned how to define resource classes and handle CRUD operations using JAX-RS annotations.
Introduction & Overview
Read summaries of the section's main ideas at different levels of detail.
Quick Overview
Standard
In this section, we discuss how to create REST resources with JAX-RS in Java EE. We cover key annotations, methods for CRUD operations, and best practices for managing employee resources.
Detailed
Creating a REST Resource
In Java EE, JAX-RS is the standard API used for building RESTful applications. Creating a REST resource involves defining a resource class that will handle HTTP requests to manage resources. In this case, we'll be managing Employee resources.
A simple resource class, EmployeeResource, can be created using the @Path annotation to define the URI endpoint. Inside this class, methods are annotated with HTTP verbs (@GET, @POST, @PUT, @DELETE) to perform various operations on the Employee resource.
- @GET: Used to retrieve a list of employees, and outputs data in JSON format using
@Produces(MediaType.APPLICATION_JSON). - @POST: Accepts an incoming employee object via JSON, adds it to the list, and returns the added employee. It uses
@Consumesfor input type specification. - @PUT: Updates existing employee details based on the provided ID and returns the updated object. It also uses
@PathParamto fetch the ID from the URI. - @DELETE: Removes an employee based on the ID specified in the URI and returns a success message.
These methods enable the implementation of CRUD operations for managing employee resources within a RESTful architecture. Understanding REST resources is crucial for building effective API services.
Youtube Videos
Audio Book
Dive deep into the subject with an immersive audiobook experience.
Defining the EmployeeResource Class
Chapter 1 of 5
🔒 Unlock Audio Chapter
Sign up and enroll to access the full audio experience
Chapter Content
@Path("/employees")
public class EmployeeResource {
private static List employees = new ArrayList<>();
// ...
}
Detailed Explanation
In this chunk, we are defining a Java class named EmployeeResource. The annotation @Path("/employees") indicates that this class will handle HTTP requests targeting the /employees URI. The employees variable is a static list that is used to store instances of the Employee class.
Examples & Analogies
Think of the EmployeeResource class as a library where all the employee records are kept. Just like books in a library, employee details such as their ID, name, and department are stored in the employees list, which is accessible through specific requests to that library.
Retrieving Employees
Chapter 2 of 5
🔒 Unlock Audio Chapter
Sign up and enroll to access the full audio experience
Chapter Content
@GET @Produces(MediaType.APPLICATION_JSON) public ListgetEmployees() { return employees; }
Detailed Explanation
This method is marked with @GET, indicating it responds to HTTP GET requests. The annotation @Produces(MediaType.APPLICATION_JSON) specifies that the response data will be in JSON format. When this method is invoked, it returns the current list of employees.
Examples & Analogies
Imagine you are at a restaurant, and you ask the waiter for the menu. This method acts as that waiter, fetching the list of employees (the menu) and presenting it in a format (JSON) that you can easily understand.
Adding an Employee
Chapter 3 of 5
🔒 Unlock Audio Chapter
Sign up and enroll to access the full audio experience
Chapter Content
@POST
@Consumes(MediaType.APPLICATION_JSON)
@Produces(MediaType.APPLICATION_JSON)
public Employee addEmployee(Employee employee) {
employees.add(employee);
return employee;
}
Detailed Explanation
This method uses the @POST annotation, which handles HTTP POST requests intended for creating new entries. The @Consumes(MediaType.APPLICATION_JSON) annotation denotes that this method expects the request data to be in JSON format. When a new employee is added, this employee object is added to the employees list and then returned.
Examples & Analogies
Think of this method like a clerk at a registration desk who accepts new applicants. When you submit your details (the employee object), the clerk adds your information to the database (the employees list) and hands you a copy of your completed registration form.
Updating an Employee
Chapter 4 of 5
🔒 Unlock Audio Chapter
Sign up and enroll to access the full audio experience
Chapter Content
@PUT
@Path("/{id}")
@Consumes(MediaType.APPLICATION_JSON)
@Produces(MediaType.APPLICATION_JSON)
public Employee updateEmployee(@PathParam("id") int id, Employee employee) {
for (Employee e : employees) {
if (e.getId() == id) {
e.setName(employee.getName());
e.setDepartment(employee.getDepartment());
return e;
}
}
return null;
}
Detailed Explanation
This method is designed to update existing employee information. The @PUT annotation signifies this method handles HTTP PUT requests, which are used for updating resources. The @Path("/{id}") allows the specific employee to be identified by their unique ID passed as a path parameter. If the employee with the given ID is found, their details are updated, and the updated employee object is returned.
Examples & Analogies
Imagine you are revising a report. This method acts like an editor who updates a specific section of the report (the employee details) when you provide new information. If the report doesn't exist, the editor simply can't make any changes.
Deleting an Employee
Chapter 5 of 5
🔒 Unlock Audio Chapter
Sign up and enroll to access the full audio experience
Chapter Content
@DELETE
@Path("/{id}")
public String deleteEmployee(@PathParam("id") int id) {
employees.removeIf(e -> e.getId() == id);
return "Employee deleted.";
}
Detailed Explanation
This method is responsible for deleting an employee from the employees list. The @DELETE annotation indicates this method will handle HTTP DELETE requests aimed at removing a resource. The employee to be deleted is identified using the ID passed in the path. Once deleted, a success message is returned.
Examples & Analogies
Think of this method as a process of deleting outdated files from a filing cabinet. When you identify which file (employee) needs to be removed, you take it out and dispose of it, then confirm that the deletion was successful.
Key Concepts
-
JAX-RS: A specification for creating RESTful web services in Java EE.
-
@Path: Annotation indicating the resource's URI.
-
@GET: HTTP method for retrieving resources.
-
@POST: HTTP method for creating resources.
-
@PUT: HTTP method for updating resources.
-
@DELETE: HTTP method for deleting resources.
-
MediaType: Defines the data format of requests and responses.
Examples & Applications
The EmployeeResource class uses the @Path('/employees') annotation to define its access point.
Using @GET with @Produces(MediaType.APPLICATION_JSON) lets the server know the client expects a JSON response.
Memory Aids
Interactive tools to help you remember key concepts
Rhymes
With JAX-RS you can impress, for RESTful services, it’s the best!
Stories
Imagine an employee directory where each employee has a unique ID. Using JAX-RS, we create paths to retrieve, add, update, or delete any employee, just like navigating a personal assistant through requests.
Memory Tools
CRUD = Create, Read, Update, Delete: The four actions to remember for handling resources.
Acronyms
REST = Representational State Transfer; JAX-RS is used to transfer these representations!
Flash Cards
Glossary
- JAXRS
Java API for RESTful Web Services; a specification to help create RESTful web services in Java EE.
- @Path
An annotation used to specify the URI path for a resource class or method.
- @GET
An annotation that specifies that a method responds to HTTP GET requests.
- @POST
An annotation that indicates the method will handle HTTP POST requests.
- @PUT
An annotation used to update the resource identified by the URI.
- @DELETE
An annotation that indicates a method will handle HTTP DELETE requests.
- MediaType
A class that defines standard MIME types for HTTP requests and responses.
Reference links
Supplementary resources to enhance your learning experience.