Uploading Files With Sugar’s REST API

The standard Sugar API documentation appears to cause issues with the latest version of the API. It appears to return an error:

{"error":"missing_parameter","error_message":"Attachment is missing"}

It also suggests a deprecated CURL call which will return the following warning:

“The usage of the @filename API for file uploading is deprecated. Please use the CURLFile class instead.”

The following example demonstrates how to upload an attachment to a note using the REST API:

/* Initialise */ 
$fileToUpload = “/documents/demo.jpg”; 
$mimetype = “image/jpeg”; 
$filename = “demo.jpg”;
/* Ensure a fully qualified path to the file */ 
/* Create a curl file wrapper */ 
/* Build the POST vars */
$rawPOSTdata = array( 
 “format” => “sugar-html-json”, 
 “delete_if_fails” => false, 
 “oauth_token” => $token, 
 “filename” => $fileData, );
Set up CURL, note the rawPOSTdata should NOT be json encoded, 
and the Content-Type header must be multipart/form-data 
$curl = curl_init(“<target host url goes here>”);
curl_setopt($curl, CURLOPT_POST, true); 
curl_setopt($curl, CURLOPT_HEADER, false); 
curl_setopt($curl, CURLOPT_RETURNTRANSFER, true); 
curl_setopt($curl, CURLOPT_FRESH_CONNECT, 1); 
curl_setopt($curl, CURLOPT_POSTFIELDS, $rawPOSTdata); 
curl_setopt($curl, CURLOPT_HTTPHEADER, array(‘Content-Type: multipart/form-data’, 
 “Cache-Control: no-cache”, 
 “OAuth-Token: $token”));

/* Make the CURL call */ $response = curl_exec($curl);

if (!$response) { die(“Rest Failure.\n”); }


Submit a Comment

Your email address will not be published. Required fields are marked *