Back to blog
AIGuides & Tutorials

How to Get Your Grok (XAI) API Key

Unlock the power of xAI with our complete guide to getting your Grok API key. Follow these step-by-step instructions to subscribe, generate, and test your key today.

Kateryna PoryvayKateryna Poryvay

Kateryna Poryvay

8 min read
How to Get Your Grok (XAI) API Key

Step 1: Ensure X Premium Subscription

Grok API access requires an active X Premium subscription:

  1. Go to x.com and log in to your account
  2. Click on "Premium" in the left sidebar
  3. Subscribe to either:
    • X Premium+: $16/month (higher API limits)
    • X Premium: $8/month (basic API access)
  4. Complete the subscription process with payment verification

Screenshot 2025-09-05 at 15.02.37

Note: API access may take 24-48 hours to activate after subscribing to Premium.

Step 2: Access the xAI Console

Navigate to the xAI developer platform:

  1. Go to console.x.ai
  2. Click "Sign in" and then choose "Login with X" to authenticate using your X account
  3. Authorize the xAI platform to access your account
  4. Complete any additional verification steps required

Screenshot 2025-09-05 at 14.58.41

If you don't see the console option, ensure:

  • Your X Premium subscription is active
  • You've waited the activation period (up to 48 hours)
  • Your account is in good standing (no violations)

Step 3: Complete Developer Onboarding

On first access, you'll need to complete the developer setup:

  • Verify developer information: Provide your name and organization (if applicable)
  • Describe your use case: Explain how you plan to use the Grok API
  • Accept terms of service: Review and accept xAI's API terms and usage policies
  • Configure account settings: Set your timezone and notification preferences

Step 4: Navigate to API Keys Section

Once in the xAI console, locate the API key management area:

  1. Click on "API Keys" in the main navigation menu
  2. Or navigate to "Settings" → "API Keys"
  3. You'll see the API key dashboard showing:
    • Existing keys (if any)
    • Usage statistics
    • Rate limit information
    • Key management options

Step 5: Generate Your API Key

Screenshot 2025-09-05 at 15.01.47

Click the "Create New Key" or "Generate API Key" button:

Configure your key settings:

  • Key name: Use descriptive names like "Production Bot", "Development Testing", or "Research Project"
  • Permissions: Select the appropriate access level:
    • Read-only: For querying and analysis
    • Read/Write: For full API capabilities
  • Model access: Choose which Grok models to enable:
    • grok-1: Standard model
    • grok-1.5: Enhanced capabilities
    • grok-2: Latest model (if available)
  • Rate limits: Configure custom limits if needed

Step 6: Save Your API Key Securely

Critical Security Notice: Your API key will only be shown once. Copy it immediately:

xai-________________________________

Grok API keys typically start with "xai-". Store your key securely:

  • Environment variable: GROK_API_KEY or XAI_API_KEY
  • Use secure vaults (1Password, Bitwarden for teams)
  • Encrypted configuration management
  • Never commit to version control or expose in frontend code

Step 7: Configure Billing and Limits

Set up your API billing preferences:

  1. Navigate to "Billing" in the console
  2. Your X Premium subscription covers base API access
  3. Configure additional settings:
    • Usage caps: Set daily/monthly maximum spending
    • Overage handling: Choose to stop or continue at higher rates
    • Alert thresholds: Set up notifications at 50%, 75%, 90% usage
    • Auto-recharge: Enable for uninterrupted service (optional)

Pricing structure (subject to change):

  • X Premium: 10,000 requests/month included
  • X Premium+: 50,000 requests/month included
  • Additional requests: $0.001 per request

Step 8: Test Your API Key

SCR-20250905-nhrz

Verify your key with a test request using curl:

curl https://api.x.ai/v1/chat/completions \
  -H "Authorization: Bearer YOUR_API_KEY_HERE" \
  -H "Content-Type: application/json" \
  -d '{
    "model": "grok-1",
    "messages": [
      {
        "role": "user",
        "content": "What is happening on X today?"
      }
    ],
    "stream": false,
    "temperature": 0.7
  }'

Replace YOUR_API_KEY_HERE with your actual API key. A successful response will contain Grok's reply.

Step 9: Understand Rate Limits and Quotas

Grok API limits vary by subscription tier:

X Premium (Basic)

  • 100 requests per minute
  • 10,000 requests per month
  • 4,096 max tokens per request
  • 2 concurrent requests

X Premium+ (Enhanced)

  • 500 requests per minute
  • 50,000 requests per month
  • 8,192 max tokens per request
  • 10 concurrent requests

Enterprise (Custom)

  • Negotiated limits
  • Priority queue access
  • Dedicated support
  • SLA guarantees

Step 10: Implement Real-time Features

Grok's unique advantage is X platform integration:

import os
import requests

headers = {
    "Authorization": f"Bearer {os.getenv('GROK_API_KEY')}",
    "Content-Type": "application/json"
}

# Query with real-time X context
payload = {
    "model": "grok-1",
    "messages": [
        {
            "role": "user",
            "content": "What are people saying about the Olympics right now?"
        }
    ],
    "enable_x_context": True,  # Enable real-time X data
    "include_trending": True,   # Include trending topics
    "max_tokens": 1000
}

response = requests.post(
    "https://api.x.ai/v1/chat/completions",
    headers=headers,
    json=payload
)

Security Best Practices

Protect your Grok API keys:

  • Link to X account security: Enable 2FA on your X account
  • Regular rotation: Regenerate keys every 60 days
  • Monitoring: Use xAI console to track unusual activity
  • IP restrictions: Whitelist specific IP addresses when possible
  • Separate environments: Use different keys for dev/staging/production

Managing Team Access

For organizations using Grok:

  • X Premium Organization: Set up organizational billing
  • Role-based access: Assign different permission levels
  • Shared workspace: Collaborate without sharing keys
  • Audit logging: Track all API key usage and changes
  • Compliance tools: Export usage data for reporting

Monitoring and Analytics

Track your Grok API usage:

xAI Console Dashboard

  • Real-time request counts
  • Token usage breakdown
  • Error rate tracking
  • Response time metrics

X Platform Integration

  • Monitor mentions of your bot/app
  • Track user engagement metrics
  • Analyze conversation patterns
  • Measure impact on X platform

Custom Analytics

  • Log all API interactions
  • Track cost per user/feature
  • Monitor model performance
  • Analyze prompt effectiveness

Troubleshooting Common Issues

"Invalid API key" error

  • Verify X Premium subscription is active
  • Check if key was properly copied (no spaces)
  • Ensure key hasn't been revoked
  • Confirm account has API access enabled

"Rate limit exceeded" error

  • Check current usage in xAI console
  • Implement exponential backoff
  • Consider upgrading to Premium+
  • Distribute requests over time

"No X context available" error

  • Ensure enable_x_context is set to true
  • Verify your X account has necessary permissions
  • Check if the topic has sufficient X activity
  • Try broadening the query scope

Account access issues

  • Verify X account is not suspended
  • Check Premium subscription status
  • Ensure phone number is verified
  • Clear browser cache and cookies

Advanced Features

Streaming responses

const eventSource = new EventSource(
  'https://api.x.ai/v1/chat/completions',
  {
    headers: {
      'Authorization': `Bearer ${apiKey}`,
      'Content-Type': 'application/json'
    }
  }
);

eventSource.onmessage = (event) => {
  const data = JSON.parse(event.data);
  // Process streaming chunks
};

X Platform Integration

  • Access real-time trending topics
  • Analyze sentiment around specific hashtags
  • Get context from recent X posts
  • Integrate with X Spaces audio content
  • Leverage user's X graph for personalization

Use Cases and Applications

Grok API excels at:

  • Real-time commentary: Events, news, and trending topics
  • Social listening: Brand monitoring and sentiment analysis
  • Content creation: X-optimized posts and threads
  • Trend analysis: Identify emerging topics and discussions
  • Customer service: Respond to X mentions and DMs
  • Research tools: Analyze public discourse on X

Unique Grok Features

Leverage Grok's distinctive capabilities:

  • Humor mode: Enable witty and entertaining responses
  • Real-time awareness: Access to current X conversations
  • Unfiltered mode: Less restrictive content generation (use responsibly)
  • X-native formatting: Automatic hashtag and mention suggestions
  • Thread generation: Create multi-post X threads
  • Trend prediction: Identify likely viral content

Migration from Other Providers

Key differences when switching to Grok:

  • X integration: Built-in access to X platform data
  • Authentication: Tied to X account rather than separate login
  • Billing: Through X Premium subscription
  • Rate limits: Generally lower than major providers
  • Unique personality: More casual and humorous tone options
  • Real-time data: Strongest for current events on X

Compliance and Guidelines

When using Grok API:

  • Respect X platform rules: Follow X's terms of service
  • Content policies: Adhere to xAI's usage guidelines
  • User privacy: Don't expose private X data
  • Attribution: Clearly identify AI-generated content
  • Rate limiting: Respect limits to maintain service quality
  • Automation rules: Follow X's automation and bot policies

Next Steps

With your API key ready:

  • Review the official xAI documentation
  • Test Grok's unique humor and personality settings
  • Implement X platform integration features
  • Set up webhook notifications for mentions
  • Explore real-time trending analysis capabilities
  • Build X-native applications and bots

Additional Resources

  • Follow @xai for API updates
  • Join the xAI developer community on X
  • Review example implementations and templates
  • Subscribe to the xAI developer newsletter
  • Check the status page for API availability
  • Explore Grok's model capabilities and limitations

Best Practices for X Integration

Maximize Grok's X platform synergy:

  • Cache responses to minimize redundant API calls
  • Use X's API in conjunction with Grok for full functionality
  • Implement proper error handling for both APIs
  • Monitor X platform changes that might affect context
  • Test with various types of X content (text, images, videos)
  • Consider time zones when analyzing trending topics

Remember that Grok's primary advantage is its deep integration with the X platform and access to real-time social data. Design your applications to leverage this unique capability, especially for use cases requiring current social context and trending information.

Ready to get started?

Scale your integration strategy and deliver the integrations your customers need in record time.

Ready to get started?
Talk to an expert

Trusted by fast-moving product & engineering teams

Nmbrs
Benefex
Invoice2go by BILL
Trengo
Ponto | Isabel Group
Apideck Blog

Insights, guides, and updates from Apideck

Discover company news, API insights, and expert blog posts. Explore practical integration guides and tech articles to make the most of Apideck's platform.

The Complete Guide to Building Workday  HRIS API Integrations
Unified APIHRIS

The Complete Guide to Building Workday HRIS API Integrations

Learn how to build production-ready Workday API integrations with complete code examples, authentication patterns, and real-world error handling strategies. Compare SOAP vs REST endpoints, handle rate limits, manage biannual updates, and discover why unified APIs eliminate 80% of integration complexity.

Saurabh Rai

Saurabh Rai

14 min read
How to Get Your Perplexity API Key
AIGuides & Tutorials

How to Get Your Perplexity API Key

This guide walks you through how to get your Perplexity API key and start building with it. From there, it explains the must-know compliance rules and best practices, like showing citations, respecting source policies, handling rate limits, and caching responses, so you can use the API securely and effectively.

Kateryna Poryvay

Kateryna Poryvay

8 min read
Understanding Authorization When Building a Microsoft Business Central API Integration
Unified APIAccounting

Understanding Authorization When Building a Microsoft Business Central API Integration

Building a Microsoft Business Central API integration means dealing with Azure AD registration, OAuth nuances, and complex permission models. Learn how unified APIs like Apideck cut development time, abstract away authentication challenges, and deliver reliable ERP integrations faster.

Saurabh Rai

Saurabh Rai

15 min read