As the description (located at http://developer.github.com/v3/repos/contents/) says:

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

An ajax code will be:

$.ajax({
    url: readme_uri,
    dataType: 'jsonp',
    success: function(results)
    {
        var content = results.data.content;
    });

Replace the readme_uri by the proper /repos/:owner/:repo/contents/:path.

Answer from atejeda on Stack Overflow
Top answer
1 of 3
42

As the description (located at http://developer.github.com/v3/repos/contents/) says:

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

An ajax code will be:

$.ajax({
    url: readme_uri,
    dataType: 'jsonp',
    success: function(results)
    {
        var content = results.data.content;
    });

Replace the readme_uri by the proper /repos/:owner/:repo/contents/:path.

2 of 3
40

This GitHub API page provides the full reference. The API endpoint for reading a file:

https://api.github.com/repos/{username}/{repository_name}/contents/{file_path}
{
  "encoding": "base64",
  "size": 5362,
  "name": "README.md",
  "content": "encoded content ...",
  "sha": "3d21ec53a331a6f037a91c368710b99387d012c1",
  ...
}
  • Consider using a personal access token
    • Rate-limits (up to 60 per-hour for anonymous, up to 5,000 per-hour for authenticated) read more
    • Enable accessing files in private repos
  • The file content in the response is base64 encoded string

Using curl

Reading https://github.com/airbnb/javascript/blob/master/package.json using GitHub's API via curl:

curl -H 'Accept: application/vnd.github.v3.raw' https://api.github.com/repos/airbnb/javascript/contents/package.json
  • Make sure to pass header Accept: application/vnd.github.v3.raw to get raw file response (thanks jakub.g)

Using Python

Reading https://github.com/airbnb/javascript/blob/master/package.json using GitHub's API in Python:

import base64
import json
import requests
import os


def github_read_file(username, repository_name, file_path, github_token=None):
    headers = {}
    if github_token:
        headers['Authorization'] = f"token {github_token}"
        
    url = f'https://api.github.com/repos/{username}/{repository_name}/contents/{file_path}'
    r = requests.get(url, headers=headers)
    r.raise_for_status()
    data = r.json()
    file_content = data['content']
    file_content_encoding = data.get('encoding')
    if file_content_encoding == 'base64':
        file_content = base64.b64decode(file_content).decode()

    return file_content


def main():
    github_token = os.environ['GITHUB_TOKEN']
    username = 'airbnb'
    repository_name = 'javascript'
    file_path = 'package.json'
    file_content = github_read_file(username, repository_name, file_path, github_token=github_token)
    data = json.loads(file_content)
    print(data['name'])


if __name__ == '__main__':
    main()
  • Define an environment variable GITHUB_TOKEN before running
🌐
GitHub
docs.github.com › en › rest › repos › contents
REST API endpoints for repository contents - GitHub Docs
Use the REST API to create, modify, and delete Base64 encoded content in a repository. Gets the contents of a file or directory in a repository. Specify the file path or directory with the path parameter.
Top answer
1 of 6
65

You can use Github git trees

https://api.github.com/repos/[USER]/[REPO]/git/trees/[BRANCH]?recursive=1

Repo

https://github.com/deeja/bing-maps-loader

Api Call

https://api.github.com/repos/deeja/bing-maps-loader/git/trees/master?recursive=1

which returns

{
sha: "55382e87889ccb4c173bc99a42cc738358fc253a",
url: "https://api.github.com/repos/deeja/bing-maps-loader/git/trees/55382e87889ccb4c173bc99a42cc738358fc253a",
tree: [
{
path: "README.md",
mode: "100644",
type: "blob",
sha: "41ceefc1262bb80a25529342ee3ec2ec7add7063",
size: 3196,
url: "https://api.github.com/repos/deeja/bing-maps-loader/git/blobs/41ceefc1262bb80a25529342ee3ec2ec7add7063"
},
{
path: "index.js",
mode: "100644",
type: "blob",
sha: "a81c94f70d1ca2a0df02bae36eb2aa920c7fb20e",
size: 1581,
url: "https://api.github.com/repos/deeja/bing-maps-loader/git/blobs/a81c94f70d1ca2a0df02bae36eb2aa920c7fb20e"
},
{
path: "package.json",
mode: "100644",
type: "blob",
sha: "45f24dcb7a457b14fede4cb907e957600882b340",
size: 595,
url: "https://api.github.com/repos/deeja/bing-maps-loader/git/blobs/45f24dcb7a457b14fede4cb907e957600882b340"
}
],
truncated: false
}
2 of 6
54

This will have to be relative to a particular commit, as some files may be present in some commits and absent in others, so before you can look at files you'll need to use something like List commits on a repository:

GET /repos/:owner/:repo/commits

If you're just interested in the latest commit on a branch you can set the sha parameter to the branch name:

sha string SHA or branch to start listing commits from.

Once you have a commit hash, you can inspect that commit

GET /repos/:owner/:repo/git/commits/:sha

which should return something like this (truncated from GitHub's documentation):

{
  "sha": "...",
  "...",
  "tree": {
    "url": "https://api.github.com/repos/octocat/Hello-World/git/trees/691272480426f78a0138979dd3ce63b77f706feb",
    "sha": "691272480426f78a0138979dd3ce63b77f706feb"
  },
  "...": "..."
}

Look at the hash of its tree, which is essentially its directory contents. In this case, 691272480426f78a0138979dd3ce63b77f706feb. Now we can finally request the contents of that tree:

GET /repos/:owner/:repo/git/trees/:sha

The output from GitHub's example is

{
  "sha": "9fb037999f264ba9a7fc6274d15fa3ae2ab98312",
  "url": "https://api.github.com/repos/octocat/Hello-World/trees/9fb037999f264ba9a7fc6274d15fa3ae2ab98312",
  "tree": [
    {
      "path": "file.rb",
      "mode": "100644",
      "type": "blob",
      "size": 30,
      "sha": "44b4fc6d56897b048c772eb4087f854f46256132",
      "url": "https://api.github.com/repos/octocat/Hello-World/git/blobs/44b4fc6d56897b048c772eb4087f854f46256132"
    },
    {
      "path": "subdir",
      "mode": "040000",
      "type": "tree",
      "sha": "f484d249c660418515fb01c2b9662073663c242e",
      "url": "https://api.github.com/repos/octocat/Hello-World/git/blobs/f484d249c660418515fb01c2b9662073663c242e"
    },
    {
      "path": "exec_file",
      "mode": "100755",
      "type": "blob",
      "size": 75,
      "sha": "45b983be36b73c0788dc9cbcb76cbb80fc7bb057",
      "url": "https://api.github.com/repos/octocat/Hello-World/git/blobs/45b983be36b73c0788dc9cbcb76cbb80fc7bb057"
    }
  ]
}

As you can see, we have some blobs, which correspond to files, and some additional trees, which correspond to subdirectories. You may want to do this recursively.

🌐
Testengineeringnotes
testengineeringnotes.com › posts › 2023-03-25-python-github-api
Get file content from Github repository — Test Engineering Notes
March 25, 2023 - Personal access token can be generated at Settings / Developer settings / Personal access tokens · To get the file content from Github repository you need to check the Github API for Repository / Content.
Top answer
1 of 2
2

Yes, it is different.

Github REST API download files has two steps.

1, The first step is get the download url.

The url format like this:

https://api.github.com/repos/<Project Name>/<Repository Name>/contents/<File Name>

The response format like this:

2, The second step is using the download url to get the file content.

The url format like this:

https://raw.githubusercontent.com/<Project Name>/<Repository Name>/main/<File Name>?token=<Random Token that related to Revision Version>

Please notice that the first step can't skip, otherwise you will be unable to get the revision token.

I can achieve your requirement using python:

import requests

#Define required information
project_name = "xxx"
repository_name = "xxx"
# repository_name = "xxx"
branch_name = "xxx"
File_name = "xxx"
PAT = "xxx"
url = "https://api.github.com/repos/"+project_name+"/"+repository_name+"/contents/"+File_name

#downoad file from github
payload = {}
headers = {
    'Authorization': 'token '+PAT
}

#download file
file_content = requests.request("GET", ((requests.request("GET", url, headers=headers, data=payload)).json())['download_url'], headers=headers, data=payload)
print(file_content.text)

Successfully get the latest contents(I am also based on private repository):

2 of 2
0

If you want a raw file, you just need to set request header Accept with application/vnd.github.v3.raw. Just one step would be enough.

GitHub API: /repos/{owner}/{repo}/contents/{path}

Refer to:

Official way to access / download github files from scripts?

https://docs.github.com/en/rest/repos/contents

🌐
Medium
medium.com › plumbersofdatascience › import-and-export-files-to-and-from-github-via-api-626efd7dd859
Import and Export Files to and from GitHub via API | by Henry Alpert | Plumbers Of Data Science | Medium
January 12, 2023 - Then, use the get_contents() method to grab all the file’s information from that GitHub repo and assign it to a variable. This call creates a PyGithub ContentFile object, but the content is not in the desired form yet, because it is still ...
🌐
LONGLOVEMYU
longlovemyu.com › githubapi
Access files using github api | LONGLOVEMYU
March 26, 2020 - My idea is using get_contents for a directory to request sha and download_url keywords, then use requests.get(). Git Blobs API is another solution. ... Notice: update_file need sha parameter, you have to request sha before use it.
Find elsewhere
🌐
GitHub API
tryapis.com › github › api › repos-get-content
Get repository content - GitHub API - tryapis.com
Instantly send requests to the GitHub API. Gets the contents of a file or directory in a repository. Specify the file path or directory in `:path`. If you omit `:path`, you will receive the contents of the repository's root directory.
🌐
GitHub
docs2.lfe.io › v3 › repos › contents
Contents | GitHub API
These API methods let you retrieve the contents of files within a repository as Base64 encoded content.
🌐
How-To Geek
howtogeek.com › home › programming › how to download single files from a github repository
How To Download Single Files From a Github Repository
November 15, 2021 - wget https://raw.githubusercontent.com/username/repository/branch/path/filename.md · If you'd rather use Git's API, you can interact with it more directly, and download files when you aren't sure of the exact file location.
🌐
GitHub
github.com › orgs › community › discussions › 49285
get the full-file-path using github API · community · Discussion #49285
To get the full path of each file, you can simply concatenate the file's path in the repository with its filename. For example, if the path of a file is src/app/index.js and its filename is index.js, then the full path of the file is src/app/index.js. Beta Was this translation helpful? Give feedback. ... Sign up for free to join this conversation on GitHub.
🌐
Mark Heath
markheath.net › post › list-and-download-github-repo-cs
How to list and download the contents of a GitHub repo in C#
June 27, 2020 - There is actually a GitHub API, which means that this simple URL (https://api.github.com/repos/markheath/azure-deploy-manage-containers/contents) can be used to list all the files in one of my GitHub repos.
🌐
GitHub
github.com › jonschlinkert › get-file
GitHub - jonschlinkert/get-file: CLI and API to get a single file from Github repository. · GitHub
var get = require('get-file'); get.files('jonschlinkert/get-file', function(err, files) { if (err) return console.error(err); console.log(files); }); ... github-contributors: Generate a markdown or JSON list of contributors for a project using ...
Author: jonschlinkert
🌐
HackerNoon
hackernoon.com › how-to-fetch-large-data-files-through-github-api
How to Fetch Large Data Files Through GitHub API
April 8, 2022 - Discover Anything · Hackernoon · Signup · Write · Light-Mode · Classic · Newspaper · Minty · Dark-Mode · Neon Noir
🌐
GitHub
gist.github.com › MichaelCurrin › 6777b91e6374cdb5662b64b8249070ea
GitHub GraphQL - Get files in a repository · GitHub
Fetch all file names with a query similar to get_github_files.gql · For each group of n files, fetch the file content directly but in one request with aliasing. The query looks something like this: query RepoFiles { repository(owner: "username", name: "repository") { file1: object(expression: "HEAD:test/filename1.txt") { ... on Blob { text byteSize } } file2: object(expression: "HEAD:test/filename2.txt") { ... on Blob { text byteSize } } ... } } The GitHub API will treat step 2 as only 1-2 request "points" toward the rate limit (not a request point per file)
🌐
Geoffhudik
geoffhudik.com › tech › 2020 › 07 › 20 › downloading-a-single-file-from-a-private-github-repository
Downloading a Single File From a Private GitHub Repository – GeoffHudik.com
July 20, 2020 - curl -H "Authorization: token $TOKEN" \ -H 'Accept: application/vnd.github.v3.raw' \ -o my-file.ext \ -L https://api.github.com/repos/my-username/my-repo/contents/my-file-path.ext?ref=my-branch