Hello everyone! I need to send http get request to twitch API. How it works: User inputs name of the streamer, my programm sends http get request to twitch API and the output need to be how much viewers right now on the twitch stream. my try:
JavaScript
x
7
1
import fetch from 'node-fetch';
2
3
const response = await fetch('https://www.google.com/');
4
const data = await response.json();
5
6
console.log(data);
7
Advertisement
Answer
I recommend that you use a package like axios
to make your request. That is because to authenticate you need to send a POST requeust
as well which axios makes very easy.
First you need to authenticate to the server this can be done like so
JavaScript
1
20
20
1
axios.post('https://id.twitch.tv/oauth2/token', {
2
client_id: '<your client id>',
3
client_secret: '<your client id>',
4
grant_type: 'client_credentials'
5
})
6
.then(function (response) {
7
console.log(response);
8
9
// the response will look like this
10
// save the access token you will need it for every request you send
11
/*
12
{
13
"access_token": "jostpf5q0puzmxmkba9iyug38kjtg",
14
"expires_in": 5011271,
15
"token_type": "bearer"
16
}
17
*/
18
})
19
20
You can query for a channel like this. You can find all request you can make and their response here. Again here you need to provide the authentication from the previous step
JavaScript
1
10
10
1
axios.get('https://api.twitch.tv/helix/search/channels?query=loserfruit', {
2
headers: {
3
'Client-Id': '<your client id>',
4
'Authorization': 'Bearer <access_token fron previous request>'
5
}})
6
.then(function (response) {
7
console.log(response);
8
})
9
10
For the example you provided it would look like this (you did not include the Bearer
Prefix
JavaScript
1
9
1
axios.get('https://api.twitch.tv/helix/search/channels?query=loserfruit', {
2
headers: {
3
'Client-Id': 'mxciemz4ew',
4
'Authorization': 'Bearer vz9fcq1xv0qxxr7kcr2g9btubgdof'
5
}})
6
.then(function (response) {
7
console.log(response);
8
})
9