Search code examples
apigithubwebhookshttp-status-code-400

How to create a webhook on a repository on the GitHub web api using AJAX?


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


Solution

  • 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);
        }
    });