How to Fetch Files from GitHub with REST API in SvelteKit

Github REST API read repo file

Accessing GitHub Files Using REST API

sitemap
JavaScript
Fetch GitHub Files
sveltekit
web development
GitHub REST API
API Integration

Scenario

In this guide, we will walk through accessing a sitemap.xml file from a GitHub repository using the GitHub REST API. The goal is to integrate this API call into a SvelteKit application, which has its own repository, allowing us to fetch and display the contents of the file.

Task Breakdown

  • Identify the API endpoint to access the file.
  • Retrieve necessary GitHub repository details: (GIT_ACCESS_TOKEN, GIT_REPO_NAME, GIT_REPO_OWNER, GIT_FILE_PATH).
  • Implement the API call from a SvelteKit application.

Identify the API endpoint to access the file.

If you visit this URL GITHUB REST API READ FILE, you will notice we can call the following endpoint:

https://api.github.com/repos/${repoOwner}/${repoName}/contents/${filePath}

This endpoint allows us to retrieve the contents of the file located at filePath within the specified repository (repoName), owned by repoOwner.

GitHub REST API Reading File Endpoint

Also, we need a couple of pieces of information to be able to call the API endpoint successfully.

The GitHub documentation also mentions that the fine-grained token must have the following permission set:

"Contents" repository permissions (read)

GitHub REST API Fine-Grained Token Permissions

Retrieve necessary GitHub repository details

Navigate to Profile / Settings / Developer Settings / Fine Grained Tokens / Generate New Token.

You can follow the following steps to obtain all the required information from git:

  1. <YOUR-TOKEN> : Which we can obtain from Developer Settings in GitHub.
    1. Click on your profile and navigate to Settings. GitHub Settings
    2. Scroll down and navigate to Developer Settings. GitHub Developer Settings Menu
    3. Navigate to Personal access Tokens, then Fine-grained tokens, and then Generate new token. Setting permissions for Personal Access Tokens
    4. Provide all the required information, the fine-grained token must have the Contents permission set to Read-only. GitHub Access Token Read Permissions
    5. Getting the rest of the information is quite easy (GIT_REPO_NAME, GIT_REPO_OWNER, GIT_FILE_PATH). GitHub Repository Info

Implement the API call from a SvelteKit application.

  1. Create a directory or folder (ex - sitemap.xml).
  2. Create a +server.js file inside the directory.
  3. Let’s write a Basic API Response:
    export async function GET() {
      const sitemap = "Hello";
      return new Response(sitemap);
    }

    At this point, you can run the server and get the API response on the route that you have just created.

  4. Now let’s create a .env file and store all the collected information from GitHub.Store Git Information in the Env FileNow import those environment variables:
    import {
      GIT_ACCESS_TOKEN,
      GIT_REPO_NAME,
      GIT_REPO_OWNER,
      GIT_FILE_PATH,
    } from "$env/static/private";
  5. Let’s use those variables and keep writing the code:
    import {
      GIT_ACCESS_TOKEN,
      GIT_REPO_NAME,
      GIT_REPO_OWNER,
      GIT_FILE_PATH,
    } from "$env/static/private";
    
    export async function GET() {
      const repoOwner = GIT_REPO_OWNER;
      const repoName = GIT_REPO_NAME;
      const filePath = GIT_FILE_PATH;
      const accessToken = GIT_ACCESS_TOKEN;
    
      const response = await fetch(
        `https://api.github.com/repos/${repoOwner}/${repoName}/contents/${filePath}`,
        {
          headers: {
            Accept: "application/vnd.github.v3.raw",
            "X-GitHub-Api-Version": "2022-11-28",
            Authorization: accessToken ? `Bearer ${accessToken}` : undefined,
          },
        }
      );
    
      const sitemap = await response.text();
      return new Response(sitemap);
    }

    At this point, you will receive the response as text:

    GitHub API Response as Text
  6. Let’s check if the response is okay and also add headers info to keep receiving the response in xml format:
    if (!response.ok) {
      throw error(500, "Failed to fetch sitemap");
    }
    
    const sitemap = await response.text();
    return new Response(sitemap, {
      headers: { "Content-Type": "application/xml" },
    });
    Now if you check the response on the browser, you can have something like this:GitHub API Response as XML