Sırrı
Sırrı

Reputation: 13

How can I get JSON response from Github Api?

I'm new at coding and I'm stuck. I'm trying to take JSON response from GitHub's REST API. I'm using external script file but it's not working. When I tried to use it in HTML with the script tag it's giving an error. I tried a way that is used for authenticating the token in fetch() it gives an error about that. It's called "header" I don't know about that. I will be happy if you guys help.

HTML:

<!DOCTYPE html>
<html lang="en-US">
<head>
    <meta charset="UTF-8">
    <title>GitHub API Trial</title>
</head>
<body>
    <script src="github.js"></script>
</body>
</html>

Script:

getData();
const api_url = 'https://api.github.com/users/alisirri/repos';
async function getData() {
    const response = await fetch(api_repo_url,
        {
            headers: {
                authorization: "TOKEN"
            }
        }
    )
    console.log(await response.json());
}

Upvotes: 1

Views: 2615

Answers (2)

Bobby Mannino
Bobby Mannino

Reputation: 256

Replace everything in the js file with this:

const api_repo_url = "https://api.github.com/users/alisirri/repos";
fetch(api_repo_url, {
    headers: {
        authorization: "TOKEN",
    },
})
    .then((response) => response.json())
    .then((data) => {
        console.log(data);
    });

No need for async either as .then() takes care of that

Upvotes: 1

yolisses
yolisses

Reputation: 156

I tested your code and looks like the headers are unnecessary

getData();
async function getData() {
  const api_url = "https://api.github.com/users/alisirri/repos";
  const response = await fetch(api_url);
  console.log(await response.json());
}

Upvotes: 1

Related Questions