Social Media APIs for Posting, Scheduling, and Analytics
The Social Media API is a Node.js wrapper SDK for Ayrshare's APIs.
Ayrshare is a powerful set of APIs that enable you to send social media posts, get analytics, and add comments to X/Twitter, Instagram, Facebook, LinkedIn, YouTube, Google Business Profile, Pinterest, TikTok, Reddit, and Telegram on behalf of your users or clients.
The Ayrshare Social API handles all the setup and maintenance for the social media networks. One API to rule them all (yeah, went there). See the full list of full list of features in our docs.
Get started with a free plan, or if you have a platform or manage multiple users check out the Business Plan.
For more information on setup, see our installation video or our Quick Start Guide.
Installation
npm i social-media-api
Setup
1. Create a free Ayrshare account.
2. Enable your social media accounts such as X/Twitter, Facebook, LinkedIn, Reddit, Instagram, Google Business Profile, Telegram, TikTok, or YouTube in the Ayrshare dashboard.
3. Copy your API Key from the Ayrshare dashboard. Used for authentication.
Getting Started
Initialize Social Post API
Create a new Social Media API object with your API Key.
const SocialMediaAPI = require("social-media-api");
const social = new SocialMediaAPI('Your API Key');
History, Post, Delete Example
This simple example shows how to post an image or video, get history, and delete the post. This example assumes you have a free API key from Ayrshare and have enabled X/Twitter, Facebook Pages, Instagram, LinkedIn. Note, YouTube, Google Business Profile, Telegram, TikTok, and Reddit also available.
const SocialMediaAPI = require("social-media-api");
const API_KEY = "Your API Key";
const social = new SocialMediaAPI(API_KEY);
const run = async () => {
const post = await social.post({
post: "Who you gonna call?",
platforms: ["twitter", "facebook", "fbg", "instagram", "linkedin", "gmb"],
mediaUrls: ["https://img.ayrshare.com/012/gb.jpg"]
}).catch(console.error);
console.log(post);
const history = await social.history()
.catch(console.error);
console.log(history);
const deletePost = await social.delete({ id: post.id })
.catch(console.error);
console.log(deletePost);
};
run();
Social Media API
The following section details the different functions of the social media API.
Post
Published a new post to the specified social networks either immediately or at scheduled future date. Returns a promise that resolves to an object containing the post ID and post status (success, error). See the post endpoint for the full capabilities.
const postResponse = await social.post({
post: "Best post ever!",
platforms: ["twitter", "facebook", "fbg", "instagram", "linkedin", "gmb", "telegram"],
mediaUrls: ["https://img.ayrshare.com/012/gb.jpg"],
scheduleDate: "2020-08-07T15:17:00Z",
shortenLinks: true,
profileKeys: ["Profile API Key 1"];
}).catch(console.error);
Delete
Delete a post with a given post ID, obtained from the "post" response. Returns a promise with the delete status. Also, can bulk delete multiple IDs at once using the "bulk" key. See the delete endpoint for more details.
const deleteResponse = await social.delete({
id: "POST ID",
bulk: ["Post ID 1", "Post ID 2", ...]
}).catch(console.error);
Get Post
Get a post with a given post ID, obtained from the "post" response. Returns a promise that resolves to an array containing the post object. See the get endpoint for more details.
const getResponse = await social.getPost({ id }).catch(console.error);
Retry Post
Retry a failed post with a given post ID, obtained from the "post" response. Returns a promise that resolves to an object containing the post status and ID. See the retry endpoint for more details.
const retryResponse = await social.retryPost({ id }).catch(console.error);
History
Get a history of all posts and their current status in descending order. Returns a promise that resolves to an array of post objects. See the history endpoint for more details.
const historyResponse = await social.history({
lastRecords: 10,
lastDays: 30,
}).catch(console.error);
Get history by post ID
const historyByIdResponse = await social.history({
id: "pK0j89"
}).catch(console.error);
Get All Post History
const historyAllPostsResponse = await social.history({
platform: "facebook"
}).catch(console.error);
Upload Media
Upload and store a new image. Returns a URL referencing the image. Can be used in "image_url" in "post". See the media endpoint for more details.
const uploadResponse = await social.upload({
file:"data:image/jpeg;base64,/9j/4AAQSkZJRgABAQAAAQ...",
fileName: "test.png",
description: "best image"
}).catch(console.error);
Get Media
Get all media URLS. Returns a promise that resolves to an array of URL objects. See the media endpoint for more details.
const mediaResponse = await social.media().catch(console.error);
Get Media Upload URL for Large Files
Get a URL to upload large files. Returns a promise that resolves to an object containing an access URL and an upload URL. See the media upload url endpoint for more details.
const mediaUploadResponse = await social.mediaUploadUrl({
fileName: "test.png",
contentType: "image/png"
}).catch(console.error);
Verify Media Exists
Verify that the media file exists when uploaded. See the media verify exists endpoint for more details.
const verifyMediaResponse = await social.verifyMediaExists({
mediaUrl: "https://theImage.jpg"
}).catch(console.error);
Resize Image
Get image resized according to social network requirements. See the resize image endpoint for more details.
const resizeImageResponse = await social.resizeImage({
imageUrl: "https://theImage.jpg",
platform: "facebook"
watermarkUrl: "https://theWatermark.png",
effects: { color: "#A020F0" }
dimensions: { width: 1200, height: 628 }
mode: "blur"
}).catch(console.error);
User
Get data about the logged in user, such as post quota, used quota, active social networks, and created date. See the user endpoint for more details.
const user = await social.user().catch(console.error);
Analytics
Get analytics on shortened links and shares, likes, shares, and impressions with for a post or at the accounts level. See the analytics endpoint for more details.
const analyticsLinks = await social.analyticsLinks({
lastDays: 3
}).catch(console.error);
const analyticsPost = await social.analyticsPost({
id: "Post ID",
platforms: ["twitter", "instagram", "facebook", "youtube", "linkedin"]
}).catch(console.error);
const analyticsSocial = await social.analyticsSocial({
platforms: ["twitter", "instagram", "facebook", "youtube", "pinterest", "tiktok", "reddit", "linkedin"]
}).catch(console.error);
Add a comment to a post. Currently only on Facebook and Instagram. See the create comment endpoint for more details.
const postCommentResponse = await social.postComment({
id: "Pkdo9sjk2",
platforms: ["instagram", "facebook"],
comment: "What a comment"
}).catch(console.error);
Get comments for a post. Currently only on Facebook and Instagram. See the get comment endpoint for more details.
const getCommentResponse = await social.getComments({
id: "Pkdo9sjk2",
}).catch(console.error);
Delete either a single comment or all comments under a post that were sent via Ayrshare. Available for Facebook, Instagram, LinkedIn, Reddit, TikTok, X/Twitter, and YouTube. See the delete comment endpoint for more details.
const deleteCommentResponse = await social.deleteComments({
id: "Pkdo9sjk2",
platforms: ["instagram", "facebook"],
}).catch(console.error);
Reply to a comment. Available for Facebook, Instagram, LinkedIn, TikTok, X/Twitter, and YouTube. See the reply comment endpoint for more details.
const replyCommentResponse = await social.replyComment({
commentId: "Pkdo9sjk2",
platforms: ["instagram", "facebook"],
comment: "What a comment"
}).catch(console.error);
Set, Delete, and List Auto Schedule
Set up an auto-post schedule by providing times to send. Post will automatically be sent at the next available time. If no more times are available today, the first available time tomorrow will be used, and so forth. See the set-auto-schedule endpoint for more details.
const setAutoSchedule = await social.setAutoSchedule({
schedule: ["13:05Z", "20:14Z"],
title: "Instagram Schedule"
}).catch(console.error);
const deleteAutoSchedule = await social.deleteAutoSchedule({
title: "Instagram Schedule"
}).catch(console.error);
const listAutoSchedule = await social.listAutoSchedule().catch(console.error);
Add a new RSS or Substack feed to auto post all new articles. Returns a promise that resolved to an object containing the feed ID. See How to Automate Your Blog or Newsletter for more info.
const feedResponse = await social.feedAdd({
url: "https://theRSSFeed",
type: "RSS",
}).catch(console.error);
Delete an RSS feed for a given ID.
const feedResponse = await social.feedDelete({
id: "Feed ID",
}).catch(console.error);
Get Feeds
Get all registered RSS feeds. Returns a promise that resolves to an array of feed objects. See the get feeds endpoint for more details.
const feedsResponse = await social.feedGet().catch(console.error);
Update Feed
Update an RSS feed for a given ID. Returns a promise that resolves to an object containing the feed ID. See the update feed endpoint for more details.
const feedResponse = await social.feedUpdate({
id: "Feed ID",
useFirstImage: true,
autoHashtag: true,
}).catch(console.error);
Business Functions for Multiple Users - Business or Enterprise Plan Required
The Business Plan allows you to create, manage, and post on behalf of client profiles via the API or Dashboard GUI. You can integrate Ayrshare into your platform, product, or agency and give your clients social media capabilites. Please contact us with any questions.
Create Profile
Create a new account profile under the primary account. See the create profile endpoint for more details.
const createProfileResponse = await social.createProfile({
title: "New Profile Title",
}).catch(console.error);
Delete Profile
Delete a profile owned by the primary account. See the delete profile endpoint for more details.
const deleteProfileResponse = await social.deleteProfile({
profileKey: "JI9s-kJII-9283-OMKM",
}).catch(console.error);
Update Profile
Update a profile owned by the primary account. See the update profile endpoint for more details.
const updateProfileResponse = await social.updateProfile({
profileKey: "JI9s-kJII-9283-OMKM",
title: "This is a greate new title"
}).catch(console.error);
Get Profiles
Get all the profiles associated with the primary account. See the get profile endpoint for more details.
const getProfileResponse = await social.getProfiles().catch(console.error);
Unlink Social Network
Unlink a social account for a given user profile owned by the primary account. See the unlink social network endpoint for more details.
const unlinkResponse = await social.unlinkSocial({
profileKey: "JI9s-kJII-9283-OMKM",
platform: "facebook"
}).catch(console.error);
Generate a JWT Url
Generate a JWT Token and URL used for authorizing a user's access to the Social Account linking page. See the generate JWT endpoint for more details.
const generateJWTResponse = await social.generateJWT({
domain: "ACME",
privateKey: "-----BEGIN RSA PRIVATE KEY...",
profileKey: "PROFILE_KEY",
}).catch(console.error);
Get Brand Info on a User
Get brand information on users and companies public social media accounts. See the brand endpoint for more details.
const brandResponse = await social.getBrandByUser({
platforms: ["instagram", "facebook"],
instagramUser: "@ayrshare",
facebookUser: "ayrshare",
}).catch(console.error);
Register, Unregister, and List Webhooks
A webhook allows you to be notified when certain system actions occur via a call to a URL you provide. Register a webhook by providing your URL and the type of action you wish to be notified. When the action occurs a POST message will be sent to the provided URL. See the webhooks endpoints for more details.
const registerWebhook = await social.registerWebhook({
action: "social",
url: "https://myhook",
}).catch(console.error);
const unregisterWebhook = await social.unregisterWebhook({
action: "social",
}).catch(console.error);
const listWebhooks = await social.listWebhooks().catch(console.error);
Auto Hashtags
Automatically add hashtags to your post. See the auto hashtags endpoint for more details.
const autoHashtagsResponse = await social.autoHashtags({
post: "I love social media",
position: "auto"
max: 2
}).catch(console.error);
Recommend Hashtags
Get suggestions for hashtags based on a keyword. See the recommend hashtags endpoint for more details.
const recommendHashtagsResponse = await social.recommendHashtags({
keyword: "social media",
}).catch(console.error);
Check Banned Hashtags
Check if a hashtag is banned on Instagram or other social networks. See the check banned hashtags endpoint for more details.
const checkBannedHashtagsResponse = await social.checkBannedHashtags({
hashtag: "socialmedia",
}).catch(console.error);
Get All Reviews
Retrieve all the reviews for the specified platform. See the get all reviews endpoint for more details.
const allReviewsResponse = await social.reviews({
platform: "facebook",
}).catch(console.error);
Get Single Review
Retrieve a single review. See the get single review endpoint for more details.
const singleReviewResponse = await social.review({
id: "Review ID",
platform: "gmb",
}).catch(console.error);
Reply to Review
Reply to a review. See the reply to review endpoint for more details.
const replyReviewResponse = await social.replyReview({
reviewId: "Review ID",
platform: "facebook",
reply: "Thank you for the review"
}).catch(console.error);
Delete Review Reply
Delete a review reply. See the delete review reply endpoint for more details.
const deleteReplyReviewResponse = await social.deleteReplyReview({
reviewId: "Review ID",
platform: "gmb",
}).catch(console.error);
Max Pack Required
Generate Post
Generate a new social post using ChatGPT. Token limits applicable. See the generate post endpoint for more details.
const generatePostResponse = await social.generatePost({
text: "I love social media",
hashtags: true,
emojis: true,
twitter: true,
}).catch(console.error);
Generate Rewrite
Generate variations of a social media post using ChatGPT. Token limits applicable. See the generate rewrite endpoint for more details.
const generateRewriteResponse = await social.generateRewrite({
post: "I love social media",
emojis: true,
hashtags: true,
twitter: true,
rewrites: 5,
}).catch(console.error);
Generate Transcription
Provide a transcription of a video file. See the generate transcription endpoint for more details.
const generateTranscriptionResponse = await social.generateTranscription({
videoUrl: "https://theVideo.mp4",
}).catch(console.error);
Generate Translation
Translate text for a post to over 100 different languages. See the generate translation endpoint for more details.
const generateTranslationResponse = await social.generateTranslation({
text: "I love social media",
lang: "es",
}).catch(console.error);
Generate Alt Text
Create AI-generated alt text for your images. See the generate alt text endpoint for more details.
const generateAltTextResponse = await social.generateAltText({
url: "https://theImage.jpg",
keywords: ["social media", "ayrshare"],
lang: "en"
}).catch(console.error);
Shorten link
Provide a URL and a shortened link will be returned. See the shorten link endpoint for more details.
const shortenLinkResponse = await social.shortLink({
url: "https://theURL.com",
utmId: "1234",
utmSource: "source",
utmMedium: "medium",
utmCampaign: "campaign",
utmTerm: "term",
utmContent: "content",
}).catch(console.error);
Analytics for Shortened Links
Return analytics for all shortened links or a single link for a given link ID. See the analytics link endpoint for more details.
const analyticsLinkResponse = await social.shortLinkAnalytics({
id: "Link ID",
fromCreatedDate: "2023-07-08T12:30:00Z",
toCreatedDate: "2023-07-08T12:30:00Z",
fromClickDate: "2023-07-08T12:30:00Z",
toClickDate: "2023-07-08T12:30:00Z",
}).catch(console.error);
Other Packages & Integrations
We have other package and integrations such as Python, Bubble.io, and Airtable + examples in PHP and Go.
Additional Information and Support
Additional examples, responses, etc. can be found at:
RESTful API Endpoint Docs
See our changelog for the latest and greatest.
Please contact us with your questions, or just to give us shout-out 📢!