Sub topic 2
The Http, HttpRequest, and HttpResponse Classes
This chapter assumes you can write basic Apex classes and tests, and that you know HTTP methods, status codes, and JSON. It covers the three classes that every callout in this tutorial uses. A mock has to stand in for exactly these classes, so you need to know what each one does.
The three classes
Apex builds an HTTP callout from three classes in the System namespace:
HttpRequestdescribes what you send: the endpoint, the method, the headers, and the body.Httpsends a request. It has one method you will use,send.HttpResponsedescribes what comes back: the status code, the headers, and the body.
The flow is always the same. You build a request, pass it to Http.send, and read the response.
Building an HttpRequest
You set each part of the request with a setter method.
| Method | Purpose |
|---|---|
| `setEndpoint(String)` | The full URL to call |
| `setMethod(String)` | `GET`, `POST`, `PUT`, `PATCH`, `DELETE` |
| `setHeader(String, String)` | One request header, such as `Accept` |
| `setBody(String)` | The request body, for example a JSON string |
| `setTimeout(Integer)` | Timeout in milliseconds |
Each setter has a matching getter, such as getEndpoint() and getMethod(). These getters matter later, because a mock receives the HttpRequest and can inspect it.
Query string values must be encoded. The WeatherService class from this tutorial uses EncodingUtil.urlEncode for the city name, so a value like New York becomes a safe URL fragment.
Sending and reading the response
new Http().send(req) makes the callout and returns an HttpResponse. The useful methods on the response are:
getStatusCode()returns anIntegersuch as200or500.getStatus()returns the status text, such asOK.getBody()returns the body as aString.getHeader(String)returns one header value.
Here is the code under test for the whole tutorial. Read it with the three classes in mind.
public with sharing class WeatherService {
public class WeatherException extends Exception {}
public static String getCondition(String city) {
HttpRequest req = new HttpRequest();
req.setEndpoint('https://api.example.com/weather?city=' + EncodingUtil.urlEncode(city, 'UTF-8'));
req.setMethod('GET');
req.setHeader('Accept', 'application/json');
HttpResponse res = new Http().send(req);
if (res.getStatusCode() != 200) {
throw new WeatherException('Unexpected status: ' + res.getStatusCode());
}
Map<String, Object> body = (Map<String, Object>) JSON.deserializeUntyped(res.getBody());
return (String) body.get('condition');
}
}The method does four things in order:
- It creates an
HttpRequestand sets the endpoint, method, and header. - It sends the request with
Http.send. - It checks the status code and throws
WeatherExceptionfor anything other than200. - It parses the JSON body and returns the
conditionvalue.
Why the status check matters
Http.send does not throw an exception when the server answers with a 404 or 500. Those are valid responses. Only a failure to complete the call, such as a timeout, raises a System.CalloutException. Your code must therefore check the status code itself, as WeatherService does. Later chapters test both paths: a mock returns a 500 to exercise the WeatherException branch.
Who can create an HttpResponse
You can build an HttpResponse yourself with new HttpResponse() and call setStatusCode, setBody, and setHeader on it. In production code you rarely need to. In tests it is the main tool, because a mock's job is to construct and return one.
What this means for testing
Your code calls Http.send, and in a test that call is not allowed to reach the network. The next chapters show how to replace the response. The code under test does not change. The platform hands your HttpResponse back from send instead of contacting the service.
Exercise
A server returns status 503 to a call made with Http.send. Does send throw an exception? How does WeatherService react?
Show answer
No. send returns an HttpResponse with status code 503, because the call completed. WeatherService checks getStatusCode(), sees it is not 200, and throws a WeatherException with the message "Unexpected status: 503".
Exercise
Which class would a mock construct and return, and which setters would it use to fake a successful JSON reply?
Show answer
It returns an HttpResponse. It would call setStatusCode(200), setBody with a JSON string, and optionally setHeader('Content-Type', 'application/json').