Skip to content
← BlogSalesforce · 3 min read

In this follow-up post, we focus on how the processed F1 data gets stored in Salesforce: deduplication, external IDs, and linking with a Flow that triggers the logic based on the season. 🛠️📦 This covers the full cycle from API to custom objects and automation.

SalesforceApex3 min

Introduction

Building Salesforce integrations with external APIs can be complex. Recently, I created a solution to import Formula 1 season data into Salesforce using Apex and Flow. This post breaks down the architecture, pagination, data modeling, and best practices learned! ⚙️


Architecture Overview

  • Secure API Access: Using Named Credentials for authentication. 🔐
  • Apex Wrappers: Strongly typed classes to deserialize JSON data. 📦
  • Pagination Logic: Looping through API pages, concatenating JSON before deserialization. 🔄
  • Flow Integration: An Invocable Apex method triggers the whole process. ⚡

Pagination & JSON Assembly

The API delivers data paginated. To handle this, I built a method that loops over pages, collects JSON snippets, then assembles a full JSON for deserialization.

java
1public static F1APIWrappers.ResultAPIWrapper createPagedResponse(String season, String raceType) { 2 Integer limit = 30; 3 Integer offset = 0; 4 Integer total = 0; 5 String accumulatedBody = '['; 6 Boolean firstPage = true; 7 8 do { 9 // Perform HTTP callout with offset and limit 10 HttpResponse response = callAPI(season, raceType, limit, offset); 11 String body = response.getBody(); 12 13 // Strip array brackets and append 14 String trimmedBody = trimArrayWrapper(body); 15 16 if (!firstPage) { 17 accumulatedBody += ','; 18 } 19 accumulatedBody += trimmedBody; 20 21 // Parse headers for pagination info 22 total = parseTotal(response); 23 offset += limit; 24 firstPage = false; 25 } while (offset < total); 26 27 accumulatedBody += ']'; 28 29 // Wrap in full JSON structure expected by wrappers 30 String fullJson = '{"MRData": {"RaceTable": {"Races": ' + accumulatedBody + '}}}'; 31 32 return (F1APIWrappers.ResultAPIWrapper) JSON.deserialize(fullJson, F1APIWrappers.ResultAPIWrapper.class); 33} 34 35

Apex Wrapper Classes Example

To map JSON into Apex, here’s an excerpt of the wrapper classes:

java
1public class F1APIWrappers { 2 public class ResultAPIWrapper { 3 public MRData MRData; 4 } 5 public class MRData { 6 public RaceTable RaceTable; 7 } 8 public class RaceTable { 9 public List<Race> Races; 10 } 11 public class Race { 12 public Integer round; 13 public String raceName; 14 public Circuit Circuit; 15 public List<Result> Results; 16 } 17 public class Circuit { 18 public String circuitId; 19 public String circuitName; 20 } 21 public class Result { 22 public Integer position; 23 public Integer points; 24 public Driver Driver; 25 public Constructor Constructor; 26 } 27 public class Driver { 28 public String driverId; 29 public String givenName; 30 public String familyName; 31 } 32 public class Constructor { 33 public String constructorId; 34 public String name; 35 } 36} 37 38

This structure mirrors the JSON, enabling JSON.deserialize() to populate all nested objects automatically.


Data Upsert with External IDs

To maintain data integrity and avoid duplicates, I used External ID fields in Salesforce. For example:

java
1Race__c raceRecord = new Race__c( 2 Name = race.raceName, 3 Round__c = race.round, 4 External_Id__c = season + '-' + race.round + '-Race' 5); 6 7upsert raceRecord External_Id__c; 8

Similarly, race results have composite keys, like:

java
1Race_Result__c resultRecord = new Race_Result__c( 2 Name = season + '-' + raceRecord.Name + '-' + result.position, 3 Race_Result_External_Id__c = raceRecord.External_Id__c + '-' + result.position 4); 5 6upsert resultRecord Race_Result_External_Id__c;

This logic ensures Salesforce either inserts or updates records correctly without duplication.


Invocable Method for Flow Automation

The process is exposed to Salesforce Flow through an Invocable Apex method, allowing automation or admin-triggered imports:

java
1@InvocableMethod(label='Get Season Data' description='Fetch race results for the season') 2public static List<Results> execute(List<Requests> requests) { 3 List<Results> outputs = new List<Results>(); 4 for (Requests req : requests) { 5 List<F1APIWrappers.Race> races = F1APIService.getResultsBySeason(req.season, 'results'); 6 ProcessedData data = insertOrUpdateRaceRecords(races, String.valueOf(req.season)); 7 insertOrUpdateAllRecords(data); 8 9 Results res = new Results(); 10 res.races = data.races; 11 outputs.add(res); 12 } 13 return outputs; 14} 15

The Flow passes the season year, triggers the import, and stores the processed data — though the data isn’t directly shown in the Flow UI yet.


Error Handling & Logs

Throughout the code, try-catch blocks and debug logs help detect and surface issues:

plain-text
1try { 2 insert currentSeason; 3} catch (DmlException e) { 4 System.debug('Error creating season: ' + e.getMessage()); 5 throw new AuraHandledException('Season creation failed: ' + e.getMessage()); 6} 7

🔧 Summary & Next Steps

This integration is still an MVP and will continue evolving:

  • ✅ Improve JSON validation for optional/missing fields
  • ✅ Add monitoring & logging visibility
  • ✅ Refactor and modularize for maintainability
  • ✅ Incremental updates instead of full re-syncs If you're working on Salesforce integrations with paginated APIs or external data syncs, I’d love to connect! 🙌

📌 Note: The GitHub repository will be shared soon — once the code is cleaned up and properly structured for public release. Stay tuned! 💻🧼

Written by Ricardo SimõesSalesforce + AI developer · Portugal / Remote
Questions about this post, or just want to talk Salesforce and AI? Happy to chat.
0Comments

Comments

Loading animation
→Keep readingAll posts →