Access API from PHP&cURL

Hi folks, looking at using PHP & curl to connect to the API. Always getting:

{“jsonrpc”:“2.0”,“error”:{“code”:-32700,“message”:“Parse error”},“id”:null}1

Am I heading in the right direction with the below code?

<?php

$data = array('jsonrpc'=>'2.0',
              'method'=>'getAllProjects',
              'id'=>'1');

$curl = curl_init();
curl_setopt($curl, CURLOPT_URL,"http://localhost/kanboard-master/jsonrpc.php");
curl_setopt($curl, CURLOPT_POST, 1);
curl_setopt($curl, CURLOPT_USERPWD, "jsonrpc:xxx_api_token_removed_xxx");
curl_setopt($curl, CURLOPT_POSTFIELDS, $data);
 
 
$result = curl_exec ($curl);
echo curl_error($curl);
curl_close ($curl);
print $result;
 
?>

Configuration:
Application version: master.d3d55224329681722b52a84b31f141bf78aaa134
PHP version: 7.3.7
PHP SAPI: apache2handler
HTTP Client: cURL
OS version: Windows NT 10.0
Database driver: sqlite
Database version: 3.24.0
Browser: Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/75.0.3770.142 Safari/537.36

You must convert your $data to json

try changing this

to this

curl_setopt($curl, CURLOPT_POSTFIELDS, json_encode($data));

It should work.
But I encourage you to try to use a JsonRPC Client library to abstract this, it is so much easier.

1 Like

Thanks Rafael. Perfect.

Had a look at some JsonRPC client libraries as well as the brilliantly simple Python one on my coding journey with KB but I’m hoping (ha!) that my use for API will be non-complex, also developing on Windows using XAMPP so trying to keep dependencies to a minimum.

For them that come after me this code works fine for (the slightly more complex process of) creating tasks:

<?php

$data = array('jsonrpc'=>'2.0',
              'method'=>'createTask',
              'id'=>1,
			  'params'=> array ('title' => 'Test',
								'project_id' => 1,
								'color_id' => 'green',
								'column_id' => 2));

$curl = curl_init();
curl_setopt($curl, CURLOPT_URL,"http://localhost/kanboard-master/jsonrpc.php");
curl_setopt($curl, CURLOPT_POST, 1);
curl_setopt($curl, CURLOPT_USERPWD, "jsonrpc:xxx_api_token_removed_xxx");
curl_setopt($curl, CURLOPT_POSTFIELDS, json_encode($data));

$result = curl_exec ($curl);
echo curl_error($curl);
curl_close ($curl);
print $result;

?>