Lua Requires Chilkat v11.0.0+
Lua
SendGrid: Add or update list contacts and check the import job
See more SendGrid Examples
Use a Marketing Campaigns API key with contact access and the ID of an existing list. A 202 response queues the upsert; it does not confirm that the contacts were saved. Save the job ID and use it to recheck a pending import without submitting the contacts again. The error report may contain contact data; handle it privately.
Add or update contacts ยท Import job status
Chilkat Lua Downloads
local chilkat = require("chilkat")
-- Assumes Chilkat is unlocked. See Global Unlock Sample.
local success = false
local http = chilkat.Http.new()
http.require_ssl_cert_verify = true
-- Supply your API key from protected configuration; AuthToken adds the Bearer prefix.
http.auth_token = "SENDGRID_API_KEY"
local resp = chilkat.HttpResponse.new()
local jobId = ""
if jobId == "" then
local contacts = chilkat.JsonObject.new()
contacts:update_string("list_ids[0]", "YOUR_LIST_UUID")
contacts:update_string("contacts[0].email", "avery@example.com")
contacts:update_string("contacts[0].first_name", "Avery")
contacts:update_string("contacts[1].email", "robin@example.com")
contacts:update_string("contacts[1].first_name", "Robin")
success = http:http_json("PUT", "https://api.sendgrid.com/v3/marketing/contacts", contacts, "application/json", resp)
if not success then
if resp.status_code == 0 then
print(http.last_error_text)
else
print("HTTP " .. resp.status_code .. ": " .. resp.body_str)
end
return
end
if resp.status_code ~= 202 then
print("HTTP " .. resp.status_code .. ": " .. resp.body_str)
return
end
local queued = chilkat.JsonObject.new()
success = queued:load(resp.body_str)
if not success then
print("Unexpected response: expected JSON.")
return
end
if not queued:has_member("job_id") then
print("No job ID returned.")
return
end
jobId = queued:string_of("job_id")
print("Save this import job ID: " .. jobId)
end
http:set_url_var("job", jobId)
success = http:http_no_body("GET", "https://api.sendgrid.com/v3/marketing/contacts/imports/{$job}", resp)
if not success then
if resp.status_code == 0 then
print(http.last_error_text)
else
print("HTTP " .. resp.status_code .. ": " .. resp.body_str)
end
return
end
if resp.status_code ~= 200 then
print("HTTP " .. resp.status_code .. ": " .. resp.body_str)
return
end
local job = chilkat.JsonObject.new()
success = job:load(resp.body_str)
if not success then
print("Unexpected response: expected JSON.")
return
end
local state = job:string_of("status")
if state == "pending" then
print("Still pending. Check again later with jobId = " .. jobId)
return
end
print("Job status: " .. state)
print("Created: " .. job:int_of("results.created_count") .. ", updated: " .. job:int_of("results.updated_count") .. ", errors: " .. job:int_of("results.errored_count"))
if (state == "errored") or (state == "failed") then
print("Review the job before retrying. If present, results.errors_url identifies the private error report.")
end