fork download
  1. public class QuidditchContactCreator {
  2. // Define the method to fetch data from the API and process it
  3. public static void fetchAndCreateContacts() {
  4. // Step 1: Get the data from the API
  5. HttpRequest req = new HttpRequest();
  6. req.setEndpoint('https://c...content-available-to-author-only...e.com/api/challenges/json/quidditch-list');
  7. req.setMethod('GET');
  8.  
  9. Http http = new Http();
  10. HttpResponse res = http.send(req);
  11.  
  12. // Step 2: Parse the JSON response
  13. if (res.getStatusCode() == 200) {
  14. String jsonResponse = res.getBody();
  15. Map<String, Object> responseData = (Map<String, Object>)JSON.deserializeUntyped(jsonResponse);
  16.  
  17. // Print the entire JSON object for debugging
  18. System.debug(responseData);
  19.  
  20. // Step 3: Loop through the list of people and create contacts
  21. List<Contact> contactsToInsert = new List<Contact>();
  22. List<Map<String, Object>> personsList = (List<Map<String, Object>>)responseData.get('data');
  23.  
  24. for (Map<String, Object> person : personsList) {
  25. String name = (String)person.get('name');
  26. String house = (String)person.get('house');
  27. String position = (String)person.get('position');
  28.  
  29. // Check if the contact already exists by matching the name
  30. Contact existingContact = [SELECT Id FROM Contact WHERE Name = :name LIMIT 1];
  31.  
  32. if (existingContact == null) {
  33. // Create a new Contact if it doesn't exist
  34. Contact newContact = new Contact();
  35. newContact.Name = name;
  36. newContact.Department = house;
  37. if (String.isNotEmpty(position)) {
  38. newContact.Title = position;
  39. }
  40. contactsToInsert.add(newContact);
  41. }
  42. }
  43.  
  44. // Insert all new contacts
  45. insert contactsToInsert;
  46.  
  47. // Step 4: Query the created contacts to get their details and print them
  48. List<Contact> createdContacts = [SELECT Name, Title, Department FROM Contact WHERE Id IN :contactsToInsert];
  49. for (Contact c : createdContacts) {
  50. System.debug('Contact: ' + c.Name + ', Title: ' + c.Title + ', Department: ' + c.Department);
  51. }
  52.  
  53. // Step 5: Delete the newly created contacts
  54. delete contactsToInsert;
  55. } else {
  56. System.debug('Error fetching data: ' + res.getStatus());
  57. }
  58. }
  59. }
  60.  
Success #stdin #stdout #stderr 0.02s 9080KB
stdin
Standard input is empty
stdout
Object: UndefinedObject error: did not understand #QuidditchContactCreator
MessageNotUnderstood(Exception)>>signal (ExcHandling.st:254)
UndefinedObject class(Object)>>doesNotUnderstand: #QuidditchContactCreator (SysExcept.st:1448)
UndefinedObject>>executeStatements (prog:1)
stderr
./prog:2: parse error, expected '}'
./prog:60: Unterminated string, attempting recovery