使用带有Apps Script的GitHub API创建新的存储库时,出现错误的响应代码404:
{“消息”:“未找到”,“ documentation_url”:“ https://developer.github.com/v3”}
我正在使用的令牌ID可用于创建新文件,因此我知道令牌ID有效。 另外,我正在使用的用户ID可以与其他一些Apps脚本代码一起创建新文件。
文档给出的网址结尾为:
POST / user / repos
我假设“ user”需要替换为用户名,而“ repos”需要替换为新的repo名称。
我正在尝试的网址是:
https://api.github.com/blueprinter/AAA_NewRepo
我也尝试过网址:
https://api.github.com/blueprinter/repos/AAA_NewRepo
我也尝试过向选项对象添加一个name
键:
name:po.repoName
我还尝试过使用带有name
键的对象将有效负载添加到字符串化有效负载对象:
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;
}
}
答案 0 :(得分:1)
问题出在网址端点上,对于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库添加到您的项目中:
1B7FSrk5Zi6L1rSxxTDgDEUsPzlukDsi4KGuTMorsTQHhGBzBkMun4iDF
,然后单击“选择”按钮。 现在您需要authorize your application on Github并将密钥添加到上述代码中。
现在您已经准备好:
-运行OauthGitHub()
函数
-查看日志,您会找到一个网址登录Github,将其粘贴到浏览器中并登录
-您的凭据将存储在您的AppScript项目中,因此您不必重复此过程。
现在,您可以运行createNewRepo()
并开始像恶魔一样创建Github存储库,或使用Github API的任何其他端点构建新的应用程序脚本函数。
在那里好运