Create a post in Blogger with Google Apps Script

后端 未结 1 469
粉色の甜心
粉色の甜心 2020-12-02 01:45

So far I haven\'t found a good code to create posts in Blogger with Google Script.

In the API Console I got the following credentials:

  • Client ID
相关标签:
1条回答
  • 2020-12-02 01:55

    Required reading:

    • ScriptApp#getOauthToken
    • Blogger §post#insert
    • UrlFetchApp#fetch
    • Editing manifest#Setting explicit scopes
    • Switch to standard GCP
    • API Library

    Issue:

    • Usage of asynchronous client side browser samples in the synchronous server side.

    Solution:

    • It is possible to access Blogger api from Google apps script using UrlFetchApp
    • Full OAuth flow can be bypassed using oauth token provided by ScriptApp
    • Include scopes in the appsscript.json manifest file.
    • Switch to a standard GCP and enable the blogger api

    Snippet:

    function createBlogPost(){
      var postUrl = "https://www.googleapis.com/blogger/v3/blogs/blogId/posts";
      var blogId = /*"YOUR_BLOG_ID"*/;
      postUrl = postUrl.replace("blogId",blogId);
      var options = {
        method:"post",
        contentType:"application/json",
        headers: { Authorization: "Bearer "+ ScriptApp.getOAuthToken()},
        muteHttpExceptions: true,
        payload: JSON.stringify({
          title: "Hello from Apps Script!",
          content: "This post is automatically created by Apps script"
        })
      }
      var res = UrlFetchApp.fetch(postUrl, options).getContentText();
      console.log(res);//or Logger.log(res)
    }
    

    Manifest scopes:

    "oauthScopes": [
      "https://www.googleapis.com/auth/blogger",
      "https://www.googleapis.com/auth/script.external_request"
    ]
    
    0 讨论(0)
提交回复
热议问题