Tom Gullen
Tom Gullen

Reputation: 61727

Add contact and get contact ID in SendGrid

I'm finding this far more difficult than I feel it should be.

I'm migrating over to SendGrid's new marketing features. It's a requirement of our code that when a contact is added into SendGrid, we get the SendGrid contact ID and store it with the associated user in our database. This is so that when the users account is deleted, or they change their email address (it will be unverified so we don't store it in SendGrid as a contact until verified) we can delete the SendGrid contact.

When you add a contact, the request is put into a job and is at some point in the future added to SendGrid. There is no apparent callbacks to our server available, and polling SendGrid every few minutes to try and search for the SendGrid contact ID seems like a horrible design.

What's the best way to get the SendGrid contact ID after adding them as a contact? Polling for the contact ID might lead to some race conditions where contacts have been added and not subsequently removed if the user changes their email address before the contact ID is acquired (and other cases that are hard to design for).

Upvotes: 1

Views: 936

Answers (1)

philnash
philnash

Reputation: 73037

Twilio SendGrid developer evangelist here.

You are right, there is no notification that a contact has been added to your list. You do need to poll the import contacts status endpoint with the job ID until the job is complete. Jobs may take a while as it is possible to submit up to 30,000 contacts in one job.

Once the job has successfully completed, you can then use the get contacts by emails endpoint to get the contact and update your record with the contact ID.

If you have to change a contact but their upload job is not complete yet, you can still make updates to them as it uses the same API to create a new job and updates are keyed on the email address.

If the user changes their email address, then you can create a new job to add a new contact with the new email address. But you will also want to queue a job to delete the old contact once the initial job is complete.

Upvotes: 1

Related Questions