As we all know, creating a JSON callout body for an API integration in apex is a real pain. It's equally a pain to parse the data that is returned from the callout from within apex.
Something I've started doing is only using apex to make the callout and getting back the response, like so:
public class MyIntegrationUtility {
public static String callOut(String body) {
HttpResponse rsp = null;
try{
HttpRequest req = new HttpRequest();
req.setEndpoint('https://myapi.com/xml/v1/request.api');
req.setHeader('Content-Type','application/json');
req.setMethod('POST');
req.setBody(body);
// Make call
Http client = new Http();
rsp = client.send(req);
return rsp.getBody();
} catch (Exception e) {
String message = 'Error: ' + e.getMessage();
AuraHandledException auraError = new AuraHandledException(message);
auraError.setMessage(message);
throw auraError;
}
}
}
I create the body in my lightning component, send it to my apex controller, my apex controller makes the callout, then sends the response back to my lightning component, then all I have to do is use:
var parsed = JSON.parse(response.getReturnValue());
Now I have an object that I can easily use from within my lightning component. No need to use Roundtrip Serialization and Deserialization, a JSON Generator, or JSON Parsing. In addition, far less apex code to test.
Is this bad practice? Are there any serious consequence for doing this, like security? I have not come across this technique in the documentation for lightning components. So far it's really sped up an API integration I'm doing for a lightning component I'm working on.
The only downside I've thought of so far is if there is something in the response that I parsed from within the client, and I need to save it on the server. That would require another trip back to my apex controller.