I've been doing some research on this issue, but I haven't been able to find a solution. I'm trying to return HTTP 403 after failing to validate some information sent in a POST request to Salesforce. I have considered just throwing an exception to get some sort of error code returned, but that doesn't seem like a great way to do it.

I also tried using the HttpResponse class, but I'm not exactly sure how to. Doing something like the following yields the obvious error saying the function must return a String.

if (<some validation fails>) {
        HttpResponse err = new HttpResponse();
        return err;

What's the best way to send a response with a specific HTTP header code through an Apex class?



In response to @metadaddy, this is in an Apex class, ie:


global class MyClass {


    global static String doPost() {

        //Do stuff

        //Return something
        return JSON.serialize(retrievedVals);
  • Is this in an Apex REST Method or a Visualforce Page?
    – metadaddy
    Dec 10, 2014 at 6:49
  • @metadaddy this is in an Apex REST method - see my edit please.
    – rebello95
    Dec 10, 2014 at 6:55

1 Answer 1


This pattern where you explicitly update the RestContext allows you to set the status value:

global static void doPost() {

    // Do stuff

    RestResponse res = RestContext.response;
    if (res == null) {
        res = new RestResponse();
        RestContext.response = res;

    // Return something
    res.responseBody = Blob.valueOf(JSON.serialize(retrievedVals));

    // Set the status
    res.statusCode = 403;

There is a more complete example here.

  • Awesome! This is exactly what I needed, thank you!
    – rebello95
    Dec 10, 2014 at 15:29

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.