2

When I try localhost:8080/api/employees I get a list (JSON-format). I would also like to get a single employee by ID. When I try localhost:8080/api/123abc I cannot find the employee with that ID. My response is:

Whitelabel Error Page This application has no explicit mapping for /error, so you are seeing this as a fallback.

Tue Jul 28 08:50:28 CEST 2020 There was an unexpected error (type=Not Found, status=404).

My code is below here

@RestController
@RequestMapping(value = "/api", produces = MediaType.APPLICATION_JSON_VALUE)
public class TestApiController {
    @Autowired
    private EmployeePoller poller;

    @GetMapping(path = "/employees")
    public List<Employee> allEmployees() {
        return poller.getAllEmployees();
    }

    @GetMapping(path = "/{id}")
    public Employee singleEmployee(@PathVariable String id) {
        return poller.getEmployeeById(id);
    }

edit: @PathVariable Long id and poller.getEmployeeById(id.toString()); doesn't work either.

toydarian
  • 4,246
  • 5
  • 23
  • 35
  • From the error `404`, I'd guess, that there is no employee with the id `123abc`. I can't test this, as I don't have your data. – toydarian Jul 28 '20 at 07:24
  • When i try `@GetMapping(path = "/{id}") public Employee singleEmployee(@PathVariable String id) { System.out.println(id); return poller.getEmployeeById(id); }` It doesnt print the id either. But this work `@GetMapping(path = "/123") public Employee singleEmployee() { return poller.getEmployeeById("123abc"); }` – Magnus Strand Jul 28 '20 at 07:28
  • Did you debug to see it if it gets to the line ```return poller.getEmployeeById(id);``` ? – Ali Ben Zarrouk Jul 28 '20 at 07:41
  • Can you find the user with id of "123abc" among the results when you hit the `/employees` endpoint? I mean does it really exist? – ardatosun Jul 28 '20 at 08:29

1 Answers1

1

The 404 - Not found could be:

  1. GET /api/123abc isn't declared as endpoint in your controller.
  2. There isn't employee with id = 123abc.

To confirm what's your case, do a new request with method OPTION to localhost:8080/api/123abc

If the response is 404, the issue is in your controller. If response is 200, then there isn't employee with id 123abc.

Also I see you are using the same path for both endpoints. Try the following code (It validate if "id" variable is employees).

@GetMapping(path = "/{id}")
public Employee getEmployee(@PathVariable(name = "id") String id) {
    if ("employees".equals(id)) {
        return poller.getAllEmployees();
    } else {
        return poller.getEmployeeById(id);
    }
}
  • Please don't post only code as answer, but also provide an explanation what your code does and how it solves the problem of the question. Answers with an explanation are usually more helpful and of better quality, and are more likely to attract upvotes. – Dima Kozhevin Jul 28 '20 at 09:48