+ Start a Discussion
Poorna Developer 13Poorna Developer 13 

API Callout Reponse handling

Hi Everyone,
 My team have a requirements regarding API call, 
We have a pass HttpRequest in the form of JSON data.While, requesting to web service need data field validations like remove null and empty data, required fields should be filled or else throw an error in record page.  And, get back HttpResponse as JSON form.Once, get Reponse from web service need to handling the server response if response.GetStatusCode == 200 'success' or else need to stop the process and throw an error on the record page.

What I have done?
 Trigger to get Record when it's generate JSON data and validate. And, send that JSON data as a setBody while  sending  HttpRequest. Once the response get from web service, need a help to handling web service response.

Any Suggestions?
 Thanks in advance.
SUCHARITA MONDALSUCHARITA MONDAL

Hi Poorna,

Once you get  response. then you check with the status code. If your status code is 200/Success, then perform further step. Also perform this callouts in future method for Asyncronousity.

Http http = new Http();
HttpRequest request = new HttpRequest();
request.setEndpoint('https://th-apex-http-callout.herokuapp.com/animals');
request.setMethod('GET');
HttpResponse response = http.send(request);
// If the request is successful, parse the JSON response.
if(response.getStatusCode() == 200) {
    // Deserialize the JSON string into collections of primitive data types.
    Map<String, Object> results = (Map<String, Object>) JSON.deserializeUntyped(response.getBody());
    // Cast the values in the 'animals' key as a list
    List<Object> animals = (List<Object>) results.get('animals');
    System.debug('Received the following animals:');
    for(Object animal: animals) {
        System.debug(animal);
    }
}


Link:  https://trailhead.salesforce.com/content/learn/modules/apex_integration_services/apex_integration_rest_callouts
 
Hope this will give you some idea.
Thanks
Sucharita
Poorna Developer 13Poorna Developer 13
Hi Sucharita
   Thanks.
Our requirement is something different from your code.
We need to handle after getting response from web service. Like, If the statuscode is equal to 200 is success. Or else, web service response throw an error how to handle that in the future class.
Sample Code:
 public with sharing class ServerCallouts
{
@future(Callout=true)
public static void doCallout()
{
try
{
//do web serivce callout //get web service response //if resposne statuscode is equal to 200 do further process
}
catch(Exception ex)
{
LoggingLevel.ERROR, ex.getMessage();
//If web service response is not equal to 200, handle web service error here
// need to return web service response from here
}
}
}