使用 Apps 脚本创建新的 GitHub 存储库 (repo) - 错误 - 404 - {"message":"Not Found","documentation_url":"https://developer.github.com/v3"}
Create new GitHub repository (repo) using Apps Script - Error - 404 - {"message":"Not Found","documentation_url":"https://developer.github.com/v3"}
在使用 GitHub API 和 Apps 脚本创建新的存储库时,我收到响应代码 404,错误为:
{"message":"Not Found","documentation_url":"https://developer.github.com/v3"}
我使用的令牌 ID 可用于创建新文件,因此我知道令牌 ID 是有效的。
此外,我使用的用户 ID 可用于使用其他一些 Apps 脚本代码创建新文件。
文档给出了 url 结尾:
POST /user/repos
我假设 "user" 需要替换为用户名,"repos" 需要替换为新的存储库名称。
我正在尝试的 url 是:
https://api.github.com/blueprinter/AAA_NewRepo
我也试过 url:
https://api.github.com/blueprinter/repos/AAA_NewRepo
我也试过向选项对象添加 name
键:
name:po.repoName
我也尝试过将带有 name
键的对象添加到 stringify 有效负载对象中:
data = {
name:po.repoName
}
payload = JSON.stringify(data);
options = {
method: 'post',
muteHttpExceptions: true,
contentType: "application/json",
headers: {
Authorization: "Bearer " + myToken
},
responseType: 'json',
payload:payload
}
代码:
function createNewRepo_(po) {
try{
var data,myToken,options,payload,rslt,rspnsCode,apiBaseUrl,url;
/*
https://developer.github.com/v3/repos/#create
POST /user/repos -
po.userName - The user name in the GitHub account
po.repoName - The name of the repository to put the file into
*/
//Logger.log('po: ' + JSON.stringify(po))
apiBaseUrl = 'https://api.github.com';//Every url must have this at the beginning
if (!po.userName) {
po.userName = getMyGitHubInfo_('userName');
}
url = apiBaseUrl + "/" + po.userName + "/" + po.repoName;
Logger.log('url 23: ' + url)
myToken = getGitHubToken();
payload = JSON.stringify(data);
options = {
method: 'post',
muteHttpExceptions: true,
contentType: "application/json",
headers: {
Authorization: "Bearer " + myToken
},
responseType: 'json'
}
//Logger.log('options 39: ' + JSON.stringify(options))
rslt = UrlFetchApp.fetch(url,options);
rspnsCode = rslt.getResponseCode();
Logger.log('rspnsCode 44: ' + rspnsCode)
if (rspnsCode !== 200 && rspnsCode !== 201) {
throw new Error('Response coming back from GitHub is: ' + rspnsCode + "\n\n" + rslt.getContentText());
}
Logger.log('rslt.getContentText(): ' + rslt.getContentText())
Logger.log('typeof rslt: ' + typeof rslt)
data = JSON.parse(rslt);//Even though the returned value is an object it must be parsed into JSON
Logger.log('data' + JSON.stringify(data))
}catch(e) {
Logger.log("Error: " + e.message + "\nStack: " + e.stack)
//errorHandling(e);//Run centralized error handling function
return false;
}
}
function getMyGitHubInfo_(k) {
var o;
o = {
userName:'git_hub_user_ID_Here',//Your user name
}
if (k) {
return o[k];
} else {
return o;
}
}
问题出在 url 端点上,creating repositories 应该始终是 https://api.github.com/user/repos
。
我构建了一个简化示例来展示如何使用 AppsScript 和 Github API:
创建存储库
function createNewRepo() {
try {
apiBaseUrl = 'https://api.github.com/user/repos';
options = {
method: 'post',
muteHttpExceptions: true,
contentType: "application/json",
headers: {
Authorization: "Bearer " + getService().getAccessToken(),
},
responseType: 'json',
payload: JSON.stringify({
"name": "Hellosssss-World",
"description": "This is your first repository",
"homepage": "https://github.com",
"private": false,
"has_issues": true,
"has_projects": true,
"has_wiki": true
})
}
var response = UrlFetchApp.fetch(apiBaseUrl,options);
var responseCode = response.getResponseCode();
data = JSON.parse(response);//Even though the returned value is an object it must be parsed into JSON
if (responseCode !== 200 && responseCode !== 201) {
throw new Error('Response coming back from GitHub is: ' + responseCode + "\n\n" + response.getContentText());
}
else {
Logger.log('A new repository was succesfully created');
Logger.log('Name: ' + data.name);
Logger.log('Url: ' + data.url);
}
}
catch(e) {
Logger.log("Error: " + e.message + "\nStack: " + e.stack)
//errorHandling(e);//Run centralized error handling function
}
}
但是对于 运行 这个功能你必须经过身份验证,为此,我们可以使用 this code sample 通过 AppsScript 在 Github 上进行身份验证,再次使用此代码在您的 AppsScript 项目中:
var CLIENT_ID = 'YOUR_CLIENT_ID';
var CLIENT_SECRET = 'YOUR_CLIENT_SECRET_ID';
/**
* Authorizes and makes a request to the GitHub API.
*/
function OauthGitHub() {
var service = getService();
if (service.hasAccess()) {
var url = 'https://api.github.com/user/repos';
var response = UrlFetchApp.fetch(url, {
headers: {
Authorization: 'Bearer ' + service.getAccessToken()
}
});
var result = JSON.parse(response.getContentText());
Logger.log(JSON.stringify(result, null, 2));
} else {
var authorizationUrl = service.getAuthorizationUrl();
Logger.log('Open the following URL and re-run the script: %s',
authorizationUrl);
}
}
/**
* Reset the authorization state, so that it can be re-tested.
*/
function reset() {
getService().reset();
}
/**
* Configures the service.
*/
function getService() {
return OAuth2.createService('GitHub')
// Set the endpoint URLs.
.setAuthorizationBaseUrl('https://github.com/login/oauth/authorize')
.setTokenUrl('https://github.com/login/oauth/access_token')
// Set the client ID and secret.
.setClientId(CLIENT_ID)
.setClientSecret(CLIENT_SECRET)
// Set the name of the callback function that should be invoked to
// complete the OAuth flow.
.setCallbackFunction('authCallback')
// Set the property store where authorized tokens should be persisted.
.setPropertyStore(PropertiesService.getUserProperties())
.setScope('repo');
}
/**
* Handles the OAuth callback.
*/
function authCallback(request) {
var service = getService();
var authorized = service.handleCallback(request);
if (authorized) {
return HtmlService.createHtmlOutput('Success!');
} else {
return HtmlService.createHtmlOutput('Denied.');
}
}
/**
* Logs the redict URI to register.
*/
function logRedirectUri() {
Logger.log(OAuth2.getRedirectUri());
}
请记住,您必须将 Oauth 库添加到您的项目中:
- 点击菜单项"Resources > Libraries..."
- 在"Find a Library"文本框中
- 输入脚本 ID
1B7FSrk5Zi6L1rSxxTDgDEUsPzlukDsi4KGuTMorsTQHhGBzBkMun4iDF
并单击 "Select" 按钮。
- 在下拉框中选择一个版本(通常
最好选择最新版本)。
- 单击 "Save" 按钮。
现在您需要 authorize your application on Github 并将密钥添加到上述代码中。
现在你准备好了:
- 运行 OauthGitHub()
函数
- 检查日志,你会发现 url 登录 Github,将其粘贴到你的浏览器并登录
- 您的凭据将存储在您的 AppScript 项目中,因此您不必重复此过程。
现在您可以 运行 createNewRepo()
并开始像恶魔一样创建 Github 存储库或使用 Github [=55] 的任何其他端点构建新的应用程序脚本函数=].
祝你好运。
在使用 GitHub API 和 Apps 脚本创建新的存储库时,我收到响应代码 404,错误为:
{"message":"Not Found","documentation_url":"https://developer.github.com/v3"}
我使用的令牌 ID 可用于创建新文件,因此我知道令牌 ID 是有效的。 此外,我使用的用户 ID 可用于使用其他一些 Apps 脚本代码创建新文件。
文档给出了 url 结尾:
POST /user/repos
我假设 "user" 需要替换为用户名,"repos" 需要替换为新的存储库名称。
我正在尝试的 url 是:
https://api.github.com/blueprinter/AAA_NewRepo
我也试过 url:
https://api.github.com/blueprinter/repos/AAA_NewRepo
我也试过向选项对象添加 name
键:
name:po.repoName
我也尝试过将带有 name
键的对象添加到 stringify 有效负载对象中:
data = {
name:po.repoName
}
payload = JSON.stringify(data);
options = {
method: 'post',
muteHttpExceptions: true,
contentType: "application/json",
headers: {
Authorization: "Bearer " + myToken
},
responseType: 'json',
payload:payload
}
代码:
function createNewRepo_(po) {
try{
var data,myToken,options,payload,rslt,rspnsCode,apiBaseUrl,url;
/*
https://developer.github.com/v3/repos/#create
POST /user/repos -
po.userName - The user name in the GitHub account
po.repoName - The name of the repository to put the file into
*/
//Logger.log('po: ' + JSON.stringify(po))
apiBaseUrl = 'https://api.github.com';//Every url must have this at the beginning
if (!po.userName) {
po.userName = getMyGitHubInfo_('userName');
}
url = apiBaseUrl + "/" + po.userName + "/" + po.repoName;
Logger.log('url 23: ' + url)
myToken = getGitHubToken();
payload = JSON.stringify(data);
options = {
method: 'post',
muteHttpExceptions: true,
contentType: "application/json",
headers: {
Authorization: "Bearer " + myToken
},
responseType: 'json'
}
//Logger.log('options 39: ' + JSON.stringify(options))
rslt = UrlFetchApp.fetch(url,options);
rspnsCode = rslt.getResponseCode();
Logger.log('rspnsCode 44: ' + rspnsCode)
if (rspnsCode !== 200 && rspnsCode !== 201) {
throw new Error('Response coming back from GitHub is: ' + rspnsCode + "\n\n" + rslt.getContentText());
}
Logger.log('rslt.getContentText(): ' + rslt.getContentText())
Logger.log('typeof rslt: ' + typeof rslt)
data = JSON.parse(rslt);//Even though the returned value is an object it must be parsed into JSON
Logger.log('data' + JSON.stringify(data))
}catch(e) {
Logger.log("Error: " + e.message + "\nStack: " + e.stack)
//errorHandling(e);//Run centralized error handling function
return false;
}
}
function getMyGitHubInfo_(k) {
var o;
o = {
userName:'git_hub_user_ID_Here',//Your user name
}
if (k) {
return o[k];
} else {
return o;
}
}
问题出在 url 端点上,creating repositories 应该始终是 https://api.github.com/user/repos
。
我构建了一个简化示例来展示如何使用 AppsScript 和 Github API:
创建存储库function createNewRepo() {
try {
apiBaseUrl = 'https://api.github.com/user/repos';
options = {
method: 'post',
muteHttpExceptions: true,
contentType: "application/json",
headers: {
Authorization: "Bearer " + getService().getAccessToken(),
},
responseType: 'json',
payload: JSON.stringify({
"name": "Hellosssss-World",
"description": "This is your first repository",
"homepage": "https://github.com",
"private": false,
"has_issues": true,
"has_projects": true,
"has_wiki": true
})
}
var response = UrlFetchApp.fetch(apiBaseUrl,options);
var responseCode = response.getResponseCode();
data = JSON.parse(response);//Even though the returned value is an object it must be parsed into JSON
if (responseCode !== 200 && responseCode !== 201) {
throw new Error('Response coming back from GitHub is: ' + responseCode + "\n\n" + response.getContentText());
}
else {
Logger.log('A new repository was succesfully created');
Logger.log('Name: ' + data.name);
Logger.log('Url: ' + data.url);
}
}
catch(e) {
Logger.log("Error: " + e.message + "\nStack: " + e.stack)
//errorHandling(e);//Run centralized error handling function
}
}
但是对于 运行 这个功能你必须经过身份验证,为此,我们可以使用 this code sample 通过 AppsScript 在 Github 上进行身份验证,再次使用此代码在您的 AppsScript 项目中:
var CLIENT_ID = 'YOUR_CLIENT_ID';
var CLIENT_SECRET = 'YOUR_CLIENT_SECRET_ID';
/**
* Authorizes and makes a request to the GitHub API.
*/
function OauthGitHub() {
var service = getService();
if (service.hasAccess()) {
var url = 'https://api.github.com/user/repos';
var response = UrlFetchApp.fetch(url, {
headers: {
Authorization: 'Bearer ' + service.getAccessToken()
}
});
var result = JSON.parse(response.getContentText());
Logger.log(JSON.stringify(result, null, 2));
} else {
var authorizationUrl = service.getAuthorizationUrl();
Logger.log('Open the following URL and re-run the script: %s',
authorizationUrl);
}
}
/**
* Reset the authorization state, so that it can be re-tested.
*/
function reset() {
getService().reset();
}
/**
* Configures the service.
*/
function getService() {
return OAuth2.createService('GitHub')
// Set the endpoint URLs.
.setAuthorizationBaseUrl('https://github.com/login/oauth/authorize')
.setTokenUrl('https://github.com/login/oauth/access_token')
// Set the client ID and secret.
.setClientId(CLIENT_ID)
.setClientSecret(CLIENT_SECRET)
// Set the name of the callback function that should be invoked to
// complete the OAuth flow.
.setCallbackFunction('authCallback')
// Set the property store where authorized tokens should be persisted.
.setPropertyStore(PropertiesService.getUserProperties())
.setScope('repo');
}
/**
* Handles the OAuth callback.
*/
function authCallback(request) {
var service = getService();
var authorized = service.handleCallback(request);
if (authorized) {
return HtmlService.createHtmlOutput('Success!');
} else {
return HtmlService.createHtmlOutput('Denied.');
}
}
/**
* Logs the redict URI to register.
*/
function logRedirectUri() {
Logger.log(OAuth2.getRedirectUri());
}
请记住,您必须将 Oauth 库添加到您的项目中:
- 点击菜单项"Resources > Libraries..."
- 在"Find a Library"文本框中
- 输入脚本 ID
1B7FSrk5Zi6L1rSxxTDgDEUsPzlukDsi4KGuTMorsTQHhGBzBkMun4iDF
并单击 "Select" 按钮。 - 在下拉框中选择一个版本(通常 最好选择最新版本)。
- 单击 "Save" 按钮。
现在您需要 authorize your application on Github 并将密钥添加到上述代码中。
现在你准备好了:
- 运行 OauthGitHub()
函数
- 检查日志,你会发现 url 登录 Github,将其粘贴到你的浏览器并登录
- 您的凭据将存储在您的 AppScript 项目中,因此您不必重复此过程。
现在您可以 运行 createNewRepo()
并开始像恶魔一样创建 Github 存储库或使用 Github [=55] 的任何其他端点构建新的应用程序脚本函数=].
祝你好运。