Sample code for 30+ languages & platforms
Python Requires Chilkat v11.0.0+

SendGrid: Save and verify a topic opt-out

See more SendGrid Examples

Use this when a signed-in reader turns off Product updates. Look up the configured group before submitting: SendGrid warns that a nonexistent or deleted group can cause a global suppression instead. Keep the group active while processing preferences. Deleting a marketing contact is not a substitute for recording an opt-out.

Add group suppressions ยท Check specific addresses

Chilkat Python Downloads

Python
import sys
import chilkat2

success = False

# Assumes Chilkat is unlocked. See Global Unlock Sample.
success = False
http = chilkat2.Http()
http.RequireSslCertVerify = True
# Supply your API key from protected configuration; AuthToken adds the Bearer prefix.
http.AuthToken = "SENDGRID_API_KEY"
resp = chilkat2.HttpResponse()

# Take the address from the authenticated account and the group ID from configuration.
address = "reader@example.com"
http.SetUrlVar("group","12345")

success = http.HttpNoBody("GET","https://api.sendgrid.com/v3/asm/groups/{$group}",resp)
if (success != True):
    if (resp.StatusCode == 0):
        print(http.LastErrorText)
    else:
        print("HTTP " + str(resp.StatusCode) + ": " + resp.BodyStr)

    sys.exit()

if (resp.StatusCode != 200):
    print("HTTP " + str(resp.StatusCode) + ": " + resp.BodyStr)
    sys.exit()

groupInfo = chilkat2.JsonObject()
success = groupInfo.Load(resp.BodyStr)
if (success != True):
    print("Unexpected response: expected JSON.")
    sys.exit()

if (groupInfo.StringOfEquals("name","Product updates",True) != True):
    print("Unexpected unsubscribe group; no preference was changed.")
    sys.exit()

addresses = chilkat2.JsonObject()
addresses.UpdateString("recipient_emails[0]",address)

success = http.HttpJson("POST","https://api.sendgrid.com/v3/asm/groups/{$group}/suppressions",addresses,"application/json",resp)
if (success != True):
    if (resp.StatusCode == 0):
        print(http.LastErrorText)
    else:
        print("HTTP " + str(resp.StatusCode) + ": " + resp.BodyStr)

    sys.exit()

if (resp.StatusCode != 201):
    print("HTTP " + str(resp.StatusCode) + ": " + resp.BodyStr)
    sys.exit()

success = http.HttpJson("POST","https://api.sendgrid.com/v3/asm/groups/{$group}/suppressions/search",addresses,"application/json",resp)
if (success != True):
    if (resp.StatusCode == 0):
        print(http.LastErrorText)
    else:
        print("HTTP " + str(resp.StatusCode) + ": " + resp.BodyStr)

    sys.exit()

if (resp.StatusCode != 200):
    print("HTTP " + str(resp.StatusCode) + ": " + resp.BodyStr)
    sys.exit()

matches = chilkat2.JsonArray()
success = matches.Load(resp.BodyStr)
if (success != True):
    print("Unexpected response: expected JSON.")
    sys.exit()

if (matches.Size == 1):
    print("Confirmed opt-out: " + matches.StringAt(0))
else:
    print("Opt-out not confirmed. Recheck this group.")