An API is a public web address that answers questions with data. When your code
sends a request to that address, the service on the other side sends back a
response: a status code that says what happened, and a body that holds the data.
Salesforce talks to APIs all the time. A callout from Apex is how your code asks
another system for something and uses the answer.
Three classes do the work. HttpRequest describes what you want: the endpoint
(the URL), the method (GET to read, POST to create), and a timeout. Http
sends it. HttpResponse holds what came back.
Http http = new Http();
HttpRequest request = new HttpRequest();
request.setEndpoint('https://dummyjson.com/products/1');
request.setMethod('GET');
request.setTimeout(30000);
HttpResponse response = http.send(request);
Always set a timeout. Without one, the platform uses a short default, and a slow
service fails the request rather than the whole transaction.
The endpoint is just a string, so you can build it in parts:
request.setEndpoint('https://dummyjson.com/products/' + productId);
response.getStatusCode() gives you the number the service used to report the
outcome. 200 means it worked. 404 means there is nothing at that address.
500 means the service broke. Check the status code before you use the body,
because an error response still has a body, and it is not the data you asked for.
response.getBody() returns the answer as text. Most APIs answer in JSON, and
JSON.deserializeUntyped turns that text into plain Apex values:
Map<String, Object> product = (Map<String, Object>) JSON.deserializeUntyped(response.getBody());
String title = (String) product.get('title');
A JSON object becomes a Map, a JSON array becomes a List, and the values
keep the types they had in the JSON. Numbers arrive as Integer when they have
no decimal point and as Decimal when they do, so price is a Decimal and
stock is an Integer.
One detail catches everyone the first time. The endpoint for a single product
answers with a JSON object, so it becomes a Map. The endpoint for the whole
collection also answers with a JSON object, but its products key holds a
List. Parsing the collection body as a Map and then reading title from it
gives you null, because the title of a collection does not exist.
The first mistake is reading the body before checking the status code. The second
is forgetting to set a timeout. The third is assuming every JSON answer is a
Map when it might be a List.