Search code examples
hpcc-eclhpcc

How to send POST request using sendgrip api in HPCC ECL?


Could someone kindly assist me in making a POST request call using the SendGrid API in HPCC ECL? I have diligently referred to the documentation and examples provided in the forum, but I have not come across any specific information or methods regarding making a POST request using the SendGrid API.


Solution

  • There are a couple of things in your sample code preventing the JSON request from being formatted exactly the way the SendGrid API expects.

    Long xpaths within RECORD layouts are great for reading in values, but not for writing out nested data structures. It's better to build out the child data structures explicitly.

    Also, several of the request items are JSON object arrays. Any JSON object arrays should be represented in the output RECORD layouts as child datasets.

    ECL defaults to writing out child datasets with a Dataset/Row layout. You can change this in the xpath of the child dataset. For example {XPATH('content/')}; removes the extra "Row" tag from the default layout; giving us the "content": [] format the API expects.

    For complex output structures it also gets tricky trying to build it all as default values in the RECORD layout. It's better to first build the request as an inline dataset and then pass it to the HTTPCALL.

    Finally, the API-Key needs to be formatted as a bearer token within the authorization header.

    fromRec := RECORD
      STRING email {XPATH('email')};
      STRING name {XPATH('name')}; 
    END;
    
    toRec := RECORD
      STRING email {XPATH('email')};
      STRING name {XPATH('name')}; 
    END;
    
    personalizationsRec := RECORD
      DATASET(toRec) receiver {XPATH('to')};
      STRING subject {XPATH('subject')}; 
    END;
    
    contentRec := RECORD
      STRING type {XPATH('type')}; 
      STRING value {XPATH('value')}; 
    END;
    
    requestRec := RECORD
      fromRec sender {XPATH('from')};
      DATASET(personalizationsRec) personalizations {XPATH('personalizations/')};
      DATASET(contentRec) content {XPATH('content/')};
    END;
    
    
    responseRec := RECORD
      STRING msg; 
    END; 
    
    requestDataset := dataset([{{'[email protected]', 'JDoe'}, [{[{'[email protected]','JD'}], 'Hello, World!'}], [{'text/plain', 'Heya!'}]}], requestRec);
    
    requestRec t(requestRec l) := TRANSFORM
     SELF := l;
    END;
    
    SENDGRID_API_KEY :='<API-Key>';
    SENDGRID_AUTH_HEADER := 'Bearer ' + SENDGRID_API_KEY;
    
    responseRec doResponse := TRANSFORM
      SELF.msg := 'ERROR: ' + failcode + ' ' + failmessage;
    END;
    
    OUTPUT(HTTPCALL(requestDataset, 'https://api.sendgrid.com/v3/mail/send', '', requestRec, t(LEFT), DATASET(responseRec), onFail(doResponse), JSON, LOG, HTTPHEADER('Authorization', SENDGRID_AUTH_HEADER)));
    

    HTH,

    Tony