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"
]