Salesforce integration practice exercises: REST, callouts and events
Integration exercises you can do with a free org and free tools: outbound callouts with Named Credentials, mocks for tests, your own REST endpoint, the standard APIs, and event-driven integration.
All exercises use the data model from our real estate practice project: Property__c, Buyer__c, Agent__c, Property_Agent__c and Property_Offer__c. Build Task 1 of that project first (about an hour), in a free Developer Edition org. Each exercise has a level, a check so you know it works, and a model answer to open after you have tried.
Exercises
1. Callout with a Named Credential
IntermediateCreate an External Credential and Named Credential for a free public API (for example a currency exchange rate API), then write Apex that converts a property price into another currency.
- Run the method in Anonymous Apex and print the converted price.
- There is no URL or key in your Apex code.
Show a model answer
public with sharing class FxService {
public static Decimal convert(Decimal amount, String fromCcy, String toCcy) {
HttpRequest req = new HttpRequest();
req.setEndpoint('callout:FX_API/latest?from=' + EncodingUtil.urlEncode(fromCcy, 'UTF-8')
+ '&to=' + EncodingUtil.urlEncode(toCcy, 'UTF-8'));
req.setMethod('GET');
req.setTimeout(10000);
HttpResponse res = new Http().send(req);
if (res.getStatusCode() != 200) {
throw new CalloutException('FX API returned ' + res.getStatusCode());
}
Map<String, Object> body = (Map<String, Object>) JSON.deserializeUntyped(res.getBody());
Map<String, Object> rates = (Map<String, Object>) body.get('rates');
return amount * (Decimal) rates.get(toCcy);
}
}Adjust the path and JSON parsing to your API. The Named Credential holds the URL; the External Credential holds authentication. Give users access through the permission set that the External Credential's principal is mapped to.
2. Test a callout with a mock
IntermediateWrite a test for exercise 1 using HttpCalloutMock. Test both a success and a 500 error.
- Both tests pass without calling the real API.
Show a model answer
@IsTest
private class FxServiceTest {
class Mock implements HttpCalloutMock {
Integer code; String body;
Mock(Integer c, String b) { code = c; body = b; }
public HttpResponse respond(HttpRequest req) {
HttpResponse r = new HttpResponse();
r.setStatusCode(code); r.setBody(body); return r;
}
}
@IsTest static void success() {
Test.setMock(HttpCalloutMock.class, new Mock(200, '{"rates":{"EUR":0.5}}'));
Assert.areEqual(50, FxService.convert(100, 'USD', 'EUR'));
}
@IsTest static void serverError() {
Test.setMock(HttpCalloutMock.class, new Mock(500, ''));
try { FxService.convert(100, 'USD', 'EUR'); Assert.fail('Expected an exception'); }
catch (CalloutException e) { Assert.isTrue(e.getMessage().contains('500')); }
}
}3. Build your own REST endpoint
IntermediateExpose an Apex REST service at /services/apexrest/buyers that creates a buyer from JSON and returns the new ID. Call it from Postman or Workbench.
- A POST with valid JSON returns 201 and an ID.
- Missing required data returns 400 with a message.
Show a model answer
@RestResource(urlMapping='/buyers')
global with sharing class BuyerApi {
global class BuyerIn { public String name; public String email; public Decimal budget; }
@HttpPost
global static void create() {
RestResponse res = RestContext.response;
try {
BuyerIn b = (BuyerIn) JSON.deserialize(RestContext.request.requestBody.toString(), BuyerIn.class);
if (String.isBlank(b.name)) { res.statusCode = 400; res.responseBody = Blob.valueOf('{"error":"name is required"}'); return; }
Buyer__c rec = new Buyer__c(Name = b.name, Email__c = b.email, Budget__c = b.budget);
insert rec;
res.statusCode = 201;
res.responseBody = Blob.valueOf(JSON.serialize(new Map<String, Object>{ 'id' => rec.Id }));
} catch (Exception e) {
res.statusCode = 400;
res.responseBody = Blob.valueOf(JSON.serialize(new Map<String, Object>{ 'error' => e.getMessage() }));
}
}
}4. Use the standard REST API
BeginnerWithout writing Apex, use the standard REST API (Postman, Workbench or the Salesforce CLI) to: query properties under a price, create a property, and create a property with two offers in one request.
- The query returns JSON records.
- The composite request creates all three records or none.
Show a model answer
Query: GET /services/data/vXX.X/query?q=SELECT+Id,Name+FROM+Property__c. Create: POST /services/data/vXX.X/sobjects/Property__c. For related records in one call, use the Composite API with allOrNone: true and reference the property's new ID in the offers with @{refProperty.id}. Use the latest API version your org shows in Setup, Apex Classes, Version Settings.
5. Platform Event for accepted offers
AdvancedCreate a platform event Offer_Accepted__e with Property ID and Amount. Publish it from a flow when an offer is accepted, and subscribe with an Apex trigger that creates a follow-up record (standing in for an external system).
- Accept an offer: the subscriber runs (check the debug log of the Automated Process user or the record it creates).
Show a model answer
trigger OfferAcceptedSubscriber on Offer_Accepted__e (after insert) {
List<Task> tasks = new List<Task>();
for (Offer_Accepted__e e : Trigger.new) {
tasks.add(new Task(WhatId = e.Property_Id__c, Subject = 'Prepare sale contract'));
}
insert tasks;
}Choose "Publish After Commit" so the event is only sent if the transaction succeeds. External systems can subscribe to the same event with the Pub/Sub API.
Keep going
Common questions
01Which free tools can I use to practise integration?
Which free tools can I use to practise integration?
Postman (or the Salesforce Platform APIs collection for it), Workbench, and the Salesforce CLI are all free. Public test APIs and webhook testing sites are useful targets for callouts.
02Do I need a connected app to call Salesforce APIs?
Do I need a connected app to call Salesforce APIs?
Yes, for OAuth from an external tool. In current orgs you create an External Client App (or a connected app where still available) and use an OAuth flow such as client credentials for system-to-system integrations, with a dedicated integration user.