4

Is the following code a RESTful service?

    @RestResource(urlMapping='/MyAccount')
    global class MyAccount {
       @HttpPost
       global static Account createAccount(String Name){
           Account acc = new Account(name= name);
           insert acc;       
           RestResponse res = RestContext.response;
           res.statusCode=201;
           return acc;
       }
   }

Please clarify my below doubts.
1. I read somewhere that a restful service should return statuscode 201 if POST operation is successful and a resource is successfully created. So I am not sure if the above service can be called restful if I don't set statuscode to 201.
2. Also that the response should enclose the location of the resource that is created through the call. If I set return type of the method to void, will it still be RESTful?

3
  • It will return a status of successful unless you set it otherwise. So yes, it is a restful class.
    – Eric
    Commented Dec 6, 2015 at 3:14
  • Yes Eric, it does return success code 200 but not 201 unless we set the error code explicitly to 201. 200 indicates that call was successful whereas 201 indicates that resource is successfully created. I read (martinfowler.com/articles/richardsonMaturityModel.html) that RESTful service should return 201 code upon successful creation of a resource. Please clarify
    – Mikey
    Commented Dec 6, 2015 at 3:35
  • Please mark as answered (so the question does not keep surfacing as unanswered) as an adequate and correct answer was given
    – Eric
    Commented Dec 6, 2015 at 23:39

1 Answer 1

6

Once you annotate your class with @RestResource salesforce takes care of setting status and header.

Even if you set return type as void your client requesting resource will still see the status code of 200 and if your apex fails your client will see failure with 500 status code or 400.

Whatever you return only defines body of the response not header.

Use workbench rest utility to see headers of response

I did something to test both positive and negative tests with return type as void

@RestResource(urlMapping='/MyAccount')
global class MyAccount {
   @HttpPost
   global static void createAccount(String Name){
       Account acc = new Account(name= name);
       insert acc;       
   }
 }

POSITIVE RESPONSE HEADERS

enter image description here

NEGATIVE RESPONSE HEADERS

enter image description here

Clearly the headers are added by SFDC itself and you dont need your own custom implementation around response behaviors unless you really wish to handle exceptions and add your own custom headers .

You can gracefully handle exceptions by try ,catch mechanisms with your own response wrapper as well depending on how other party or system will handle this .

Also its not always mandatory to show status code as 201 for response on POST .Many API's use 200 as well

You must log in to answer this question.

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