2

Can a REST Http post method get a custom object( containing other custom objects and standard objects ) as a parameter if so how would the http post request body look like ? Thank you all for reading this : )

@RestResource(urlMapping='/myCustomREST/v1/*')
global with sharing class RestCustomClass {
global class myCustomRequest {
    public MyCustomObj customObj;
    public Account account;
    public Contact contact;

}

.....

1 Answer 1

6

The RestRequest documentation explains that:

If the Apex method has no parameters, then Apex REST copies the HTTP request body into the RestRequest.requestBody property.

So that allows you to take control of the deserialization into an instance of the class you have defined by using JSON.deserialize:

@HttpPost  
global static void post() {
    myCustomRequest data = (myCustomRequest) JSON.deserialize(
            RestContext.request.requestBody.toString(),
            myCustomRequest.class
            );
    // Use the data
}

The serialization/deserialization supports custom and standard objects.

3
  • Thanks for your input dear Keith, I really really appreciate it.
    – SInadino
    Commented Mar 17, 2016 at 19:36
  • That means we can have method annotated with @HttpGet and no parameters in the signature and use requestBody as mentioned above? The reason I ask this question is I always thought @HttpGet method should have parameters and @HttpPost method no paramters.
    – javanoob
    Commented Mar 18, 2016 at 0:24
  • @javanoob A GET is different in that the parameters are encoded in the URL (so not as JSON) and most conveniently obtained from RestRequest.params. I've never used method parameters for a GET...
    – Keith C
    Commented Mar 18, 2016 at 8:35

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .