public class QuidditchContactCreator {
// Define the method to fetch data from the API and process it
public static void fetchAndCreateContacts() {
// Step 1: Get the data from the API
HttpRequest req = new HttpRequest();
req.setEndpoint('https://c...content-available-to-author-only...e.com/api/challenges/json/quidditch-list');
req.setMethod('GET');
Http http = new Http();
HttpResponse res = http.send(req);
// Step 2: Parse the JSON response
if (res.getStatusCode() == 200) {
String jsonResponse = res.getBody();
Map<String, Object> responseData = (Map<String, Object>)JSON.deserializeUntyped(jsonResponse);
// Print the entire JSON object for debugging
System.debug(responseData);
// Step 3: Loop through the list of people and create contacts
List<Contact> contactsToInsert = new List<Contact>();
List<Map<String, Object>> personsList = (List<Map<String, Object>>)responseData.get('data');
for (Map<String, Object> person : personsList) {
String name = (String)person.get('name');
String house = (String)person.get('house');
String position = (String)person.get('position');
// Check if the contact already exists by matching the name
Contact existingContact = [SELECT Id FROM Contact WHERE Name = :name LIMIT 1];
if (existingContact == null) {
// Create a new Contact if it doesn't exist
Contact newContact = new Contact();
newContact.Name = name;
newContact.Department = house;
if (String.isNotEmpty(position)) {
newContact.Title = position;
}
contactsToInsert.add(newContact);
}
}
// Insert all new contacts
insert contactsToInsert;
// Step 4: Query the created contacts to get their details and print them
List<Contact> createdContacts = [SELECT Name, Title, Department FROM Contact WHERE Id IN :contactsToInsert];
for (Contact c : createdContacts) {
System.debug('Contact: ' + c.Name + ', Title: ' + c.Title + ', Department: ' + c.Department);
}
// Step 5: Delete the newly created contacts
delete contactsToInsert;
} else {
System.debug('Error fetching data: ' + res.getStatus());
}
}
}