3

I am experimenting with Webhooks in the GitHub api. I got one working by doing it manually as in going into my repository and clicking into the setting and enabling a web hook. But now I want to do this in AJAX and I am getting problems. Anytime I try to send a POST to the web api it fails with a 400 (Bad Request). I am not sure where I am going wrong with my code.

function createWebHooksOnRepos(token){
const webhookURL = "https://api.github.com/repos/DanoBuck/AlgorithmsAndDataStructures/hooks";

const json = {
    "name": "WebHook",
    "active": true,
    "events": [
        "issue_comment",
        "issues"
    ],
    "config": {
        "url": "http://39a40427.ngrok.io/api/webhooks/incoming/github",
        "content_type": "json"
        }
};
$.ajax({
    headers: {
        "Authorization": "Token " + token
    },
    url: webhookURL,
    data: json,
    type: "POST",
    dataType: "json",
    success: function(data){
        console.log(data);
    }
});

}

Thank you

DanoBuck
  • 43
  • 1
  • 4

1 Answers1

3

From github Webhook API doc :

name - string - Required. Use "web" for a webhook or use the name of a valid service. (See /hooks for the list of valid service names.)

So in your case, just rename Webhook to web :

const json = {
    "name": "web",
    "active": true,
    "events": [
        "issue_comment",
        "issues"
    ],
    "config": {
        "url": "http://39a40427.ngrok.io/api/webhooks/incoming/github",
        "content_type": "json"
        }
};

Also JSON.stringify your data before sending :

$.ajax({
    headers: {
        "Authorization": "Token " + token
    },
    url: webhookURL,
    data: JSON.stringify(json),
    type: "POST",
    dataType: "json",
    success: function(data) {
        console.log(data);
    }
});
Bertrand Martel
  • 42,756
  • 16
  • 135
  • 159
  • Still no luck with this. Still receiving the same response back "Failed to load resource: the server responded with a status of 400 (Bad Request)" . Thank you for your help though. – DanoBuck Feb 12 '17 at 20:14
  • You forgot to stringify the data, I've updated my post – Bertrand Martel Feb 12 '17 at 20:17
  • data: JSON.stringify(json), - That line makes it work perfectly. Thank you very much for your help. Appreciate the help greatly. – DanoBuck Feb 12 '17 at 20:20