Apex HttpMethod with two possible returning types

Is it possible to make an apex httpMethod return two different kind of data type (DTOs).

When I try to do :
global static Object myMethod()

I get this error : HttpGet methods do not support return type of Object.

Answers:

Thank you for visiting the Q&A section on Magenaut. Please note that all the answers may not help you solve the issue immediately. So please treat them as advisements. If you found the post helpful (or not), leave a comment & I’ll get back to you as soon as possible.

Method 1

Another common solution is to have a top-level DTO that contains the other two DTOs:

public class Response {
  public ResponseDTO response;
  public ErrorDTO[] errors;
}

This is particularly useful if you want to use the automatic XML/JSON conversion support provided by the platform depending on the Accept request header.

You can read more about this automatic serialization behavior here and its related sub-pages.

Edit:

You can actually use a virtual class, then have each DTO extend that class, giving you the ability to return either:

global virtual class Response {
    // stuff here //
}
global class DTO1 extends Response {
    // more stuff here //
}
global class DTO2 extends Response {
    // more stuff here //
}
@HttpGet global static Response doGet() {
    Response res;
    if(shouldDTO1()) {
      res = new DTO1();
    }
    if(shouldDTO2()) {
      res = new DTO2();
    }
    return res;
}

Method 2

The response you return has to be of type Blob, so it doesn’t matter what you return in the function.
The way to return an object is by serializing your object as a JSON file, convert it to Blob object, and adding it to the responseBody of the RestResponse.

Here’s an example:

@RestResource(urlMapping='/ServiceName/*')
global class SomeService {
    @HttpGet
    global static void getData(){
        RestResponse res = RestContext.response;
        try {
            List<Lead> leadsList = [SELECT Id 
                                     FROM Lead];
            res.statusCode = 200;
            res.responseBody = Blob.valueOf(JSON.serialize(leadsList));
        } catch (Exception e) {
            res.statusCode = 500;
            res.responseBody = Blob.valueOf(e.getMessage());
        }
    }
}

Method 3

Yes, your method should return a String and you’ll need to serialize your object in JSON before returning them.

global static String myMethod() {
 ...
 return JSON.serialize(myRecord);
}


All methods was sourced from stackoverflow.com or stackexchange.com, is licensed under cc by-sa 2.5, cc by-sa 3.0 and cc by-sa 4.0

0 0 votes
Article Rating
Subscribe
Notify of
guest

0 Comments
Inline Feedbacks
View all comments
0
Would love your thoughts, please comment.x
()
x