Using httr to POST to Twilio API

I have had success using {httr} to access one of Twilio's APIs. e.g. I have used the code below to grab pages from their "Messages" API:

library(httr)
Twil_dest <- paste0("https://api.twilio.com/2010-04-01/Accounts/",
                    Twilio_SID, # my SID
                    "/Messages.json?PageSize=1000")
d <- GET(Twil_dest,
    authenticate(Twilio_SID, tok)) # my SID and token

They have another API where you can request a job through POST, which they then make accessible to a webhook (please clarify my terminology!). The instructions for that API are here for a variety of languages including curl, java, python, php, etc. For instance, for curl it suggests

curl -X POST https://bulkexports.twilio.com/v1/Exports/Messages/Jobs \
--data-urlencode "Email=you@example.com" \
--data-urlencode "WebhookMethod=POST" \
--data-urlencode "WebhookUrl=https://www.company.com/bulkexporthook" \
--data-urlencode "StartDay=2019-11-20" \
--data-urlencode "EndDay=2019-11-30" \
--data-urlencode "FriendlyName=Export1" \
-u $TWILIO_ACCOUNT_SID:$TWILIO_AUTH_TOKEN

I would like to use httr::POST to submit that request, but I don't know how to format the parameters in the request.

When I have tried putting them in a list inside query(LIST_OF_MY_PARAMETERS), it says all the parameters must be named. When I construct a string where each one is preceded by ? I get a bad request error 400.


POST(
  paste0(
    bulk_dest,
    "?Email=MY@EMAIL.COM",
    "?WebhookMethod=POST",
    glue::glue("?WebhookUrl={webhook}"),
    "?StartDay=2020-01-01",
    "?EndDay=2020-01-10",
    "?FriendlyName=Export1"
  ),
  authenticate(Twilio_SID, tok)
)

Many thanks!
Jon

Why the "?" and paste()? You may be thinking about GET that would encode variables as: http://example.com?param1=value1&param2=value2.

In your case, for POST, I think you just want to put your data in the body, as a simple list. You can use encode="form" to have the equivalent of --data-url-encode if I understand correctly the help for POST(). So, does something like that work?

httr::POST(url = "https://bulkexports.twilio.com/v1/Exports/Messages/Jobs",
           body = list(Email="MY@EMAIL.COM",
                       WebhookMethod="POST",
                       WebhookUrl=webhook,
                       StartDay="2020-01-01",
                       EndDay="2020-01-10",
                       FriendlyName="Export1"),
           encode = "form")

This topic was automatically closed 7 days after the last reply. New replies are no longer allowed.

If you have a query related to it or one of the replies, start a new topic and refer back with a link.

Yes, that worked, once I also added an authenticate() term too. Many thanks!

1 Like