API gives constant subscriber count - youtube-api

I am trying to make a web app which shows real time subscribercount of a youtube channel.But it just shows me a constant number.The number of subscribers are not updated in next call of API.
I have written this function to get subs.I have tried with ID as well still no updates.Help me out.
Javascript
function getsubscribers(username, element) {
let url = `https://www.googleapis.com/youtube/v3/channels?key=${KEY}&forUsername=${username}& part=statistics`;
fetch(url)
.then((res) => res.json())
.then((data) => {
element.innerText = data.items[0].statistics.subscriberCount;
});
}

YouTube analytics has the same issue.
This is because the YouTube API is not a realtime api, the data seams to be updated once a day.

Related

Youtube Data API is getting called too many times

So I set up the youtube data api and I added following code to fetch 4 videos on my page: Works fine for like 3 hours before the daily quota of 10.000 is reached. I tested it locally and everything worked fine there. Also: I´m using the search resource and its list method, which result in a quota cost of 100 per call, but that normally shouldnt be a problem, because its a small page.Thx in advance.
const youtubeWrapper = document.querySelector(".youtube-playlist");
async function getFloVideoData(){
const response = await fetch("https://youtube.googleapis.com/youtube/v3/search?part=snippet&channelId=UC78M9ne3s4_XpcmPM4r0Xxw&maxResults=4&order=viewCount&key=myAPIkey");
const data = await response.json();
const {items} = data;
items.forEach((item) => {
youtubeWrapper.innerHTML += `<div class="video-container"><img src="${item.snippet.thumbnails.medium.url}"><p>${item.snippet.title}</p><p>${item.snippet.publishTime}</p></div>`;
});
)
}
setTimeout(getFloVideoData(),3600000); //call function every hour too limit API-Calls

React native PouchDB get hangs

I have a promise chain where I get the content from local DB, update it with the latest fetched from API. This cycle is run whenever user eg opens a content. It works well. Except when the user is opening the app through a deep link. Eg, I go to the company website, I have the deep link option in the safari, I open it. It successfully fetches the content opened from the website, goes into the promise lifecycle where it tries to load and update the content but it just hangs. All input data is correct and it doesn't make sense why it hangs at all.
PouchDB is using adapter pouchdb-adapter-react-native-sqlite with react-native-sqlite-2
createDBIndex()
.then(() => {
console.groupCollapsed('Updating existing content');
console.log(toUpdateArray);
console.log('Fetching articles and indexes');
return Promise.all(toUpdateArray.map(({ _id }) => DB.articles.get(_id)));
})
.then(dbArticles => {
console.log('Resolving finders-keepers');
console.log(dbArticles);
const updatedContent = dbArticles.map(dbItem => {
const toUpdate = toUpdateArray.find(item => item._id === dbItem._id);
return {
...dbItem,
...toUpdate,
expire: moment().add(1, 'd').format()
};
});
return DB.articles.bulkDocs(updatedContent).then(() => updatedContent);
})
.then(updatedDBArray => {
console.log('update result', updatedDBArray);
console.groupEnd();
return updatedDBArray;
})
The last console.log it gives is Fetching articles and indexes and the whole app freeze. tried to print the PouchDB get function result or error but nothing. It doesn't get resolved or rejected.
What I can share is that recently people have problems using PouchDB in a React Native environment which is using AsynchStorage as its backing storage. Take a look at this question and that question and also this issue.

YouTube IFrame Player API getVideoData is removed: how to get title?

On November 13th, I got a call from a customer reporting that the YouTube player didn't work anymore. After a quick look in the dev tool, I found that there was an error:
Uncaught TypeError: a.getVideoData is not a function
Looking into what the player object was containing, I learned that there's no function getVideoData anymore.
The function getVideoData provided a way to get the video title. Now, how can I get the title?
Is there any article from Google about this change?
To get a video's title, you can query the YouTube Data API v3:
GET https://www.googleapis.com/youtube/v3/videos
?part=snippet
&id=VIDEO_ID
&key=YOUR_API_KEY
For that you need to sign up on the Google Cloud Console and create an API key (it's free). You can restrict the API key to only be used from your website, that way you can safely make it public in your JS source code/html code without others being able to make queries on your behalf. Make sure to enable the YouTube Data API v3 in the console as well, otherwise your queries will return errors.
The above query will return a JSON representation of the information on the video that you are interested in (the snippet part). Say you parse the JSON into an object called result. Then you can get the video title via
result.items[0].snippet.title
getVideoData() seems to be back (Dec, 2017). So, try again !
As of today (October 1st, 2020), I am retrieving the title of the video from within YouTube's API object:
// Assigning YouTube's ID to your ID variable
const playerID = "xxxxxxx";
// Creating an object for the video using YouTube's API.
const yPlayer = new YT.Player(playerID, {
events: {
'onReady': onPlayerReady(),
'onStateChange': onPlayerStateChange()
}
});
function onPlayerReady() {
}
function onPlayerStateChange() {
// Title retrieved here
let videoTitle = yPlayer.j.videoData.title;
}
onYouTubeIframeAPIReady();

GAPI batch request on youtube v3 playlistItems.insert doesnt work as expected

I was playing with v3 Youtube API yesterday and found something unexpected / missing something.
Below code piece is creating a batch request to add multiple playlistItems.insert request and executes them.
const gapiRequest = (playlistId,videoId,i) => gapi.client.request({
path: '/youtube/v3/playlistItems?part=snippet',
method:'POST',
body:JSON.stringify({
snippet: {
playlistId,
position:i,
resourceId:{
videoId,
kind: 'youtube#video'
}
}
})
})
let addItemsToList = gapi.client.newBatch();
songs.map((song,i) => {
addItemsToList.add(
gapiRequest(playlistId,song.get('id'),i)
);
})
addItemsToList.then(result => {
console.log(result)
debugger;
})
I double checked the batch request. As I expected it has 19 (means I'm tryin to add 19 playlist item to playlist) request.
Also it's looks all working fine when I debug result. Batch request returns status 200 (means all playlistItems inserted) for every batch item.
But when it comes to youtube playlist I only see 3(sometimes 5-6) song added.
Does anyone have an idea what's going on / what am I missing ?

How to retrieve Medium stories for a user from the API?

I'm trying to integrate Medium blogging into an app by showing some cards with posts images and links to the original Medium publication.
From Medium API docs I can see how to retrieve publications and create posts, but it doesn't mention retrieving posts. Is retrieving posts/stories for a user currently possible using the Medium's API?
The API is write-only and is not intended to retrieve posts (Medium staff told me)
You can simply use the RSS feed as such:
https://medium.com/feed/#your_profile
You can simply get the RSS feed via GET, then if you need it in JSON format just use a NPM module like rss-to-json and you're good to go.
Edit:
It is possible to make a request to the following URL and you will get the response. Unfortunately, the response is in RSS format which would require some parsing to JSON if needed.
https://medium.com/feed/#yourhandle
⚠️ The following approach is not applicable anymore as it is behind Cloudflare's DDoS protection.
If you planning to get it from the Client-side using JavaScript or jQuery or Angular, etc. then you need to build an API gateway or web service that serves your feed. In the case of PHP, RoR, or any server-side that should not be the case.
You can get it directly in JSON format as given beneath:
https://medium.com/#yourhandle/latest?format=json
In my case, I made a simple web service in the express app and host it over Heroku. React App hits the API exposed over Heroku and gets the data.
const MEDIUM_URL = "https://medium.com/#yourhandle/latest?format=json";
router.get("/posts", (req, res, next) => {
request.get(MEDIUM_URL, (err, apiRes, body) => {
if (!err && apiRes.statusCode === 200) {
let i = body.indexOf("{");
const data = body.substr(i);
res.send(data);
} else {
res.sendStatus(500).json(err);
}
});
});
Nowadays this URL:
https://medium.com/#username/latest?format=json
sits behind Cloudflare's DDoS protection service so instead of consistently being served your feed in JSON format, you will usually receive instead an HTML which is suppose to render a website to complete a reCAPTCHA and leaving you with no data from an API request.
And the following:
https://medium.com/feed/#username
has a limit of the latest 10 posts.
I'd suggest this free Cloudflare Worker that I made for this purpose. It works as a facade so you don't have to worry about neither how the posts are obtained from source, reCAPTCHAs or pagination.
Full article about it.
Live example. To fetch the following items add the query param ?next= with the value of the JSON field next which the API provides.
const MdFetch = async (name) => {
const res = await fetch(
`https://api.rss2json.com/v1/api.json?rss_url=https://medium.com/feed/${name}`
);
return await res.json();
};
const data = await MdFetch('#chawki726');
To get your posts as JSON objects
you can replace your user name instead of #USERNAME.
https://api.rss2json.com/v1/api.json?rss_url=https://medium.com/feed/#USERNAME
With that REST method you would do this: GET https://api.medium.com/v1/users/{{userId}}/publications and this would return the title, image, and the item's URL.
Further details: https://github.com/Medium/medium-api-docs#32-publications .
You can also add "?format=json" to the end of any URL on Medium and get useful data back.
Use this url, this url will give json format of posts
Replace studytact with your feed name
https://api.rss2json.com/v1/api.json?rss_url=https://medium.com/feed/studytact
I have built a basic function using AWS Lambda and AWS API Gateway if anyone is interested. A detailed explanation is found on this blog post here and the repository for the the Lambda function built with Node.js is found here on Github. Hopefully someone here finds it useful.
(Updating the JS Fiddle and the Clay function that explains it as we updated the function syntax to be cleaner)
I wrapped the Github package #mark-fasel was mentioning below into a Clay microservice that enables you to do exactly this:
Simplified Return Format: https://www.clay.run/services/nicoslepicos/medium-get-user-posts-new/code
I put together a little fiddle, since a user was asking how to use the endpoint in HTML to get the titles for their last 3 posts:
https://jsfiddle.net/h405m3ma/3/
You can call the API as:
curl -i -H "Content-Type: application/json" -X POST -d '{"username":"nicolaerusan"}' https://clay.run/services/nicoslepicos/medium-get-users-posts-simple
You can also use it easily in your node code using the clay-client npm package and just write:
Clay.run('nicoslepicos/medium-get-user-posts-new', {"profile":"profileValue"})
.then((result) => {
// Do what you want with returned result
console.log(result);
})
.catch((error) => {
console.log(error);
});
Hope that's helpful!
Check this One you will get all info about your own post........
mediumController.getBlogs = (req, res) => {
parser('https://medium.com/feed/#profileName', function (err, rss) {
if (err) {
console.log(err);
}
var stories = [];
for (var i = rss.length - 1; i >= 0; i--) {
var new_story = {};
new_story.title = rss[i].title;
new_story.description = rss[i].description;
new_story.date = rss[i].date;
new_story.link = rss[i].link;
new_story.author = rss[i].author;
new_story.comments = rss[i].comments;
stories.push(new_story);
}
console.log('stories:');
console.dir(stories);
res.json(200, {
Data: stories
})
});
}
I have created a custom REST API to retrieve the stats of a given post on Medium, all you need is to send a GET request to my custom API and you will retrieve the stats as a Json abject as follows:
Request :
curl https://endpoint/api/stats?story_url=THE_URL_OF_THE_MEDIUM_STORY
Response:
{
"claps": 78,
"comments": 1
}
The API responds within a reasonable response time (< 2 sec), you can find more about it in the following Medium article.

Resources