function readOnly(count){ }
Starting November 20, the site will be set to read-only. On December 4, 2023,
forum discussions will move to the Trailblazer Community.
+ Start a Discussion
Nithesh NNithesh N 

apex rest callout form-data blob Help

Hi folks...Can you help me recreating this curl command into Rest callout...?
curl --request POST \
  --url https://api.imgur.com/3/image \
  --header 'authorization: Client-ID {{clientId}}' \
  --header 'content-type: multipart/form-data; boundary=----WebKitFormBoundary7MA4YWxkTrZu0gW' \
  --form image=R0lGODlhAQABAIAAAAAAAP/
What I have written so far...
String apiUrl = 'https://api.imgur.com/3/image'; 
        String apiKey = 'f714837c34e1426'; 
        String boundary = '----WebKitFormBoundary7MA4YWxkTrZu0gW';
        HttpRequest req = new HttpRequest();
        Http http = new Http();
        req.setMethod('POST');    
        req.setEndpoint(url);
        Blob bodyValue = file;
        String authorizationHeader = 'Client-ID ' + apiKey;
        req.setHeader('Content-Type', 'multipart/form-data; boundary=' + boundary);
        req.setHeader('Authorization', authorizationHeader);
        req.setBodyAsBlob(bodyValue);
        HTTPResponse res = http.send(req);
        system.debug(res.getBody());
        return res.getBody();

Please help me finish the callout....? The blog post i was referencing is bit confusing. http://blog.deadlypenguin.com/blog/2016/02/09/jira-attaching-a-file-in-salesforce/

Thanks ...


 
NagendraNagendra (Salesforce Developers) 
Hi Niteesh,


I've covered multipart/form data support from Apex(http://www.fishofprey.com/2017/04/steps-required-to-support-posting.html) with respect to the Einstien Predictive Vision service in a blog post.

The short answer is it's a reasonably complicated as you need to manually build up the form data body in code while making careful consideration to ensure the intermediate base 64 encoding doesn't mess up the binary encoding.

You definitely shouldn't be passing the binary data from the file directly off as the request body. It will be missing the required boundary markers.

Instead, have a look at the uploadFile method by Grant Wickman in Post multipart without Base64 Encoding the body(https://salesforce.stackexchange.com/questions/24108/post-multipart-without-base64-encoding-the-body/33326#33326). It shouldn't need much modification to produce what you need. Mostly just adding the Authorization header and getting the response body.

Hope this helps.

Please mark this as solved if it's resolved.

Thanks,
Nagendra