demostanis
demostanis

Reputation: 98

Create a gist using GitHub API

I wanna create a gist using GitHub API. I tried an POST ajax request:

var gist = {
    "description": "Avatars",
    "public": true,
    "files": {
        "check.txt": {
            "content": "Avatars list..."
        }
    }
};

$.ajax({
    url: 'https://api.github.com/gists',
    type: 'POST',
    dataType: 'json',
    data: JSON.stringify(gist),
    success: function(e) {
      console.log(e);
    },
    error: function(e) {
      console.error("Error!: ", e);
    }
});

But I always get the following error:

jquery-3.1.1.min.js:4 POST https://api.github.com/gists 401 (Unauthorized)

Can anyone help me? Thanks

Upvotes: 0

Views: 3014

Answers (2)

Andreas Rozek
Andreas Rozek

Reputation: 412

Since I ran across the same problem recently, let me add the examples requested by T.Todua

If you want to authenticate with username and password, add the following lines to your $.ajax request:

crossDomain: true,
beforeSend: function (XHR) {
  XHR.setRequestHeader(
    'Authorization','Basic ' + btoa(Username + ':' + Password)
  );
},

If, however, you created an access token for your gists (see Github help and don't forget to check the "Gist" permission!) then add the following lines instead

crossDomain: true,
headers: {
  'Authorization':'bearer ' + GitHubAccessToken
},

The GitHubAccessToken will be shown once (and only once!) immediately after creation, so make sure to store it in a safe location as everybody knowing this access token will be able to modify your gists (until you revoke it again).

Upvotes: 1

Jerodev
Jerodev

Reputation: 33206

When you want to edit things on Github, you need to authorize your request. Either by adding a username and password to the request or an oauth token.

More information can be found in the authorization documentation: https://developer.github.com/v3/auth/

Upvotes: 3

Related Questions