Search code examples
jsonbashcurlpushbullet

Sending SMS using the Pushbullet API via Bash scripting (curl)


I'm working on a cli for the Pushbullet HTTP API using Bash scripting. Sending pushes (notes and links), as well as creating, deleting, and modifying contacts & devices are all straight forward using curl and Bash. However, sending SMS and files are a bit more complex, as both require sending more complex JSON-formatted requests to the server (multiple JSON-formatted requests, in the case of pushing files).

I've tried sending many variations on the following (both with and without escape characters), but the server keeps replying about JSON-formatting errors. The following code is based off of the example given in the Pushbullet HTTP API documentation.

 curl -su $auth_id: -X POST https://api.pushbullet.com/v2/ephemerals --header "Content-Type: application/json" 
      --data-binary '{ "\"type"\": "\"push"\", "\"push"\": { \
      "\"type"\": "\"messaging_extension_reply"\", \
      "\"package_name"\": "\"com.pushbullet.android"\", \
      "\"source_user_iden"\": "\"$source_idens"\", \
      "\"target_device_iden"\": "\"$target_idens"\", \
      "\"conversation_iden"\": "\"$sms_device"\", \
      "\"message"\": "\"Hello"\" \
} }'

Using bash -x, I can see that this is (supposedly) what is being sent to the server:

--data-binary '{"type": "push", "push": { 
"type": "messaging_extension_reply", 
"package_name": "com.pushbullet.android", 
"source_user_iden": "<source_idens>", 
"target_device_iden": "<device_idens>", 
"conversation_iden": "<sms_phone_number>", 
"message": "Hello" } }'

In all cases, the server returns: {"error":{"type":"invalid_request","message":"Failed to parse JSON body.","cat":"(=^‥^=)"}}

What is the appropriate formatting of a JSON request using curl to send an SMS via the Pushbullet API? Am I overlooking something obvious? I'm trying to accomplish this using only curl and Bash, I see no reason why it's not possible (maybe not the fastest or most elegant way, but certainly possible).


Solution

  • I found the solution to my issue so I thought I'd share it. It was actually very simple:

    Because the curl command includes a JSON-formatted response with single quotes, variable expansion was not occurring. This is a limitation (or perhaps a feature) of Bash. So, even though the server responded with { } indicating no errors in the request, the requests were actually being sent without the proper values for parameters, such asuser_iden,source_user_iden, etc.

    Solution: Enclose all variable expansions inside the JSON-formatted request in a double-quote and single-quote, like so:

    "'"$user_idens"'"