Salesforce Technical Questions and answers

How to Return HTTP 200 in Apex REST?

Spread the love

Question

I am new to working with webhooks and need to expose an Apex class to an external system to handle a POST operation in Salesforce. Specifically, I am integrating with Authorize.net, which requires the webhook endpoint to return an HTTP 200 status code.

Here’s the screenshot of API documentation.

Here’s the debug output from my code:

RestContext.response ### RestResponse:[headers={}, responseBody=null, statusCode=null]
RestContext.statusCode again ### 200

Here’s my current Apex class:

@RestResource(urlMapping='/test/*')
global with sharing class WebHookHandler {

    @HttpPost
    global static Integer somePost() {
        RestRequest requestContext = RestContext.request;
        RestResponse responseContext = RestContext.response;
        String requestBody = RestContext.request.requestBody.toString();
        System.debug('RestContext.response ### ' + RestContext.response);
        responseContext.statusCode = 200;
        System.debug('RestContext.statusCode again ### ' + responseContext.statusCode);
        return responseContext.statusCode;
    }
}

However, when the endpoint returns the status code, the response body contains the value 200, which seems incorrect.

How can I properly set the status code and response body to meet the requirements of the webhook?

Answer

Your current implementation returns the statusCode as the response body, which is likely not the desired behavior. To correctly handle webhooks from Authorize.net or similar systems, you need to ensure that the HTTP response adheres to their specifications. This typically involves setting the appropriate status code and optionally including a response body if required. Here’s how you can improve your Apex class.

Correct Approach:

You can modify the method to set the status code and response body directly using the RestContext.response object. Here’s the updated code:

@RestResource(urlMapping='/test/*')
global with sharing class WebHookHandler {

    @HttpPost
    global static void somePost() {
        // Retrieve the request context
        RestRequest requestContext = RestContext.request;

        // Log the request body for debugging
        String requestBody = RestContext.request.requestBody.toString();
        System.debug('Request Body: ' + requestBody);

        // Set the response context
        RestResponse responseContext = RestContext.response;
        responseContext.statusCode = 200; // Set HTTP 200 status code
        responseContext.responseBody = Blob.valueOf('success'); // Set the response body as expected

        // Log for debugging
        System.debug('Response Status Code: ' + responseContext.statusCode);
        System.debug('Response Body: ' + responseContext.responseBody.toString());
    }
}

Explanation of the Changes:

  1. Void Return Type:
    Change the method’s return type to void to avoid returning unnecessary data that could be serialized into the response body. Instead, explicitly set the response in RestContext.response.
  2. Response Body:
    Use the responseBody property to set a meaningful response message, such as 'success'. Authorize.net may not require a response body, but if they do, include whatever is specified in their documentation.
  3. HTTP Status Code:
    Set the statusCode property to 200 to comply with the webhook’s requirement.

Additional Notes:

If the webhook requires no response body, you can skip setting responseBody. The simplified version of the method would look like this:

@RestResource(urlMapping='/test/*')
global with sharing class WebHookHandler {

    @HttpPost
    global static void somePost() {
        // Set the HTTP 200 status code
        RestContext.response.statusCode = 200;

        // Optional: Log the request for debugging purposes
        System.debug('Request Body: ' + RestContext.request.requestBody.toString());
    }
}

Refer to the webhook documentation to ensure your response format (status codes and body) matches their requirements. Always test the webhook with the external system to validate the behavior.

Summing Up

To properly handle a webhook in Salesforce and return an HTTP 200 status code, you need to use the RestContext.response object to set the response explicitly. Update your Apex method with a void return type to avoid unintentionally returning data in the response body. Set the statusCode property to 200 and, if required by the external system (e.g., Authorize.net), set a meaningful value in the responseBody property using Blob.valueOf('your message'). This ensures the response adheres to the webhook’s specifications. If no response body is required, simply set the status code and leave the body unset.

Enroll for Career-Building Salesforce Training with Real-Time Projects

Our Salesforce Course is designed to deliver a thorough understanding of the Salesforce platform, equipping you with the essential skills to excel in the CRM domain. The curriculum includes key modules like Salesforce Admin, Developer, and AI, seamlessly blending theoretical concepts with practical application. With real-world project experience and hands-on exercises, you’ll develop the expertise to tackle complex business challenges using Salesforce solutions. Our seasoned instructors ensure you gain valuable technical knowledge and industry-relevant insights to thrive in the Salesforce ecosystem.

Beyond technical expertise, our Salesforce training in India provides personalized mentoring, certification support, and interview coaching to enhance your career prospects. Participants benefit from comprehensive study materials, practical exposure through live projects, and individualized guidance throughout the course. By the program’s conclusion, you’ll be well-prepared not only for certification exams but also for real-world scenarios, armed with the problem-solving skills and hands-on experience employers value. Take the first step in your Salesforce career with us and open the door to a world of exciting opportunities. Enroll for Free Demo!

Open Chat
1
Dear Sir/Madam
How can I help you?