GitHub API to Create a File

Neil picture Neil · Mar 10, 2014 · Viewed 8.5k times · Source

So I'm trying to familiarize myself with the GitHub API. I'm using cURL commands to implement some of their basic functionality. I can get the basic authorization & repository creation correctly. Currently, I'm trying to create a file in a repository using their API & am facing the "message":"Not Found" error as the response.

Their documentation suggests this:

PUT /repos/:owner/:repo/contents/:path

I came up with this as the cURL equivalent:

curl -H 'Authorization: <token>' -d '{"path": "test.txt", "message": "Initial Commit", "committer": {"name": "<name>", "email": "<email>"}, "content": "bXkgbmV3IGZpbGUgY29udGVudHM=", "note":"Test Commit"}' https://api.github.com/repos/InViN-test/test_repo1/contents/test.txt

I think the problem is with the API URL I'm using at the end, but I can't seem to figure out what the URL should look like.

This is what I used to create a repository:

curl -i -H 'Authorization: <token>' -d '{"name": "test_repo1", "message": "Initial Commit", "committer": {"name": "<name>", "email": "<email>"}, "content": "bXkgbmV3IGZpbGUgY29udGVudHM=", "note":"Test Commit"}' https://api.github.com/user/repos

The repository creation URL I used follows: user/repos as the syntax. Similarly, I've tried using user/repos/repo, but it didn't work.

Can anyone shed any light on this?

I've gone through various StackOverflow questions & many seem similar but none really offer an example so I can figure out where the mistake lies.

EDIT: Thanks to TimWolla for the answer.

Syntax of a working command to create a file in a repository using the GitHub API:

curl -i -X PUT -H 'Authorization: token <token_string>' -d '{"path": "<filename.extension>", "message": "<Commit Message>", "committer": {"name": "<Name>", "email": "<E-Mail>"}, "content": "<Base64 Encoded>", "branch": "master"}' https://api.github.com/repos/<owner>/<repository>/contents/<filename.extension>

My example:

curl -i -X PUT -H 'Authorization: token f94ce61613d5613a23770b324521b63d202d5645' -d '{"path": "test4.txt", "message": "Initial Commit", "committer": {"name": "Neil", "email": "[email protected]"}, "content": "bXkgbmV3IGZpbGUgY29udGVudHM=", "branch": "master"}' https://api.github.com/repos/InViN-test/test_repo1/contents/test4.txt

Answer

TimWolla picture TimWolla · Mar 11, 2014

When using curl you need to specify the correct HTTP Verb (PUT in this case) using the -X option:

curl -X PUT -H 'Authorization: …' yadayada

Also using your example payload an error 500 showed up, this shortened payload worked fine:

{"message": "Initial Commit","content": "bXkgbmV3IGZpbGUgY29udGVudHM="}

I don't know the actual reason for the Server error, though.