Search code examples
javaspring-bootspring-data-jpapostman

Why is my controller calling different API when there is no match API for the request?


I am working on a Spring boot project, it produces strange behaviors, for example:

I have two APIs as follow

Controller file

@GetMapping("/list/employees")
public ResponseEntity<List<Employee>> getEmployees(){
    List<Employee> list = employeeService.getAllEmployees();
    return new ResponseEntity<List<Employee>>(list, new HttpHeaders(), HttpStatus.OK );
}

@GetMapping("employee/{id}")
public ResponseEntity<Employee> getEmployeeById(@PathVariable("id") long id) throws RuntimeException{
        Employee employee = employeeService.getEmployee(id);
        return new ResponseEntity<Employee>(employee,new HttpHeaders(),HttpStatus.OK);
}

Service file

/*  return all employees */
public List<Employee> getAllEmployees(){
    List<Employee> listEmployee = employeeRepo.findAll();
    if(listEmployee.size()>0){
        return listEmployee;
    }else{
        return new ArrayList<Employee>();
    }
}

/*
    RETURN SINGLE EMPLOYEE BY ID
 */

public Employee getEmployee(long id) throws RuntimeException{
    Optional<Employee> employee = employeeRepo.findById(id);
    if(employee.isPresent()){
        return employee.get();
    }else{
         new RuntimeException("Record not found");
        }
    return null;
}

But running them in Postman gives weird output, for example:

Correct behavior of second API returning single employee

http://127.0.0.1:8080/employee/3
{
"id": 3,
"firstName": "Caption",
"lastName": "America",
"email": "[email protected]"
}

Incorrect behavior of the same API (I am typing the wrong path this time)

http://127.0.0.1:8080/employees/3

The API path is wrong (employees/3)

{
    "firstName": "Caption",
    "lastName": "America",
    "email": "[email protected]",
    "_links": {
        "self": {
            "href": "http://127.0.0.1:8080/employees/3"
        },
        "employee": {
            "href": "http://127.0.0.1:8080/employees/3"
        }
    }
}

Same behavior with the root URI, I have not triggered any action with home URI but still gives output like in the above API.

what can be the reason for these unwanted API calls?


Solution

  • Looks like you have Spring Data Rest on your class path. It will automatically wire paths based on the repositories. That second response is a HATEOAS response.

    A simple test would be to check maven/gradle. If you see spring-data-rest, comment it out and try again.