Nick
Nick

Reputation: 133

Github REST API full example

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

Upvotes: 13

Views: 20214

Answers (2)

Aviv
Aviv

Reputation: 14527

Solution: In order to perform action on github api you can use curl according to Github doc:

  1. 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

  1. the command should be in http PUT method on path /repos/:owner/:repo/contents/:path
  2. 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
  1. Verify on Github the content has been inserted correctly to your branch

Upvotes: 0

Wsl_F
Wsl_F

Reputation: 842

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.

Upvotes: 9

Related Questions