Rest api : Custom salesforce response for a rest api

apexrest-api

I'm writing a rest api , and trying to return a custom response (i.e a Map<String,Object>) , but salesforce is giving me HttpPatch methods do not support return type of System.RestResponse so i decided to populate RestContext.response but when i run it through an postman , i get 200 response all the time , an empty body , event thought i did send a body with the error code?

How can i fix this error and see the proper response?

code :

  @HttpPatch
    global static void doPost(String accountid) 
    {
        Account myaccount;
        list <Opportunity> myresult;
        try
        {
            myaccount = [select website from Account where id=:accountid];
            myresult=[select id from Opportunity where website__c=:myaccount.website limit 10];

            RestContext.response.addHeader('Content-Type', 'application/json');
            RestContext.response.responseBody = Blob.valueOf(JSON.serialize(myresult));
    response.statusCode = 201;
        }
        catch (Exception e) 
        {
            RestContext.response.addHeader('Content-Type', 'text/plain');
            RestContext.response.responseBody = Blob.valueOf('Incorrect account id');
    response.statusCode = 400;
        }
    }

Best Answer

I remember I had a similar problem a while ago.

Try setting the RestContext.response to a variable, and setting your response status code and body on that variable.

Change your code to the following:

@HttpPost
    global static void doPost(String accountid) 
    {
        Account myaccount;
        list <Opportunity> myresult;
        RestResponse res = RestContext.response;
        try
        {
            myaccount = [select website from Account where id=:accountid];
            myresult=[select id from Opportunity where website__c=:myaccount.website limit 10];

            res.addHeader('Content-Type', 'application/json');
            res.responseBody = Blob.valueOf(JSON.serialize(myresult));
            res.statusCode = 201;
        }
        catch (Exception e) 
        {
            res.addHeader('Content-Type', 'text/plain');
            res.responseBody = Blob.valueOf('Incorrect account id');
            res.statusCode = 400;
        }
    }
Related Topic