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

SendGrid: Report daily requests, deliveries, bounces, and blocks

See more SendGrid Examples

Retrieve seven completed UTC dates and print one row per date. The counts are account-level aggregates; a day’s delivered count does not identify which messages sent that day were delivered.

Global email statistics

Chilkat PowerBuilder Downloads

PowerBuilder
integer li_rc
long li_Success
oleobject loo_Http
oleobject loo_Resp
oleobject loo_Day
oleobject loo_Days
oleobject loo_Row
long i

li_Success = 0

//  Assumes Chilkat is unlocked. See Global Unlock Sample.
li_Success = 0
loo_Http = create oleobject
li_rc = loo_Http.ConnectToNewObject("Chilkat.Http")
if li_rc < 0 then
    destroy loo_Http
    MessageBox("Error","Connecting to COM object failed")
    return
end if
loo_Http.RequireSslCertVerify = 1
//  Supply your API key from protected configuration; AuthToken adds the Bearer prefix.
loo_Http.AuthToken = "SENDGRID_API_KEY"
loo_Resp = create oleobject
li_rc = loo_Resp.ConnectToNewObject("Chilkat.HttpResponse")

loo_Day = create oleobject
li_rc = loo_Day.ConnectToNewObject("Chilkat.CkDateTime")

loo_Day.SetFromCurrentSystemTime()
loo_Day.AddDays(-1)
loo_Http.SetUrlVar("end",loo_Day.GetAsIso8601("YYYY-MM-DD",0))
loo_Day.AddDays(-6)
loo_Http.SetUrlVar("start",loo_Day.GetAsIso8601("YYYY-MM-DD",0))

li_Success = loo_Http.HttpNoBody("GET","https://api.sendgrid.com/v3/stats?start_date={$start}&end_date={$end}&aggregated_by=day",loo_Resp)
if li_Success <> 1 then
    if loo_Resp.StatusCode = 0 then
        Write-Debug loo_Http.LastErrorText
    else
        Write-Debug "HTTP " + string(loo_Resp.StatusCode) + ": " + loo_Resp.BodyStr
    end if

    destroy loo_Http
    destroy loo_Resp
    destroy loo_Day
    return
end if

if loo_Resp.StatusCode <> 200 then
    Write-Debug "HTTP " + string(loo_Resp.StatusCode) + ": " + loo_Resp.BodyStr
    destroy loo_Http
    destroy loo_Resp
    destroy loo_Day
    return
end if

loo_Days = create oleobject
li_rc = loo_Days.ConnectToNewObject("Chilkat.JsonArray")

li_Success = loo_Days.Load(loo_Resp.BodyStr)
if li_Success <> 1 then
    Write-Debug "Unexpected response: expected JSON."
    destroy loo_Http
    destroy loo_Resp
    destroy loo_Day
    destroy loo_Days
    return
end if

Write-Debug "Date,Requests,Delivered,Bounces,Blocks"
loo_Row = create oleobject
li_rc = loo_Row.ConnectToNewObject("Chilkat.JsonObject")

i = 0
do while (i < loo_Days.Size)
    loo_Days.ObjectAt2(i,loo_Row)
    Write-Debug loo_Row.StringOf("date") + "," + string(loo_Row.IntOf("stats[0].metrics.requests")) + "," + string(loo_Row.IntOf("stats[0].metrics.delivered")) + "," + string(loo_Row.IntOf("stats[0].metrics.bounces")) + "," + string(loo_Row.IntOf("stats[0].metrics.blocks"))
    i = i + 1
loop


destroy loo_Http
destroy loo_Resp
destroy loo_Day
destroy loo_Days
destroy loo_Row