Search code examples
javarestpostspring-restcontroller

How does writing to response usually happen on the client side in POST in REST?


I'm learning REST and cannot find explanation of one simply thing. When, for example, we write some method in service like

@Override
public List<Response> createRequest(List<Request> requests) {
    List<Object[]> listOfUUIDsAndPermissions = signingInitiationRepository.findStorageUUIDAndPermission(); //we get from database three parameters to set it to our request to send it to some other side 

    return IntStream.range(0, Math.min(listOfUUIDsAndPermissions.size(), requests.size()))
            .mapToObj(i -> {
                Object[] arr = listOfUUIDsAndPermissions.get(i);
                Request request = requests.get(i);
                request.setStorageUUID(UUID.fromString((String) arr[0]));
                request.setPermissions(new String[]{(String) arr[1]});
                request.setServiceTo(ift);

                return new Response();
            })
            .toList();
}

And we do not need to set some fields in Response because we assume that all the necessary information will be sent to us from other side.

Is it OK to return just return new Response();?

I want to write some simple controller like

@PostMapping("/testlink")
public ResponseEntity<List<Response>> createRequest(@RequestBody List<Request> requests) {
    var result = myservice.createRequest();
    return ResponseEntity.ok(result);
}

Does it really work as I've described it above - I'll send some Request with all necessary fields and I get from client/other side/etc Response with all filled fields?


Solution

  • yes, if you return a ResponseEntity object in your controller method then the client will receive an HTTP response with headers you specify. Also, you don't need to pass your service method inside the ResponseEntity.ok(). That might create a confusing response to the client. Instead, just return result to the controller method or return ResponseEntity.ok() based on if your service method is successful.