Hey there, fellow dev! Ready to dive into the world of Instagram API integration? We're going to use the instagram-private-api
package to make this happen. Just a heads up: this is an unofficial API, so tread carefully and keep an eye on Instagram's terms of service.
Before we jump in, make sure you've got:
If you're good to go, let's get this party started!
First things first, let's set up our project:
mkdir instagram-api-project cd instagram-api-project npm init -y npm install instagram-private-api
Boom! You're all set up and ready to roll.
Now, let's get you logged in:
const { IgApiClient } = require('instagram-private-api'); const ig = new IgApiClient(); ig.state.generateDevice(process.env.IG_USERNAME); (async () => { await ig.account.login(process.env.IG_USERNAME, process.env.IG_PASSWORD); console.log('Logged in!'); })();
Pro tip: Use environment variables for your credentials. Safety first!
Let's start with some basic operations:
const userInfo = await ig.user.info(ig.state.cookieUserId); console.log(userInfo);
const feed = ig.feed.user(ig.state.cookieUserId); const posts = await feed.items(); console.log(posts);
const { promisify } = require('util'); const fs = require('fs'); const readFileAsync = promisify(fs.readFile); const photoBuffer = await readFileAsync('./path/to/photo.jpg'); const publishResult = await ig.publish.photo({ file: photoBuffer, caption: 'Check out this awesome photo!' }); console.log(publishResult);
Ready to level up? Let's try some advanced stuff:
// Like a post await ig.media.like({ mediaId: '1234567890', moduleInfo: { module_name: 'profile' } }); // Comment on a post await ig.media.comment({ mediaId: '1234567890', text: 'Great post!' });
const usersSearch = await ig.search.users('instagram'); console.log(usersSearch); const hashtagSearch = await ig.search.hashtag('coding'); console.log(hashtagSearch);
const feed = ig.feed.user(ig.state.cookieUserId); let allPosts = []; do { const posts = await feed.items(); allPosts = allPosts.concat(posts); } while (feed.isMoreAvailable()); console.log(allPosts);
Don't forget to handle those pesky errors and respect rate limits:
try { // Your API calls here } catch (error) { if (error.name === 'IgRateLimitError') { console.log('Hit rate limit, waiting before retrying...'); await new Promise(resolve => setTimeout(resolve, 60000)); // Retry your API call } else { console.error('An error occurred:', error); } }
Remember to:
And there you have it! You've just built a solid Instagram API integration using JavaScript. You've learned how to authenticate, perform basic and advanced operations, and handle errors like a pro.
Keep exploring and pushing the boundaries of what you can do with this API. The sky's the limit!
Want to dive deeper? Check out these resources:
Happy coding, and may your Instagram integrations be ever awesome! 🚀📸