2

I want to process a POST to a custom APEX REST endpoint that is being posted from SLACK with a Content type of application/x-www-form-urlencoded

When I inspect the body of the post in Hookbin it contains one parameter called "payload" and in it is a URL Encoded string.

I have created the following class and I have made it public and shared the class so that unauthenticated posts can be received without a challenge for credentials or requiring a token.

@RestResource(urlMapping='/slack/*')
global class REST_Slack  {

    @HttpPost global static void doPost() {
        System.debug('Response:');
        System.debug(RestContext.request.requestBody.toString());
        RestContext.response.headers.put('Content-Type','text/html');
        RestContext.response.statusCode = 200;
        System.debug(RestContext.response);
        List<String> items = new List<String>();
        for(String key : RestContext.request.headers.keySet()) {
            items.add(key + ' => ' + RestContext.request.headers.get(key));
        }
        
        RestContext.response.responseBody = Blob.valueOf('<html><body><span>Headers</span><div>' + String.join(items,'<br/>') + '</div><br/><br/><span>Request Body</span><div>' + EncodingUtil.urlEncode(RestContext.request.requestBody.toString(), 'utf-8') + '</div><br/><br/><span>Params</span><div>' + RestContext.request.params + '</div></body></html>');
    }

}

When I run this I am able to see the response but the body appears to be blank rather than populated with the value of the parameters. Is there another way that I should be attempting to access the payload parameter within my code?

1

So the issue was bad testing on my part. I was sending an empty string from my VS Code manual REST Posts.

Here is how I was able to get the content of the Post that was in application/x-www-form-urlencoded

RestContext.request.params.get('payload');

That grabbed the body parameter named payload. Presuming I had a form with a bunch of different input boxes you could surmise what the other names would be or inspect RestContext.request.params

The following minimal code will echo back the urlencoded content I received that was in the payload parameter.

@RestResource(urlMapping='/slack/*')
global class REST_Slack  {

    @HttpPost global static void doPost() {
        RestContext.response.headers.put('Content-Type','text/html');
        RestContext.response.statusCode = 200;  
        RestContext.response.responseBody = 
        Blob.valueOf(RestContext.request.params.get('payload'));
}

}

My content happens to be in JSON format within the payload however this may not be true for everyone so I left the content generic or whatever Content-Type makes the most sense for how you want to process the response.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.