Mio Winter
Mio Winter

Reputation: 33

Using Google Apps Script and the Pastebin.com API to post a paste

I am trying to make a Pastebin.com paste using Google Apps Script from the spreadsheet script editor. Can anyone tell me what I'm doing wrong?

function postPastebinPost() {
  var options, url, apiKey, payload, response;

  apiKey = <api key goes here>;
  payload = 'Hello World';

  options = {
    'method' : 'post',
    'payload' : payload
  };

  url = 'https://pastebin.com/api/api_post.php'
    + '?api_dev_key=' + apiKey
    + '&api_option=paste'
    + '&api_paste_code=' + encodeURIComponent(payload);

  response = UrlFetchApp.fetch(url, options);
  Logger.log(response);
}

I run this and my log reads Bad API request, invalid api_option. I've searched for solutions but I have not found any.

Documentation:

Pastebin.com API

• Google Apps Script's UrlFetchApp Class

Upvotes: 3

Views: 1077

Answers (2)

user8617716
user8617716

Reputation:

The following is in case the user wants to create a new paste as part of their own Pastebin account (and not «Paste as a guest»). It's just an adaptation of Amit Agarwal's answer.

function postPastebinPost() {
  var title = 'abc';
  var contents = 'Hello World \n next line of content  \n more text';
  var payload = {
    api_dev_key: 'aa6f3ab...', // https://pastebin.com/api#1
    api_option: 'paste',
    api_paste_name: title,
    api_paste_code: contents,
    api_paste_private: '0', // public paste
    api_user_name: 'diccionario...', // name of your Pastebin account
    api_user_password: 'dk398d...', // password to your Pastebin account
    api_user_key: '39dk3...', // https://pastebin.com/api/api_user_key.html
    };
  var options = {
    method : 'POST',
    payload: payload
    };
  var url = 'https://pastebin.com/api/api_post.php';
  var response = UrlFetchApp.fetch(url, options);
  Logger.log(response.getContentText());
}

The whole documentation is at https://pastebin.com/api.

Upvotes: 0

Amit Agarwal
Amit Agarwal

Reputation: 11268

The parameters should be passed in the payload of the POST request.

function postPastebinPost() {

  var apiKey = 'YOUR KEY GOES HERE';
  var text = 'Hello World';

  var payload = {
    api_dev_key: apiKey,
    api_option: 'paste',
    api_paste_code:  text
  };

  var options = {
    method : 'POST',
    payload: payload
  };

  var url = 'https://pastebin.com/api/api_post.php';

  var response = UrlFetchApp.fetch(url, options);
  Logger.log(response.getContentText());
}

Upvotes: 4

Related Questions