‫Hi, welcome back. In this lecture, we're going to build GET Employee by Id REST API and in the next lecture,
‫we will write a unit test to test GET Employee by Id REST API.
‫Let's go ahead and let's build GET Employee by Id REST API
‫so in an EmployeeController, go to the bottom and just type the method public and the return type
‫of the method we are going to use
‫ResponseEntity. Well, ResponseEntity is a very useful class that we can use to create a response
‫for the REST API.
‫And this is generic class
‫so let's pass
‫Employee as a type. Let's give the method name as getEmployeeById and let's get the method argument as employeeId
‫of type Long
‫all right. Let's annotate this method with @GetMapping annotation to handle HTTP GET Request
‫and again, we need to pass the path variable that is ID.
‫OK, now this is called a URI template variable.
‫Well, we want to bind the value of this URI of this template variable
‫to the method argument
‫so in order to do that, let's go ahead and
‫let's use @PathVariable annotation and just pass this ID
‫All right, perfect. Within a method, we're going to have a return statement and then call an employee
‫service and we have get employee
‫by id method. Well, getEmployeeById method
‫returns Optional of type Employee
‫All right, let's call this method and just pass the employeeId. Now, our REST API should return a
‫proper status. Proper status code meaning let's say if the employee with this given id exist in
‫the database, then this REST REST should return a status code.
‫OK, OK, that is 200.
‫If the employee with a given ID is not exist in database, then the REST API should return
‫a status
‫code 404 that is not found. In order to configure the response status code
‫here what I'm going to do is I am going to call my method of Optional class map() method and then I'm going to
‫provide Lambda you know, lambda expression implementation for the functional interface.
‫And we can also use a method reference to call the method directly.
‫So here I'm going to use a ResponseEntity and then method reference and then call ok() method.
‫So this will basically map whether the employee object is exist or not.
‫If it is exist, then simply it will return
‫OK, or else we will return status not found.
‫OK, here I will provide a lambda expression and response entity
‫it has not found status and I'm going to build this object simply over here
‫that's it.
‫So what we have done, we have called get employee by id method, which returns an optional of type employee
‫and we are using the map() method to just map whether the employer object is exist or not.
‫If it exists, then we simply return the status code OK or else we simply return a status code
‫not found
‫All right.
‫So this is how we write the rest API to get a employee object by id
‫All right.
‫In the next lecture, what we gonna do is we gonna write a JUnit test case to test
‫this REST API
‫All right.
‫I will see you in the next lecture.