Search code examples
javascriptapigithubgist

GitHub API - Comment on Gist returns 404


After following the documentation on GitHub's API, I got stuck on submitting a comment for a gist, the following code always returns 404, and the same call made in Postman too.

My JavaScript code as follows:

const config = {
        method: 'POST',
        headers: {
            'Authorization': credentials.authorizationHeader,
            'Content-Type': 'application/vnd.github.v3.text+json'
        },
        body: { "body": JSON.stringify(comment) } 
    };

    fetch(`https://api.github.com/gists/${gistId}/comments/`, config)
        .then(res => {
            if (res.ok) {
                dispatch(getGistDetails(gistId, credentials));

                dispatch({ type: SUBMIT_COMMENT_SUCCESS });
            } else {
                ToastAndroid.show('An error ocurred, please try again.', ToastAndroid.SHORT);
                console.log(res);
                dispatch({ type: SUBMIT_COMMENT_FAIL });
            }
        })
        .catch(err => console.log(err));

Credentials I'm getting via OAuth:

accessToken: "redacted"
authorizationHeader:"bearer redacted"
clientID:"redacted"
idToken:null
scopes:"gist"
type:"bearer"

I tried changing the authorizationHeader to token <oauth_token, but still no success.

Thanks in advance.


Solution

  • Turns out I was overcomplicating, as getting a gist's details through the API also nets you a comments_url field with the correct url, so no need to splice strings, falling into the very strange issue mentioned by @Zilvinas below. Also, a minor adjustment in the body to

    const body = { body: comment }
    
    const config = {
        method: 'POST',
        headers: {
            'Authorization': credentials.authorizationHeader,
            'Content-Type': 'application/vnd.github.v3.text+json'
        },
        body: JSON.stringify(body)
    };
    

    fixed the subsequent Problems parsing JSON error I got.