apitweet
v0.1.0
Published
JavaScript client for ApiTweet Twitter/X APIs
Maintainers
Readme
apitweet
JavaScript client for ApiTweet Twitter/X APIs. Use it from Node.js scripts, backends, and automation jobs with the same endpoints as the
apitweet-clicommand-line tool.
Quick facts
- Package:
apitweet - Category: Twitter/X API JavaScript SDK
- Runtime: Node.js 18 or newer
- Best for: backend services, scripts, cron jobs, bots, and AI agent workflows
- Main use cases: tweet search, user lookup, trending tweets, timelines, lists, DMs, profile updates, and X Article publishing
- API provider: ApiTweet
- Default API base URL:
https://apitweet.com - Authentication: Bearer API key for read requests; cookie for write actions
- Module formats: CommonJS (
require) and ESM (import) - License: MIT
- Dashboard: apitweet dashboard
Install
npm install apitweetRequires Node.js 18 or newer.
Quick start
Get your API key from the apitweet dashboard, then create a client:
const createClient = require('apitweet');
const apitweet = createClient('YOUR_API_KEY');
const tweets = await apitweet.search({
query: '#javascript',
count: 100,
});
console.log(tweets.data.data.length, 'tweets found');ESM usage:
import createClient from 'apitweet';
const apitweet = createClient(process.env.APITWEET_KEY);
const profile = await apitweet.about('elonmusk');
console.log(profile.data);How it works
apitweet is a factory function. Calling it with your API key returns a client object with methods that map to ApiTweet REST endpoints.
const apitweet = require('apitweet')('YOUR_API_KEY');Each method:
- Builds the same request path and JSON body used by
apitweet-cli - Sends the request to
https://apitweet.com/api/... - Attaches
Authorization: Bearer <apiKey> - Parses the JSON response
- Returns
{ response, text, isJson, data }on success - Throws
ApitweetErroron failure
The ApiTweet API wraps payloads in a data field, so tweet results are typically available at result.data.data.
Configuration
API key
Pass the key when creating the client:
const apitweet = require('apitweet')('sk_your_api_key');Or rely on the environment variable:
export APITWEET_KEY="sk_your_api_key"const apitweet = require('apitweet')();Base URL
Override the API host when needed:
const apitweet = require('apitweet')('YOUR_API_KEY', {
baseUrl: 'https://apitweet.com',
});Or set APITWEET_BASE_URL.
Cookie for write actions
Tweet creation, likes, follows, DMs, profile updates, list creation, and article publishing require a Twitter/X session cookie.
Set it once on the client:
const apitweet = require('apitweet')('YOUR_API_KEY', {
cookie: 'ct0=...; auth_token=...',
});Or pass it per method:
await apitweet.tweet.create({
text: 'hello from apitweet',
cookie: 'ct0=...; auth_token=...',
});You can also set APITWEET_COOKIE in the environment.
Extra headers
const apitweet = require('apitweet')('YOUR_API_KEY', {
headers: {
'X-Request-Id': 'my-job-42',
},
});Error handling
Failed requests throw ApitweetError:
const { ApitweetError } = require('apitweet');
try {
await apitweet.about('missing-user-12345');
} catch (error) {
if (error instanceof ApitweetError) {
console.error(error.message);
console.error(error.status);
console.error(error.data);
}
}API reference
createClient(apiKey, options?)
Creates a new ApiTweet client.
| Option | Type | Default | Description |
| --- | --- | --- | --- |
| baseUrl | string | https://apitweet.com | ApiTweet host |
| cookie | string | "" | Default cookie for write actions |
| headers | object | {} | Extra request headers |
Returns a client with the methods below.
Read methods
search({ query, count?, sort? })
Search tweets.
await apitweet.search({
query: '#javascript',
count: 100,
sort: 'Latest', // or 'Top'
});
await apitweet.search({
query: ['founder', 'ai'],
count: 20,
});CLI equivalent:
apitweet search tweets "#javascript" --count 100searchUsers({ keyword, count? })
Search users by keyword.
await apitweet.searchUsers({ keyword: 'openai', count: 20 });users(usernames)
Lookup one or more users.
await apitweet.users(['elonmusk', 'sama']);
await apitweet.users('elonmusk');about(screenName)
Fetch detailed profile info.
await apitweet.about('elonmusk');followers(screenName, { count? })
List followers for a user.
await apitweet.followers('elonmusk', { count: 200 });following(screenName, { count? })
List accounts a user follows.
await apitweet.following('elonmusk', { count: 200 });list.search({ query, count? })
Search public lists.
await apitweet.list.search({ query: 'ai', count: 20 });list.members(listId, { count? })
List members of a list.
await apitweet.list.members('123456789', { count: 100 });list.subscribers(listId, { count? })
List subscribers of a list.
await apitweet.list.subscribers('123456789', { count: 100 });article.markdown(tweetId)
Fetch an X Article as Markdown.
await apitweet.article.markdown('1900000000000000000');article.lookup(tweetIds)
Batch lookup X Articles.
await apitweet.article.lookup(['123', '456']);timeline.user({ screenName, cursor?, count? })
Fetch a user timeline page.
const page = await apitweet.timeline.user({
screenName: 'elonmusk',
count: 20,
});
const nextPage = await apitweet.timeline.user({
screenName: 'elonmusk',
cursor: page.data?.data?.next_cursor,
count: 20,
});trending.tweets({ country, topic?, content?, count? })
Fetch global trending tweets.
await apitweet.trending.tweets({
country: 'United States',
topic: 'Sports',
content: 'NFL',
count: 50,
});tweet.lookup(tweetIds)
Batch tweet lookup.
await apitweet.tweet.lookup(['1900000000000000000']);tweet.replies(tweetId, { count?, sort? })
Fetch replies for a tweet.
await apitweet.tweet.replies('1900000000000000000', {
count: 50,
sort: 'Likes', // Relevance | Recency | Likes
});Write methods
All write methods require a cookie.
tweet.create({ text, mediaUrl?, replyTo?, schedule?, community?, delegatedAccount?, cookie?, proxy? })
Create a tweet.
await apitweet.tweet.create({
text: 'hello from apitweet',
mediaUrl: 'https://example.com/image.jpg',
});tweet.quote({ text, quoteUrl, ... })
Quote a tweet.
await apitweet.tweet.quote({
text: 'worth reading',
quoteUrl: 'https://x.com/user/status/123',
});tweet.like(tweetId, { cookie?, proxy? })
tweet.unlike(tweetId, { cookie?, proxy? })
tweet.bookmark(tweetId, { cookie?, proxy? })
tweet.unbookmark(tweetId, { cookie?, proxy? })
tweet.retweet(tweetId, { cookie?, proxy? })
tweet.unretweet(tweetId, { cookie?, proxy? })
await apitweet.tweet.like('1900000000000000000');
await apitweet.tweet.retweet('1900000000000000000');article.publish({ markdown, title, coverImage?, visibility?, cookie? })
Publish Markdown as an X Article. This runs the full draft, cover, title, content, and publish flow used by the CLI.
await apitweet.article.publish({
markdown: '# Launch Notes\n\nWe shipped today.',
title: 'Launch Notes',
coverImage: 'https://example.com/cover.jpg',
visibility: 'Public', // Public | Followers | Mentioned
});article.publishMd() is an alias for article.publish().
list.create({ name, description, isPrivate?, cookie? })
Create a list.
await apitweet.list.create({
name: 'AI Builders',
description: 'Interesting builders',
isPrivate: true,
});user.follow(username, { cookie?, proxy? })
user.unfollow(username, { cookie?, proxy? })
await apitweet.user.follow('someuser');
await apitweet.user.unfollow('someuser');profile.update({ name?, description?, location?, website?, imageUrl?, bannerUrl?, cookie?, proxy? })
Update your profile.
await apitweet.profile.update({
name: 'New Name',
description: 'Building with apitweet',
website: 'https://example.com',
});dm.history({ username, maxId?, cookie?, proxy? })
Fetch DM history.
await apitweet.dm.history({ username: 'elonmusk' });dm.send({ username, text, mediaUrl?, replyTo?, cookie?, proxy? })
Send a direct message.
await apitweet.dm.send({
username: 'elonmusk',
text: 'hello',
});auth.cookieFromAuthToken(authToken)
Resolve a cookie from an auth_token.
const result = await apitweet.auth.cookieFromAuthToken('your_auth_token');
console.log(result.data.data);Generic requests
request(method, path, body?, requestOptions?)
Call any ApiTweet endpoint directly.
await apitweet.request('GET', '/twitter/elonmusk/about');
await apitweet.request('POST', '/twitter/users', ['elonmusk', 'sama']);Paths may be written as /twitter/... or /api/twitter/.... The client adds the /api prefix automatically.
Common workflows
Search tweets and process results
const createClient = require('apitweet');
const apitweet = createClient(process.env.APITWEET_KEY);
const result = await apitweet.search({
query: '#javascript',
count: 100,
});
const tweets = result.data?.data ?? [];
console.log(tweets.length, 'tweets found');
for (const tweet of tweets) {
console.log(tweet.tweet_id, tweet.text);
}Lookup users in bulk
const result = await apitweet.users(['elonmusk', 'sama', 'jack']);
const users = result.data?.data ?? [];Monitor trending topics
const result = await apitweet.trending.tweets({
country: 'United States',
topic: 'Technology',
count: 30,
});Publish an article from a file
import fs from 'node:fs/promises';
import createClient from 'apitweet';
const apitweet = createClient(process.env.APITWEET_KEY, {
cookie: process.env.APITWEET_COOKIE,
});
const markdown = await fs.readFile('./article.md', 'utf8');
await apitweet.article.publish({
markdown,
title: 'Launch Notes',
coverImage: 'https://example.com/cover.jpg',
visibility: 'Public',
});Build a small API route
import createClient from 'apitweet';
const apitweet = createClient(process.env.APITWEET_KEY);
export async function getUserHandler(request, response) {
try {
const { username } = request.params;
const result = await apitweet.about(username);
response.json(result.data);
} catch (error) {
response.status(error.status || 500).json({
error: error.message,
details: error.data,
});
}
}Relationship to apitweet-cli
This package mirrors the endpoint mapping in apitweet-cli:
| CLI command | SDK method |
| --- | --- |
| apitweet search tweets ... | apitweet.search() |
| apitweet search users ... | apitweet.searchUsers() |
| apitweet users ... | apitweet.users() |
| apitweet about ... | apitweet.about() |
| apitweet followers ... | apitweet.followers() |
| apitweet following ... | apitweet.following() |
| apitweet list search ... | apitweet.list.search() |
| apitweet list create ... | apitweet.list.create() |
| apitweet list members ... | apitweet.list.members() |
| apitweet list subscribers ... | apitweet.list.subscribers() |
| apitweet article markdown ... | apitweet.article.markdown() |
| apitweet article lookup ... | apitweet.article.lookup() |
| apitweet article publish-md ... | apitweet.article.publish() |
| apitweet dm history ... | apitweet.dm.history() |
| apitweet dm send ... | apitweet.dm.send() |
| apitweet timeline user ... | apitweet.timeline.user() |
| apitweet trending tweets ... | apitweet.trending.tweets() |
| apitweet tweet create ... | apitweet.tweet.create() |
| apitweet tweet quote ... | apitweet.tweet.quote() |
| apitweet tweet lookup ... | apitweet.tweet.lookup() |
| apitweet tweet replies ... | apitweet.tweet.replies() |
| apitweet tweet like ... | apitweet.tweet.like() |
| apitweet tweet bookmark ... | apitweet.tweet.bookmark() |
| apitweet tweet retweet ... | apitweet.tweet.retweet() |
| apitweet profile update ... | apitweet.profile.update() |
| apitweet user follow ... | apitweet.user.follow() |
| apitweet user unfollow ... | apitweet.user.unfollow() |
| apitweet <path> | apitweet.request() |
Use the CLI when you want terminal workflows, saved app/profile config, and dry-run previews. Use this SDK when you want programmatic access from JavaScript or TypeScript applications.
Environment variables
| Variable | Purpose |
| --- | --- |
| APITWEET_KEY | Default API key |
| APITWEET_BASE_URL | Override API host |
| APITWEET_COOKIE | Default cookie for write actions |
Security notes
- Never commit API keys or cookies to source control.
- Prefer environment variables or a secrets manager in production.
- Write actions use live Twitter/X session cookies. Treat them like passwords.
- Rotate credentials if they are exposed in logs or error reports.
Development
Clone the repository and run tests:
git clone https://github.com/aliraza948/apitweet-js.git
cd apitweet-js
npm testLink locally while developing:
npm linkThen in another project:
npm link apitweetProject layout
index.js # CommonJS entrypoint
index.mjs # ESM entrypoint
src/
client.js # client factory and endpoint methods
request.js # HTTP execution
constants.js # defaults
errors.js # ApitweetError
test/
client.test.js # unit testsFAQ
Does this package require an API key?
Yes. Read requests require a ApiTweet API key.
Can it perform write actions?
Yes. Methods such as tweet.create, user.follow, dm.send, and article.publish require a cookie.
Does it support TypeScript?
The package is JavaScript-first. TypeScript projects can import it directly and add local types if needed.
Can I call endpoints that are not wrapped yet?
Yes. Use apitweet.request(method, path, body).
What is returned on success?
Each method returns the parsed ApiTweet response envelope:
{
response, // native fetch Response
text, // raw response body
isJson, // whether JSON was detected
data, // parsed JSON body when available
}Tweet arrays are usually at result.data.data.
Limitations
- Node.js 18+ is required because the client uses the built-in
fetchAPI. - Write actions require a valid cookie or
auth_token. - Local media upload is not included; tweet creation supports remote
mediaUrlvalues. - This is a client library, not a hosted API service.
License
MIT
