简体   繁体   中英

Get Method status Issue

I am testing API'S. In which I use GET method to check responses. I Perform Searching by using ID.I enter invalid value Like I search ID=30 but there is no record of ID=30 But still it will show 200 Status. But it should be show us 204 Status. Is it wrong or Right or why they are showing 200 status if there is no data?

The HTTP 200 OK success status response code indicates that the request has succeeded.

You have to put a check of empty data and set HttpStatus.NO_CONTENT (204) before sending the response back to client otherwise it will show HttpStatus.OK (200) by default.

Example: If you try to search with id 30,it will fetch the employee with id 30 with status 200 Ok and if you try to search with some other id (not in the list),it will give you no data with status 204 No Content

@RequestMapping("/employee/{id}")
  public ResponseEntity<Employee> getEmployeeById(@PathVariable("id") int id){
    
    //HardCoded Data
    List<Employee> list = new ArrayList<>();
    list.add(new Employee(10,"a"));
    list.add(new Employee(20,"b"));
    list.add(new Employee(30,"c"));

    Optional<Employee> optional = list.stream().filter(x -> x.getId() == id).findFirst();
    Employee employee = null;
    if(optional.isPresent()){
      employee = optional.get();
    }
    return new ResponseEntity<>(employee, employee==null ? HttpStatus.NO_CONTENT : HttpStatus.OK);
  }

带有状态码的 API 请求

在此处输入图像描述

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM