Authentication
Complete guide to API authentication, API keys, security best practices, and troubleshooting authentication issues.
Overview
All API requests require authentication using an API key. This guide covers everything you need to know about authenticating your requests, securing your API keys, and handling authentication errors.
Authentication Method
The API uses API Key authentication via HTTP headers. This is a simple and secure method that works with all HTTP clients.
Getting Your API Key
Step 1: Choose a Platform
The API is available on multiple platforms:
- RapidAPI: Large marketplace with multiple payment options
- JoJoAPI: Smaller marketplace with lower fees (10% cheaper)
- Direct Gateway: Direct access with 20% discount
Step 2: Sign Up
- Visit your chosen platform
- Create an account
- Subscribe to a plan (free plans available)
- Get your API key from the dashboard
Step 3: Get Gateway URL
- RapidAPI/JoJoAPI: Use their provided endpoint URLs (found in dashboard)
- Direct Gateway: Contact us to get your gateway URL and API key
Direct Gateway Contact:
- Telegram: @benagain - Fastest response (usually within hours)
- Email: vipertools@proton.me - For detailed inquiries
What to include: Mention you want to use the Direct Gateway, your preferred plan, and any questions you have. We'll provide your API key and gateway URL.
Using Your API Key
Header Format
Include your API key in every request using the X-API-KEY header:
X-API-KEY: YOUR_API_KEYcURL Example
curl --request GET \
--url 'https://<direct.gateway>/tweet/123456789' \
--header 'X-API-KEY: YOUR_API_KEY'JavaScript Example
const response = await fetch('https://<direct.gateway>/tweet/123456789', {
headers: {
'X-API-KEY': 'YOUR_API_KEY'
}
});Python Example
import requests
response = requests.get(
'https://<direct.gateway>/tweet/123456789',
headers={'X-API-KEY': 'YOUR_API_KEY'}
)Node.js (axios) Example
const axios = require('axios');
const response = await axios.get('https://<direct.gateway>/tweet/123456789', {
headers: {
'X-API-KEY': 'YOUR_API_KEY'
}
});Security Best Practices
1. Never Commit API Keys
❌ Bad:
// Don't do this!
const API_KEY = 'sk_live_1234567890abcdef';✅ Good:
// Use environment variables
const API_KEY = process.env.API_KEY;2. Use Environment Variables
Node.js:
// .env file
API_KEY=your_api_key_here
// In code
require('dotenv').config();
const API_KEY = process.env.API_KEY;Python:
# .env file
API_KEY=your_api_key_here
# In code
from dotenv import load_dotenv
import os
load_dotenv()
API_KEY = os.getenv('API_KEY')Browser (Client-Side):
// ⚠️ Warning: Never expose API keys in client-side code!
// Use a backend proxy instead
// Backend proxy
app.get('/api/tweet/:id', async (req, res) => {
const response = await fetch(`https://<direct.gateway>/tweet/${req.params.id}`, {
headers: { 'X-API-KEY': process.env.API_KEY }
});
const data = await response.json();
res.json(data);
});3. Rotate API Keys Regularly
// Implement key rotation
async function rotateAPIKey() {
// Generate new key
const newKey = await generateNewKey();
// Update in secure storage
await updateKeyInVault(newKey);
// Update environment
process.env.API_KEY = newKey;
// Revoke old key
await revokeOldKey();
}4. Use Key Management Services
AWS Secrets Manager:
const AWS = require('aws-sdk');
const secretsManager = new AWS.SecretsManager();
async function getAPIKey() {
const secret = await secretsManager.getSecretValue({
SecretId: 'twitter-api-key'
}).promise();
return JSON.parse(secret.SecretString).apiKey;
}HashiCorp Vault:
const vault = require('node-vault');
async function getAPIKey() {
const client = vault({
endpoint: 'https://vault.example.com',
token: process.env.VAULT_TOKEN
});
const secret = await client.read('secret/twitter-api-key');
return secret.data.apiKey;
}5. Restrict Key Permissions
- Use separate keys for different environments (dev, staging, prod)
- Rotate keys if compromised
- Monitor key usage for anomalies
Authentication Errors
401 Unauthorized
Error Response:
{
"error": {
"code": 401,
"message": "Unauthorized",
"details": "Invalid or missing API key"
}
}Common Causes:
- API key not included in request
- API key is incorrect
- API key has expired or been revoked
- API key format is invalid
Solutions:
function validateAPIKey(key) {
if (!key) {
throw new Error('API key is required');
}
if (typeof key !== 'string') {
throw new Error('API key must be a string');
}
if (key.length < 10) {
throw new Error('API key appears to be invalid');
}
return true;
}
// Usage
try {
validateAPIKey(API_KEY);
const response = await fetch(url, {
headers: { 'X-API-KEY': API_KEY }
});
} catch (error) {
console.error('API key validation failed:', error.message);
}Handling Authentication Errors
async function makeAuthenticatedRequest(url) {
try {
const response = await fetch(url, {
headers: { 'X-API-KEY': API_KEY }
});
if (response.status === 401) {
const error = await response.json();
// Log error for debugging
console.error('Authentication failed:', error);
// Check if key needs to be refreshed
if (error.details?.includes('expired')) {
await refreshAPIKey();
return makeAuthenticatedRequest(url); // Retry
}
throw new Error('Invalid API key');
}
if (!response.ok) {
throw new Error(`HTTP ${response.status}`);
}
return await response.json();
} catch (error) {
console.error('Request failed:', error);
throw error;
}
}Multi-Environment Setup
Environment-Specific Keys
// config.js
const config = {
development: {
apiKey: process.env.DEV_API_KEY,
baseUrl: 'https://dev-gateway.example.com'
},
staging: {
apiKey: process.env.STAGING_API_KEY,
baseUrl: 'https://staging-gateway.example.com'
},
production: {
apiKey: process.env.PROD_API_KEY,
baseUrl: 'https://direct.gateway'
}
};
const env = process.env.NODE_ENV || 'development';
module.exports = config[env];Usage
const config = require('./config');
const response = await fetch(`${config.baseUrl}/tweet/123`, {
headers: { 'X-API-KEY': config.apiKey }
});Testing Authentication
Test Valid Key
async function testAuthentication() {
const response = await fetch('https://<direct.gateway>/user/44196397', {
headers: { 'X-API-KEY': API_KEY }
});
if (response.ok) {
console.log('✅ Authentication successful');
} else if (response.status === 401) {
console.error('❌ Authentication failed');
}
}Test Invalid Key
async function testInvalidKey() {
const response = await fetch('https://<direct.gateway>/user/44196397', {
headers: { 'X-API-KEY': 'invalid_key' }
});
if (response.status === 401) {
console.log('✅ Correctly rejected invalid key');
}
}Troubleshooting
Issue: "Invalid API key" but key looks correct
Possible Causes:
- Extra whitespace in key
- Key copied incorrectly
- Key from wrong environment
Solutions:
// Trim whitespace
const cleanKey = API_KEY.trim();
// Verify key format
if (!/^[a-zA-Z0-9_-]+$/.test(cleanKey)) {
throw new Error('Invalid API key format');
}Issue: Key works in one environment but not another
Possible Causes:
- Different keys for different environments
- Environment variable not set
- Key not loaded correctly
Solutions:
- Verify environment variables are set
- Check key is loaded from correct source
- Ensure key matches environment
Related Documentation
- Error Handling Guide - Handling 401 errors
- Rate Limits Guide - Rate limit information
- Best Practices - Security best practices
