Advanced 35 min read

HTTP Callouts: Http, HttpRequest, HttpResponse

By the end of this lesson, you'll be able to:

  • Build an HttpRequest with a method, endpoint, headers, and body
  • Send it with the Http class and read the HttpResponse
  • Connect this directly to Module 31's HttpCalloutMock lesson

Prerequisites: "XML Basics in Apex"

Building the request

HttpRequest request = new HttpRequest();
request.setEndpoint('https://api.example.com/shipping-rates');
request.setMethod('GET');
request.setHeader('Content-Type', 'application/json');

HttpRequest is built up piece by piece: setEndpoint (the URL), setMethod (GET, POST, PUT, DELETE), and setHeader for any metadata the external API requires — this is the object Module 31's mock classes ultimately received as their respond(request) parameter.

Sending it and reading the response

Http http = new Http();
HttpResponse response = http.send(request);

if (response.getStatusCode() == 200) {
    Map<String, Object> parsed = (Map<String, Object>) JSON.deserializeUntyped(response.getBody());
    Decimal rate = (Decimal) parsed.get('rate');
} else {
    System.debug('Callout failed with status: ' + response.getStatusCode());
}

http.send(request) actually makes the call, returning an HttpResponsegetStatusCode() (Lesson 6's 200/500 pattern from Module 31) and getBody() (Lesson 2's JSON.deserializeUntyped) are exactly the methods every mock's fabricated response provided during testing.

A POST request with a body

HttpRequest request = new HttpRequest();
request.setEndpoint('https://api.example.com/orders');
request.setMethod('POST');
request.setHeader('Content-Type', 'application/json');

Map<String, Object> orderData = new Map<String, Object>{'productId' => 'W123', 'quantity' => 2};
request.setBody(JSON.serialize(orderData));

HttpResponse response = new Http().send(request);

setBody combined with Lesson 2's JSON.serialize is the complete pattern for sending data to an external API, not just reading from one — this is genuinely everything a real callout needs.

Exercise

Build and send a GET request to 'https://api.example.com/status' and debug the response status code.

Show hint

setEndpoint, setMethod('GET'), then http.send(request).

APEX

HTTP Callouts: Http, HttpRequest, HttpResponse Quiz

1. Which class actually sends the HttpRequest and returns an HttpResponse?

Log in to submit the quiz and save your score.

My Notes

Log in to keep private notes on this lesson.

Questions about this lesson

No questions yet — be the first to ask.

Log in to ask a question about this lesson.

Summary

This lesson makes a real HTTP callout end to end — the exact thing Module 31's HttpCalloutMock lesson tested, finally shown from the calling side.