[SalesForce] Create the HTTP Request and Response apex classes to call the REST API

1.) Instantiating the Account object 2.) Serializing the object into the JSON format 3.) Creating an HTTPRequest, with parameters, and body 4.) Sending the HTTPRequest 5.) Handling the response, as well as failures.

Sample request need to be send to API for the response as follows with Account Id and Record Type.

{"action":"read",
"params":[
{"record_type":"consumer",
"Accountid":"471856"}
]
}

Here is the class that I have developed but I'm not sure whether I'm handling the record type correctly or not ?

public class AccountInformation {
    public String record_type;  
    public String AccountId;    

    public accoutninformation(string r,string id){
        record_type=r,
        AccountId=id
    }
    accountInformation ai = new accountInformation(acct.RecordType.Name, ''    acct.Account_Id__c);
    //Serialize the object to JSON format
    JSONString = JSON.serializePretty(ai);
    System.debug('Serialized Account: ' + JSONString);
    HttpRequest req = new HttpRequest();
    //Set HTTPRequest Method
    req.setMethod('POST');
    //Set HTTPRequest header proporties
    req.setHeader('NLAuth, nlauth_account: 11111, nlauth_email: restapi@test.com, nlauth_signature: PASSWORD,nlauth_role: 3')
    req.setHeader('content-type', 'application/json');
    req.setHeader('Accept', 'application/json');
    //Set HTTPRequest Endpoint
    req.setEndpoint('YOUR ENDPOINT URL HERE');
    //Set HTTP Request Body
    req.setBody(JSONString);
    Http http = new Http();
    try{
        HTTPResponse res = http.send(req);
        //Helpful debug messages
        System.debug(res.toString());
        System.debug('STATUS:'+res.getStatus());
        System.debug('STATUS_CODE:'+res.getStatusCode());
        System.debug('Content: ' + res.getBody());
    }
}

Best Answer

Can you please post the error message which you are getting.

As far as I can see: this is a pseudo code which explains less about your actual problem which your are facing.

My understanding:

You want to send an http request to an end point (another salesforce org). You have whitelisted the End point in connected apps.

You are sending a serializable Json data which will be accepted and parsed at the other side and a response will be sent.

What we need more is ; the actual error and the debug value of the ai (if the error is coming on it ).

Related Topic