Github REST API full example - rest

I would like to create a new file in the my github repository by using github REST API. I've found following link, but honestly I don't understand it((
As I understand, I could do POST
url: https://api.github.com/repos/MyUserName/MyRepositoryName
headers:
Accept: application/vnd.github.v3+json
body:
{
"message": "my commit message",
"committer": {
"name": "My name",
"email": "my email"
},
"content": "base64encoded"
}
But it doesn't work. Could you please, write
1) which url should I call
2) which headers this request should contains
3) what body should be

You were close:) Lets assume, that
1) your login: YourUsername
2) your access token: 123a321
3) repository to be updated: YourRepo
4) file to be created: file.txt
5) folder that will contains new file: f1/f2
According to those assumptions your request should be following:
type : PUT
url : https://api.github.com/repos/YourUsername/YourRepo/contents/f1/f2/file.txt
headers :
{
"Content-Type" : "application/vnd.github.v3+json",
"Authorization" : "token 123a321"
}
body :
{
"message": "my commit message",
"committer": {
"name": "My name",
"email": "my email"
},
"content": "base64encoded"
}
UPD
If you write in java, you can use GitHubFileAPI library, that I recently pushed to the maven central repository.

Solution: In order to perform action on github api you can use curl
according to Github doc:
first make sure you have specific privileges and authentication token generated to your account in order to interact with Github api:
profile Settings -> Developer Settings -> Personal access tokens -> Generate new token
the command should be in http PUT method on path /repos/:owner/:repo/contents/:path
The required params for editing or adding new files (according to api)
message (String), Content (String) and sha(String), additional params are branch(String) commiter(String) and author(String)
Lets perform some curl message in order to perform your action, the simple formula for this case would be:
curl --user <userName>:<token>
--data '{"key":"value"}'
--header <HeaderType>
--request <HTTPMethod>
<fullURL>
for demonstration lets fill some details:
curl --user johnDoe:abc123!##
--data '{"message":"my message","content":"my content","sha":"abcjfhtenf736gd843ji43903"}'
--header Content-Type:application/json
--request PUT
https://api.github.com/repos/MyOrganization/MyCoolApp/contents/app/models
Verify on Github the content has been inserted correctly to your branch

Related

Apps Script Execution API 404 error with devMode: true

When requesting POST https://script.googleapis.com/v1/scripts/{script_id}:run with devMode: true I get a 404 error. I can run the script successfully with devMode: false.
Although other people (1, 2) have raised this issue, none of the other solutions work. I keep getting an HTTP 404 Not Found error whenever my request comes with devMode: true.
I have performed the following steps:
created a new Google account
created a Cloud project
set up an OAuth consent screen for the project
authorized the domain for the app (just in case)
created 'Desktop' OAuth2 credentials for this project with OAuth scopes listed below
enables Apps Script API on the project
created a standalone Apps Script using Google Drive ("Test 1")
set the Cloud Platform project ID for the script Test 1
deploy the script Test 1 as an API executable, with access to "Anyone"
obtain a valid access token with the exact same scopes listed below and used for the OAuth consent screen configuration in the Cloud project. The token is for the same account that owns the script and the cloud project.
After performing the above steps, running with devMode: false was successful, but when switching to devMode: true it failed.
The same happens when I set access to "Only Me".
To make clear the steps that I took, I provide a full flow of screenshots taken along the way (open image in new window to zoom in; the flows to top-to-bottom; the three columns from left to right are: Cloud console project flow; Apps Script flow; OAuth2 flow):
At the request of #ziganotschka I made a simpler copy of my Apps Script function:
function test() {
return 1;
}
And the appsscript.json manifest is:
{
"timeZone": "Asia/Jerusalem",
"dependencies": {
},
"exceptionLogging": "STACKDRIVER",
"runtimeVersion": "V8"
}
The code for obtaining the OAuth2 token and running the script, in Python:
##
# %%
import requests
import urllib
import json
client_id = '...'
client_secret = '...'
script_id = '...'
is_dev_mode = True # True or False
##
# %% Initiate OAuth2
url = 'https://accounts.google.com/o/oauth2/auth?' + urllib.parse.urlencode({
'client_id': client_id,
'redirect_uri': 'urn:ietf:wg:oauth:2.0:oob',
'response_type': 'code',
'scope': ' '.join([
'https://www.googleapis.com/auth/userinfo.email',
'https://www.googleapis.com/auth/userinfo.profile',
'openid',
'https://www.googleapis.com/auth/documents',
'https://www.googleapis.com/auth/drive',
'https://www.googleapis.com/auth/drive.scripts',
'https://www.googleapis.com/auth/script.external_request',
'https://www.googleapis.com/auth/script.projects',
'https://www.googleapis.com/auth/script.scriptapp',
'https://www.googleapis.com/auth/script.container.ui'
])
}, doseq=True)
print(url)
##
# %% Exchange authorization code with access and refresh tokens
print('Enter authorization token: ', end='')
authorization_code = input()
authorization_token_response = requests.post('https://accounts.google.com/o/oauth2/token', data={
'code': authorization_code,
'client_id': client_id,
'client_secret': client_secret,
'redirect_uri': 'urn:ietf:wg:oauth:2.0:oob',
'grant_type': 'authorization_code'
})
authorization_token_response.raise_for_status()
authorization_data = authorization_token_response.json()
access_token = authorization_data["access_token"]
refresh_token = authorization_data["refresh_token"]
##
# %%
response = requests.post(f'https://script.googleapis.com/v1/scripts/{script_id}:run',
data=json.dumps({
"function": "test",
"parameters": [],
"devMode": is_dev_mode
}),
headers={
'content-type': 'application/json',
'authorization': f'Bearer {access_token}'
}
)
response.raise_for_status()
print(response.content)
I get similar results for a curl call:
$ curl 'https://script.googleapis.com/v1/scripts/x...x:run' -X POST -H 'content-type: application/json' -d '{"function":"test","parameters":[],"devMode":true}' -H 'authorization: Bearer x...x' --silent
{
"error": {
"code": 404,
"message": "Requested entity was not found.",
"status": "NOT_FOUND"
}
}
I consider this as an issue report, as Google mention that they use Stack Overflow to field technical questions for Apps Script API. As well as a beacon to anyone who has been frustrated with this issue.
Any my question would be -- am doing anything wrong?
As an aside question: what's the difference between substituting script_id for the Current API ID (as suggested in 'How to Execute a function guide'; this identifier seems to be identical to the script Project key under File > Project properties) and the Script's Drive file ID (suggested everywhere else; this seems to be identical to Script ID)?

How to create a secret-text type of credential for Jenkins using Jenkins API?

So far, I'm using the credentials plugin on Jenkins and I do a POST to {JENKINS_URL}/credentials/store/system/domain/_/createCredentials using a credentials.xml that looks like this:
<com.cloudbees.plugins.credentials.impl.UsernamePasswordCredentialsImpl>
<scope>GLOBAL</scope>
<id>my-test-cred</id>
<description>This is an example from REST API</description>
<username>xyz-test</username>
<password>
xyz-yay
</password></com.cloudbees.plugins.credentials.impl.UsernamePasswordCredentialsImpl>
and it successfully creates a credential of type username:password.
But suppose I want to create a credential of type secret-text which would hold a token or a secret, like say, a GitHub token, how can I make a credentials.xml for that kind? I've searched high and low and I cannot find a definitive guide here :-(
I used successfully the class from #rkparmar's proposal with XML format to create a secret text credential in Jenkins.
<org.jenkinsci.plugins.plaincredentials.impl.StringCredentialsImpl>
<scope>GLOBAL</scope>
<id>testID</id>
<secret>thisIsAtest</secret>
<description>TEST</description>
</org.jenkinsci.plugins.plaincredentials.impl.StringCredentialsImpl>
Agree! It is difficult to find xml to credential for secret-text. If you have way to get xml from .json than please find .json below to create credentials for secret-text
curl -X POST 'http://user:token#jenkins_server:8080/credentials/store/system/domain/_/createCredentials' \
--data-urlencode 'json={
"": "0",
"credentials": {
"scope": "GLOBAL",
"id": "myid",
"secret": "mysecret",
"description": "mydescription",
"$class": "org.jenkinsci.plugins.plaincredentials.impl.StringCredentialsImpl"
}
}

Cloud Functions REST API: Creating a new action from a zip file

I'm trying to create a nodejs function from a zip file and through the REST API using the following curl:
curl --request PUT --url 'https://my:credentials#openwhisk.eu-gb.bluemix.net/api/v1/namespaces/mynamespace/actions/my_action_name?overwrite=true' --header 'accept: application/json' --header 'content-type: application/json' --data '{"annotations":[{"key":"exec","value":"nodejs:10"},{"key":"web-export","value":true}],"exec":{"kind":"nodejs:10","init":"./action.zip"},"parameters":[{"key":"message","value":"Hello World"}]}'
As a result I get an error:
"error":"The request content was malformed:\n'code' must be a string or attachment object defined in 'exec' for 'nodejs:10' actions"
Is it possible to get an example of how to create a new action from a zip file and through the REST API? Thank you.
You have to base64 encode your .zip file and then pass it as a code parameter. I have written a shell script(bash) to encode and also create an action called 'action'. Save the script as create.sh and execute the script ./create.sh
#!/bin/sh
ACTION=action
ZIP=$ACTION.zip
base64 $ZIP | echo "\"$(cat)\"" | jq "{namespace:\"_\", name:\"$ACTION\", exec:{kind:\"nodejs:10\", code:., binary:true, main:\"main\"}}" | curl -X PUT -H "Content-Type:application/json" -d #- https://USERNAME:PASSWORD#openwhisk.ng.bluemix.net/api/v1/namespaces/_/actions/$ACTION?overwrite=true
Complete code
app.js or index.js code
function myAction(args) {
const leftPad = require("left-pad")
const lines = args.lines || [];
return { padded: lines.map(l => leftPad(l, 30, ".")) }
}
exports.main = myAction;
package.json
{
"name": "node",
"version": "1.0.0",
"description": "",
"main": "app.js",
"scripts": {
"test": "echo \"Error: no test specified\" && exit 1"
},
"author": "",
"license": "ISC",
"dependencies": {
"left-pad" : "1.1.3"
}
}
Run npm install and zip the file zip -r action.zip *.
To test the action
ibmcloud fn action invoke --result action --param lines "[\"and now\", \"for something completely\", \"different\" ]"
The REST API for creating or updating a Cloud Functions actions is documented in the IBM Cloud Functions API docs. A good way to find out the exact curl / request syntax is to use the IBM Cloud Functions CLI in verbose mode (-v). The CLI is just a wrapper around the REST API and in verbose mode all the REST details are printed.
Here is the relevant part for what could be printed:
Req Body
Body exceeds 1000 bytes and will be truncated
{"namespace":"_","name":"mytest/myaction","exec":{"kind":"nodejs:8","code":"UEsDBBQAAAAIAHJPhEzjlkxc8wYAAH8VAAALABwAX19tYWluX18ucHlVVAkAA+iFxFrohcRadXgLAAEE9AEAAAT0AQAAxVhtb9s2EP6uX8HRCCLBipb002DA69YkbYo17dZ0GwbDMGSKlrXJokfSToNh/313R+rNL2labJiK1iJ578/x7tTBgJ7A/QzYq8IuN3NmdbpYFIIZm9rC2EKYmiIYsB+1ynW6Ykqz1y9u2WWpNhl7uamELVTFrGJClaUUtha2LeQ9S6uMiVJVspYNgnDPWKVhb5lalqU2ZUXFUqZlmaKwtKTNeWpkzKp0JcsHdj
You would need to set the binary field to true and include the zip content as code. The curl docs suggest to use #filename to reference your zip file:
If you want the contents to be read from a file, use <#filename> as
contents.

Upload a file to my github repo from postman

I would like to upload a file to my Github repo from Postman. What I have tried is:
Generate token from PAT: https://github.com/settings/tokens.
Method PUT URL: https://github.com/username/test2/info/lfs/objects/cd00e292c5970d3c5e2f0ffa5171e555bc46bfc4faddfb4a418b6840b86e79a2
Body is a 1 MB file.
I am receiving the following error: Your browser did something unexpected. Please contact us if the problem persists.
According to the API Reference you can't simply PUT a file to that URL. Rather, you need to encode the file as Base64, and put it within a JSON object with the following inputs:
{
"message": "my commit message",
"committer": {
"name": "Scott Chacon",
"email": "schacon#gmail.com"
},
"content": "bXkgbmV3IGZpbGUgY29udGVudHM="
}

Read PR Title of a project on github

Is it possible to read the PR Title of a github repo?
I want to do some analysis over the data, currently I go and manually check the title and sometimes PR are very large in number
Any guidance will be helpful.
One way to do that is using the GitHub API. For example,
to get the pull request URLs and their titles in JSON format of someuser in somerepo, using curl and jq you could do:
curl -s https://api.github.com/repos/someuser/somerepo/pulls | jq '[.[] | { url: .url, title: .title }]'
The output will look something like:
[
{
"url": "https://api.github.com/repos/SonarSource/sonarlint-visualstudio/pulls/159",
"title": "Remove the locally copied Alm.Authentication classes and use the NuGeā€¦"
},
{
"url": "https://api.github.com/repos/SonarSource/sonarlint-visualstudio/pulls/108",
"title": "New settings for Nuget package installation"
}
]