Apex for LWC, Flow and Integrations · Lesson 37 of 41
JSON and HTTP Callouts in Apex
Integrations speak JSON. Whether you're calling a payment API, receiving a webhook, or storing configuration, you'll convert between JSON text and Apex objects constantly. Apex gives you three levels of control – typed classes, untyped maps, and a generator/parser for full control – plus the HTTP classes to send it over the wire.
In this lesson
- Typed JSON with wrapper classes
- Untyped JSON with maps
- Serialising: nulls, pretty print and reserved words
- Making HTTP callouts the right way
Typed JSON: deserialize into classes
When you know the shape of the data, define classes that mirror it and let JSON.deserialize fill them. Unknown properties in the JSON are ignored; missing ones stay null:
// OrderPayload.cls
public class OrderPayload {
public String orderId;
public String customerEmail;
public Decimal total;
public Date orderDate;
public List<Line> lines;
public class Line {
public String sku;
public Integer quantity;
public Decimal unitPrice;
}
}
String body = '{"orderId":"ORD-1042","customerEmail":"asha@acme.example","total":5498.00,'
+ '"orderDate":"2026-11-08","lines":[{"sku":"KB-01","quantity":2,"unitPrice":2499.00},'
+ '{"sku":"MS-07","quantity":1,"unitPrice":500.00}],"channel":"web"}';
OrderPayload order = (OrderPayload) JSON.deserialize(body, OrderPayload.class);
System.debug(order.orderId + ' for ' + order.customerEmail + ' on ' + order.orderDate.format());
for (OrderPayload.Line l : order.lines) {
System.debug(l.sku + ' x' + l.quantity + ' @ ' + l.unitPrice);
}
System.debug('Lines: ' + order.lines.size() + ', total ' + order.total);
// back to JSON – nulls left out
order.customerEmail = null;
System.debug(JSON.serialize(order, true));
ORD-1042 for asha@acme.example on 08/11/2026
KB-01 x2 @ 2499.00
MS-07 x1 @ 500.00
Lines: 2, total 5498.00
{"total":5498.00,"orderId":"ORD-1042","orderDate":"2026-11-08","lines":[{"unitPrice":2499.00,"sku":"KB-01","quantity":2},{"unitPrice":500.00,"sku":"MS-07","quantity":1}]}The extra "channel" property was ignored without complaint. JSON.serialize(obj, true) suppresses null properties – useful because many APIs treat "null" and "missing" differently. Use JSON.deserializeStrict if unknown properties should be an error.
Untyped JSON: maps and lists
For dynamic or deeply nested responses you only need a few values from, JSON.deserializeUntyped returns Map<String, Object> and List<Object>:
String response = '{"status":"ok","data":{"account":{"id":"A-9","tier":"gold","limits":{"credit":250000}},'
+ '"tags":["priority","emea"]},"meta":{"requestId":"r-77"}}';
Map<String, Object> root = (Map<String, Object>) JSON.deserializeUntyped(response);
Map<String, Object> data = (Map<String, Object>) root.get('data');
Map<String, Object> account = (Map<String, Object>) data.get('account');
Map<String, Object> limits = (Map<String, Object>) account.get('limits');
System.debug('status: ' + root.get('status'));
System.debug('tier: ' + account.get('tier') + ', credit: ' + limits.get('credit'));
List<Object> tags = (List<Object>) data.get('tags');
System.debug('tags: ' + tags.size() + ' – first ' + tags[0]);
System.debug('missing key: ' + account.get('nothing'));
status: ok tier: gold, credit: 250000 tags: 2 – first priority missing key: null
Reserved words in JSON keys
APIs happily use keys like "number", "type" or "limit", which are reserved in Apex and can't be property names. Two common fixes: read those values untyped, or rename the key in the JSON text before deserialising:
// InvoiceDto.cls
public class InvoiceDto {
public String invoiceNumber; // JSON key "number" – a reserved word in Apex
public Decimal amount;
}
String apiJson = '{"number":"INV-2026-0042","amount":1180.00}';
InvoiceDto dto = (InvoiceDto) JSON.deserialize(apiJson.replace('"number":', '"invoiceNumber":'), InvoiceDto.class);
System.debug(dto.invoiceNumber + ' = ' + dto.amount);
// and back again for the API
String outbound = JSON.serialize(dto).replace('"invoiceNumber":', '"number":');
System.debug(outbound);
INV-2026-0042 = 1180.00
{"number":"INV-2026-0042","amount":1180.00}The string replace is simple and works when the key name is unique in the payload. For complex cases, JSONParser and JSONGenerator let you read and write token by token.
HTTP callouts
public with sharing class PaymentGateway {
public class GatewayException extends Exception {}
public static String createRefund(String paymentId, Decimal amount, String idempotencyKey) {
HttpRequest req = new HttpRequest();
req.setEndpoint('callout:Payments_API/v1/refunds'); // Named Credential: URL + auth
req.setMethod('POST');
req.setHeader('Content-Type', 'application/json');
req.setHeader('Idempotency-Key', idempotencyKey);
req.setTimeout(20000); // ms, max 120000
req.setBody(JSON.serialize(new Map<String, Object>{ 'paymentId' => paymentId, 'amount' => amount }));
HttpResponse res = new Http().send(req);
if (res.getStatusCode() == 201) {
return (String) ((Map<String, Object>) JSON.deserializeUntyped(res.getBody())).get('id');
}
throw new GatewayException('Refund failed with ' + res.getStatusCode() + ': ' + res.getBody().left(200));
}
}
- Named Credentials store the base URL and authentication (OAuth, API key headers) outside your code;
callout:Nameuses them. No secrets in Apex, no Remote Site Settings needed. - Callouts aren't allowed after DML in the same transaction or from triggers – call out first, or move the callout to a Queueable with
Database.AllowsCallouts. - Limits: 100 callouts and 120 seconds of total callout time per transaction.
- Test with
HttpCalloutMock– see callout mocks.
For REST design, status codes, idempotency keys and building your own endpoints with @RestResource, see the REST course lessons on Apex callouts with Named Credentials and Apex REST and the Salesforce REST API.
Practice
Try it yourself
An API returns
{"results":[{"name":"A","score":9}, …]}. Write the classes to deserialize it.Show answer
public class ScoreResponse { public List<Item> results; public class Item { public String name; public Integer score; } }then(ScoreResponse) JSON.deserialize(body, ScoreResponse.class).A callout in an after-insert trigger fails with "Callout from triggers are currently not supported". Fix the design.
Show answer
Collect the record Ids and enqueue a Queueable that implements
Database.AllowsCallouts(or a@future(callout=true)method) to make the callout after the transaction commits.
Quick check
What happens to JSON properties that have no matching Apex field?
JSON.deserialize ignores them (deserializeStrict throws).
What does JSON.serialize(obj, true) do?
Leaves out properties that are null.
Where should API credentials live?
In Named Credentials / External Credentials, referenced with callout:Name.
Summary
- Use typed classes with JSON.deserialize when you know the shape.
- Use deserializeUntyped for dynamic data; cast maps and lists as you go.
- Handle reserved-word keys by renaming or parsing untyped.
- Call APIs with HttpRequest and Named Credentials; never call out from triggers directly.
Finished this lesson?
Mark it complete to track your progress, then carry on with the next lesson.