Home > Enterprise >  Search Contacts with SendGrid API
Search Contacts with SendGrid API

Time:10-05

https://sendgrid.api-docs.io/v3.0/contacts/search-contacts

I'm attempting to search for a contact as shown in SendGrids docs above. In the body section below I'd like to change the hard coded "[email protected]" to be a variable. Such as email = req.user.email; What is the correct way to do that? Just setting the variable and dropping in 'email' does not work.

    var request = require("request");

    var options = { method: 'POST',
    
    url: 'https://api.sendgrid.com/v3/marketing/contacts/search',
    headers: 
    { 'content-type': 'application/json',
    authorization: 'Bearer SG.key' },
    body: { query: 'email LIKE \'[email protected]\' AND CONTAINS(list_ids, \'6bcc2d0c-ea17-41ba-a4a1-962badsasdas1\')' },
    json: true };
    
    request(options, function (error, response, body) {
    if (error) throw new Error(error);
    
    console.log(body);
    });

CodePudding user response:

Twilio SendGrid developer evangelist here.

Try using string interpolation using back ticks (which, as an added bonus, means you don't have to escape your single quotes), like below:

const email = req.user.email;
const body = `email LIKE '${email}' AND CONTAINS(list_ids, '6bcc2d0c-ea17-41ba-a4a1-962badsasdas1')`;

const options = {
  method: 'POST',
  url: 'https://api.sendgrid.com/v3/marketing/contacts/search',
  headers: {
    'content-type': 'application/json',
    authorization: 'Bearer SG.key'
  },
  body: { query: query },
  json: true
};

request(options, function (error, response, body) {
if (error) throw new Error(error);

console.log(body);
});
  • Related