M.Dietz
M.Dietz

Reputation: 1000

API-method can return different types, how do i define the return type?

I have the following API method:

  @GetMapping
  public ResponseEntity<List<Project>> getProjects(@RequestParam(required = false) String userName, @RequestParam(required = false) boolean additionalInfo) {
    return ResponseEntity.ok(projectService.getProjects(userName, additionalInfo));
  }

It currently returns ResponseEntity<List<Project>>. But if the optional paramater additionalInfo is true, i would like to return ResponseEntity<List<ProjectAdditionalInfoDTO>>. How do i define the return type to indicate that both of them can be returned? Of course i could use ResponseEntity<?>, but that would be ugly.

Upvotes: 0

Views: 698

Answers (3)

Vasilis Vasilatos
Vasilis Vasilatos

Reputation: 890

As far as I can understand ProjectAdditionalInfoDTO should inherit Project. That means that if you add inheritance there, then you can return the parent class since ProjectAdditionalInfoDTO would always be Project. If not, then since they are different resources you should have different endpoints to access them.

Upvotes: 0

Tommy Brettschneider
Tommy Brettschneider

Reputation: 1500

I'd keep things simple and just split things up into two separate controller methods... e.g.

@GetMapping
public ResponseEntity<List<Project>> getProjects(@RequestParam(required=false) String userName) {
    //...
}

@GetMapping
public ResponseEntity<List<ProjectAdditionalInfoDTO>> getProjectsWithAdditionalInfos(@RequestParam(required=false) String userName, @RequestParam(required=true) boolean additionalInfo) {
    //...
}

Upvotes: 1

HPacquee
HPacquee

Reputation: 609

If they both have the same interface (let's say BaseProject) you can make it return the following:

ResponseEntity<List<? extends BaseProject>>

There is no possibility to show that 2 options are possible in the return type via the method signature.

Upvotes: 0

Related Questions