Skip to content
Advertisement

How can I POST to multiple IDs from an API endpoint using PHP and CURL?

I am trying to post a message via the Canvas API using PHP.

I believe this is more of a PHP question than Canvas.

The following code WORKS when I include a single userID for a “recipients[]’ (’79’ is a specific user idea and the API sends them a message – like an email).

See below for the API documentation and the issue trying to post to multiple IDs.

$post = [
  'recipients[]' => 79,
  'group_conversation' => true,
  'bulk_message' => true,
  'subject'=>$msg_subject,
  'body'=>$msg_body,
];


$curl = curl_init();
curl_setopt_array($curl, array(
  CURLOPT_URL => $token_url,
  CURLOPT_HTTPHEADER => $header,
  CURLOPT_SSL_VERIFYPEER => false,
  CURLOPT_CUSTOMREQUEST => "POST",
  CURLOPT_POSTFIELDS => $post,
  CURLOPT_RETURNTRANSFER => true
));

$lti_msgresponse = curl_exec($curl);
curl_close($curl);
echo($lti_msgresponse);

Here is the Canvas documentation: https://edu.pretpriemacedu.mk/doc/api/conversations.html#method.conversations.create

Specifically:

recipients[] Required
string
An array of recipient ids. These may be user ids or course/group ids prefixed with “course_” or “group_” respectively, e.g. recipients[]=1&recipients=2&recipients[]=course_3

The API calls for a string to be sent for this “array” (brackets at the end?). You can’t pass multiple “recipients” fields because only the last one will record (duh).

I think a solution might have to do with using http_build_query (see https://www.php.net/http_build_query) to send complex/nested arrays, but I have experimenting with various ways to pack more into “recipients[]” and they all fail.

Any PHP or general API wisdom def appreciated…

Advertisement

Answer

The post params ( specifically “recipients” ) should look like the following

$post = [
    'recipients'         => '59,48,19,55',
    'group_conversation' => true,
    'bulk_message'       => true,
    'subject'            => $msg_subject,
    'body'               => $msg_body,
];

or, perhaps the following: 'recipients' => [59,48,19,55]. But recipients[] would be an odd parameter to pass, as it contains special-characters.

User contributions licensed under: CC BY-SA
10 People found this is helpful
Advertisement