Sub topic 2
Building a Request and Handling Its Response
Assume you know basic Apex, HTTP methods and status codes, JSON, and Salesforce governor limits. This chapter focuses on a synchronous request. The endpoint uses a Named Credential named Todo_API.
Building the request
HttpRequest stores the method, endpoint, headers, body, and timeout. Http sends the request. The callout: prefix tells Salesforce to use the configured Named Credential.
public with sharing class TodoClient {
public class TodoException extends Exception {}
public class Todo {
public Integer id;
public Integer userId;
public String title;
public Boolean completed;
}
public static Todo create(Todo newTodo) {
HttpRequest req = new HttpRequest();
req.setEndpoint('callout:Todo_API/todos');
req.setMethod('POST');
req.setHeader('Accept', 'application/json');
req.setHeader('Content-Type', 'application/json');
req.setTimeout(20000);
req.setBody(JSON.serialize(newTodo, true));
HttpResponse res;
try {
res = new Http().send(req);
} catch (CalloutException e) {
throw new TodoException('The HTTP call failed: ' + e.getMessage());
}
if (res.getStatusCode() != 201) {
throw new TodoException(
'Create failed with status ' + res.getStatusCode()
);
}
return (Todo) JSON.deserialize(res.getBody(), Todo.class);
}
}The timeout is measured in milliseconds. A timeout limits how long Apex waits for the remote service. It does not make a slow service faster.
Reading the response
HttpResponse provides the status code, headers, and body.
200usually means a successful read.201usually means a resource was created.400–499indicate a request or authorization problem.500–599indicate a server-side problem.
Check the status before deserializing the body. Error bodies often have a different JSON shape from success bodies.
Working with JSON payloads
JSON.serialize converts an Apex object into JSON. The second argument omits null fields. JSON.deserialize converts JSON into a typed Apex object, which gives the code named fields instead of unstructured maps.
Handling failures
Treat HTTP failures and transport failures separately. An HTTP error means the server replied with a status such as 400 or 500. A CalloutException means the request could not complete, such as from a timeout or connection problem.
Exercise
Why should code check the status code before calling JSON.deserialize?
Show answer
The response body for an error may have a different structure, so deserializing it as a success object can fail or hide the real problem.