1

Is it possible to send a response message from a rest webservice? I have the following :

    @RestResource(urlMapping='/*')
 global with sharing class RestResource {
    @HttpGet
    webservice static List<Contact> showContact() {
        Boolean isValid;
        String phone; 
        List<Contact> resultCon= new List<Contact>();
        RestRequest request = RestContext.request;
        RestResponse response = RestContext.response;

        try {
        phone = (request.requestURI.substring(request.requestURI.lastIndexOf('/')+1)).replaceAll('[^0-9]','');
        isValid = Regex_Validator.isValidPhone(phone);
        system.debug('isValid '+ isValid);

            resultCon = [SELECT id, phone , lastname FROM Contact WHERE phone = :phone];
        } catch(exception e) {
            system.debug('Error'+ e);
        }
        system.debug(resultCon);
        if(resultCon.IsEmpty()) {
            response.statusCode = 204;
            response.addHeader('Content-Type', 'text/plain');
            response.responseBody  = blob.valueOf('Sorry no match');
        }
        if(!isValid) {
            response.statusCode = 415;
            response.responseBody  = Blob.valueOf('Check format phonenumber :+00 0000000000');
        }
        if(!resultCon.IsEmpty()) {
            return resultCon;
        }else {
            return null;    
        }
    }
}

The statuscode is returned fine in workbench but the body is not!?

  • 3
    You haven't included enough context for your code to say with 100% certainty that you're not doing anything wrong, but it doesn't look like you're doing anything wrong here. The responseBody should be getting sent back in the response to your webservice being called. What makes you think that it isn't being sent back? Where have you looked? Is there any other code in the execution path that messes with your response? Have you tried adding debugs to your code and looking at the logs? – Derek F Jul 10 '18 at 12:43
  • @DerekF I added my complete code to give it more context – Thomas Jul 16 '18 at 10:51
0

Can you change variable response.responseBody to RestContext.response.responseBody and also set the Content-Type, see below image: if it helps? I tried and it works fine:

enter image description here

It provides the response text:

enter image description here

  • 1
    A code block is more appropriate for multi-line snippets, but that still makes this answer a code dump. I can see what the difference is, but you should edit this answer to explain, using words, what the difference between your code and OP's code is. Also, it would be good to explain why you think this should work. – Derek F Jul 10 '18 at 13:11
  • It should, now. – RKM Jul 10 '18 at 13:56

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.