1

I am writing an Apex Rest Service with the POST Method. For that, I have written an apex class wrapper for the request. Like below.

global class RestRequestWrapper {
    global String eId;
    global Decimal salary;
    global String email;
    global Date joiningDate;
}

Below is the simplified version of my doPost method. Where I am passing an instance of RestRequestWrapper class a parameter.

@RestResource(urlMapping='/ExampleRestService/*')
global class ApexRestServiceExample {
    @HttpPost
    global static String doPost(RestRequestWrapper requestData) {
        System.debug(requestData);
        return 'success';
    }
}

When I am calling this API, from workbench with the below JSON body.

{
    "eId": "asasdasdasd",
    "salary": 122233,
    "email": "[email protected]"
}

Returns this response.

[
    {
        "message": "Unexpected parameter encountered during deserialization: eId at [line:2, column:10]",
        "errorCode": "JSON_PARSER_ERROR"
    }
]

I don't run into any errors if I pass an empty JSON {}.

However, the JSON I am able to parse when fetched from the Request Body. I am not getting what I am doing wrong here. What is the difference when it is fetched from RestContext.request.requestBody.toString()?

1 Answer 1

2

You need to include the name of the parameter, as you can have multiple parameters in any order. These look the following:

JSON

{
    "requestData": 
        {
            "eId": "asasdasdasd",
            "salary": 122233,
            "email": "[email protected]"
        }
}

XML

<request>
    <requestData>
        <eId>asasdasdasd</iId>
        <salary>122233</salary>
        <email>[email protected]</email>
    </requestData>
</request>

You can read more in the documentation.

This is different than RestContext.request.requestBody.toString(), because the system provides automatic deserialization of the parameters for you. No need to call Dom.Document.loadXml() or JSON.deserialize(payload), etc. The system automatically compensates for both XML and JSON by way of Content-Type provided by the API caller. The only downside is that you lose some control over the acceptable formats.

You must log in to answer this question.

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