Skip to main content

Make a Call with APEX

Learning Objectives

After completing this unit, you’ll be able to:

  • Describe different ways of accessing the Pardot API.
  • Make a call to the Pardot API using the Developer Console and APEX.

Now that you’ve learned how calling the Pardot API works, you can try it out yourself. In this unit, you use APEX to make a Pardot API call to query the custom redirect object to return a list of custom redirects and their fields. 

As we said previously, there are many ways to access the Pardot API. And using APEX code is just one way. You can also build your own apps, or use external apps like Postman. The method we show in this unit can’t be used for system-level integrations, but it’s great for test-driving the API. 

Before you get started, log in as a Pardot admin and have a Pardot Business Unit ID if you have those permissions.

Set Up Authentication

Because you’re working in Salesforce, you can use an authentication shortcut for this activity. You create a Visualforce page to create a session, and use the session ID to authenticate to the Pardot API.

  1. Open the developer console.
  2. Create a Visualforce page named SessionPage.
  3. Copy and paste this code:
    <apex:page contentType="application/json">
    {"sessionId":"{!$Api.Session_ID}"}
    </apex:page>
  4. Save the file.

The page returns the sessionID in JSON for the APEX class to call to manage authentication.

Create a Class to Store the API Results

Next, create a class to store the results of the custom redirect query. The class also handles converting JSON response strings into the object fields.

  1. Open the developer console.
  2. Create an APEX class called SamplePardotRequest_SessionID.
  3. Copy and paste this code, then save your work:
public class CustomRedirects {
   public List<Values> values;
   public class Values {
       public Integer id;
       public String salesforceId;
       public Integer folderId;
       public String name;
       public String destinationUrl;
       public Integer campaignId;
       public Integer trackerDomainId;
       public String vanityUrlPath;
       public String vanityUrl;
       public String trackedUrl;
       public String gaSource;
       public String gaMedium;
       public String gaTerm;
       public String gaContent;
       public String gaCampaign;
       public Boolean bitlyIsPersonalized;
       public String bitlyShortUrl;
       public String createdAt;
       public String updatedAt;
       public Integer createdById;
       public Boolean isDeleted;
    }
     public CustomRedirects jsonToObject(String json) {
        System.debug('Parsing String:' + json);
        return (CustomRedirects) System.JSON.deserialize(json, CustomRedirects.class);
     }
}

The APEX code contains these three main components:

  1. A values class that contains all the response fields.
  2. A list of values that contain each query record.
  3. A method call jsonToObject that parses the JSON and set the custom redirect values.

Create a Class to Query Custom Redirects

The next class performs the query and returns a CustomRedirects object. 

  1. Open the developer console.
  2. Create an APEX class called CustomRedirectsQuery.
  3. Copy and paste this code, replacing <insert your BUID> with your Business Unit ID. Then save your work.
public class CustomRedirectsQuery {
   /*End point Url to web service callout*/
   private final static String PARDOT_URL = 'https://pi.demo.pardot.com/api/v5/objects/custom-redirects';
   //Note: If you’re using a Pardot production account, use the domain "pi.pardot.com" instead of "pi.demo.pardot.com"
   private final static String BUID = '<insert your BUID>';
   public CustomRedirects customRedirects;
  //Create a class to parse the sessionID from the APEX page.
  public class SessionId {
    public string sessionId;
  }
   //Get the session ID from the APEX Page
   @AuraEnabled
   public static string getUserSessionId() {
      SessionId sessionJson = new SessionId();
      if(!Test.isRunningTest()){
         sessionJson = (SessionId)JSON.deserialize(Page.SessionPage.getContent().toString(), SessionId.class);
      }
      return sessionJson.sessionId;
   }
   public CustomRedirects customRedirectsQuery(){
      //Set up the authorization header for the API request
      String sessionId = getUserSessionId();
      String authorizationHeader = 'Bearer '+ sessionId;
      //Set up the fields to request
      String reqFields = '?fields=id,name,campaignId,destinationUrl,folderId,trackerDomainId,vanityUrlPath,gaSource,gaMedium,gaTerm,gaContent,gaCampaign,salesforceId,vanityUrl,trackedUrl,bitlyIsPersonalized,bitlyShortUrl,isDeleted,createdAt,updatedAt,createdById,createdById';
      String response = null;
      //Set up the HTTP Classes
      Http http = new Http();
      HttpRequest req = new HttpRequest();
      HttpResponse res = new HttpResponse();
      //Create the HTTPS Request Parameters
      req.setEndpoint(PARDOT_URL + reqFields);
      req.setMethod('GET');
      req.setHeader('Pardot-Business-Unit-Id', BUID);
      req.setHeader('Authorization', authorizationHeader);
      //Print out the request to logs
      System.debug('Request:' + req);
      //Submit the request
      try {
         res = http.send(req);
         response = res.getBody();
         System.debug('Response: ' + response);
         this.customRedirects = new CustomRedirects();
         this.customRedirects = this.customRedirects.jsonToObject(response);
         System.debug('CustomRedirectArray: ' + this.customRedirects.values);
         return this.customRedirects;
      }catch(System.CalloutException e){
         System.debug('Callout Error' + e);
         System.debug(res.getBody());
         return null;
      }
   }
}

The code does the following.

  • Defines the custom redirect endpoint URL.
  • Creates a class to hold the session ID and a method to retrieve the session ID from the Visualforce page you created earlier.
  • Executes the query:
    • Creates the authentication header.
    • Adds the requested fields. Edit this part to return different fields.
    • Initializes the HTTP classes.
    • Creates the HTTPS request.
    • Submits the request.
    • Parses the results into the customRedirects object.

Execute the Code

  1. Open Debug > Open Execute Anonymous Window.
  2. Copy and paste this code:
    CustomRedirectsQuery test = new CustomRedirectsQuery();
    test.customRedirects = test.customRedirectsQuery();
    System.debug('Final Object Output: ' + test.customRedirects);
  3. Mark Open Log.
  4. Click Execute.

After a few seconds, the logs open and you can see the response of your Pardot API call within Salesforce.

Now that you’ve tried a call using APEX, experiment with the code to design your own requests. 

Resources

Keep learning for
free!
Sign up for an account to continue.
What’s in it for you?
  • Get personalized recommendations for your career goals
  • Practice your skills with hands-on challenges and quizzes
  • Track and share your progress with employers
  • Connect to mentorship and career opportunities