Intermediate 15 min read

Making HTTP Callouts with HttpRequest

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

  • Build and send an HTTP callout using HttpRequest and Http
  • Add authentication headers and a timeout to a callout

Prerequisites: None — this is the first lesson in the course.

The three callout classes

Every outbound callout in Apex follows the same three-class shape: HttpRequest (configure the method, endpoint, headers, and body), Http (actually sends the request), and HttpResponse (read back the status code and body).

Endpoints, headers, and timeouts

The endpoint must be registered as a Remote Site in Setup (or reached via a Named Credential — covered in a later lesson) before Salesforce allows the callout at all. setTimeout() caps how long Apex waits, in milliseconds (default 10 seconds, max 120). setHeader() adds authentication tokens or a content type.

A basic authenticated GET callout

HttpRequest req = new HttpRequest();
req.setEndpoint('https://api.example.com/v1/weather');
req.setMethod('GET');
req.setHeader('Authorization', 'Bearer ' + apiToken);
req.setTimeout(10000);

Http http = new Http();
HttpResponse res = http.send(req);

if (res.getStatusCode() == 200) {
    System.debug(res.getBody());
}

setTimeout() takes milliseconds — 10000 here means 10 seconds, matching Apex's default.

Exercise

Write Apex that sends a POST request to https://api.example.com/v1/orders with a JSON body and checks for a 201 status code.

Show hint

req.setMethod('POST'); req.setBody(jsonString); req.setHeader('Content-Type', 'application/json');

APEX

Making HTTP Callouts with HttpRequest — Quick Check

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

2. A callout endpoint must be registered as a Remote Site (or use a Named Credential) before Salesforce allows it.

3. What unit does setTimeout() expect?

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

Apex makes outbound HTTP callouts using the HttpRequest, Http, and HttpResponse classes — set a method, endpoint, and headers, send it, and read back the status code and body.