Discover/X API
live

X APIdocs.x.ai

Retrieve current pricing for all xAI Grok models and services: chat, image/video generation, voice, tools, batch API, and storage — structured JSON via two endpoints.

This API takes change requests — .
Endpoints
2
Updated
1mo ago

What is the X API?

The xAI Pricing API exposes structured cost data across 6 service categories via 2 endpoints: get_pricing and get_model_pricing. get_pricing returns the full pricing surface in one call, covering fields like input/output token costs per 1M tokens for chat models, per-resolution image generation rates, voice mode tiers, server-side tool invocation costs per 1k calls, and storage download rates. get_model_pricing accepts a category parameter to scope the response to a single service area.

Try it

No input parameters required.

api.parse.bot/scraper/aa5ce901-2eef-4452-97a6-2dd2d8cee956/<endpoint>
Ready to send
Fill in the parameters and hit sign in to send to see live response data here.
Call it over HTTPgrab a free API key at signup
curl -X GET 'https://api.parse.bot/scraper/aa5ce901-2eef-4452-97a6-2dd2d8cee956/get_pricing' \
  -H 'X-API-Key: $PARSE_API_KEY'
Python SDK · recommended

Typed, relational, agent-ready

A generated client with real types, enums, and the links between objects — the structure a flat JSON response can't carry. Autocompletes in your editor and reads cleanly to coding agents.

  • Fully typed · autocompletes
  • Objects link to objects
  • Typed errors & pagination

Typed Python client. Set up the SDK in your uv project, then pull this API’s typed client:

uv add parse-sdk
uv run parse init
uv run parse add --marketplace docs-x-ai-api

uv run parse add --marketplace pulls a pinned snapshot of this canonical API — it won’t change underneath you. To customize it, subscribe and swap to your own copy.

"""
xAI Pricing API Client
Retrieve pricing information for all xAI (Grok) models and services.
Get your API key from: https://parse.bot/settings
"""

import os
import requests
from typing import Optional, Literal


class ParseClient:
    """Client for interacting with the xAI Pricing API via Parse."""

    def __init__(self, api_key: Optional[str] = None):
        """
        Initialize the Parse client.

        Args:
            api_key: Your Parse API key. Defaults to PARSE_API_KEY env var.
        """
        self.base_url = "https://api.parse.bot"
        self.scraper_id = "aa5ce901-2eef-4452-97a6-2dd2d8cee956"
        self.api_key = api_key or os.getenv("PARSE_API_KEY")

        if not self.api_key:
            raise ValueError("API key is required. Pass it or set PARSE_API_KEY env var.")

    def _call(self, endpoint: str, method: str = "POST", **params) -> dict:
        """
        Make an API call to the Parse bot.

        Args:
            endpoint: The endpoint name (e.g., 'get_pricing')
            method: HTTP method ('GET' or 'POST')
            **params: Query/body parameters

        Returns:
            Response JSON as dictionary
        """
        url = f"{self.base_url}/scraper/{self.scraper_id}/{endpoint}"
        headers = {"X-API-Key": self.api_key, "Content-Type": "application/json"}

        if method.upper() == "GET":
            response = requests.get(url, headers=headers, params=params)
        elif method.upper() == "POST":
            response = requests.post(url, headers=headers, json=params)
        else:
            raise ValueError(f"Unsupported HTTP method: {method}")

        response.raise_for_status()
        return response.json()

    def get_pricing(self) -> dict:
        """
        Get all xAI model and service pricing information.

        Returns pricing for Chat API, Imagine API (image/video), Voice API,
        Tools, Batch API comparisons, and storage costs. All prices in USD.

        Returns:
            Dictionary containing all pricing categories
        """
        return self._call("get_pricing", method="GET")

    def get_model_pricing(
        self, category: Literal["all", "chat", "imagine", "voice", "tools", "batch", "storage"] = "all"
    ) -> dict:
        """
        Get xAI pricing filtered by service category.

        Args:
            category: Pricing category to retrieve. Defaults to 'all'.
                     Options: all, chat, imagine, voice, tools, batch, storage

        Returns:
            Dictionary containing pricing for the specified category
        """
        return self._call("get_model_pricing", method="GET", category=category)


def format_price(price_str: str) -> str:
    """Format price string for display."""
    return price_str.replace("$", "").strip()


def find_cheapest_chat_model(pricing_data: dict) -> Optional[dict]:
    """Find the cheapest chat model based on input token pricing."""
    if not pricing_data.get("chat_api"):
        return None

    chat_models = pricing_data["chat_api"]
    return min(chat_models, key=lambda m: float(format_price(m["input_per_1m_tokens"])))


def find_most_expensive_chat_model(pricing_data: dict) -> Optional[dict]:
    """Find the most expensive chat model based on input token pricing."""
    if not pricing_data.get("chat_api"):
        return None

    chat_models = pricing_data["chat_api"]
    return max(chat_models, key=lambda m: float(format_price(m["input_per_1m_tokens"])))


def calculate_monthly_cost(tokens: int, model_pricing: dict, cached_ratio: float = 0.0) -> float:
    """
    Calculate estimated monthly cost for token usage.

    Args:
        tokens: Number of tokens to process per month
        model_pricing: Model pricing dict from chat_api
        cached_ratio: Ratio of cached tokens (0.0 to 1.0)

    Returns:
        Estimated monthly cost in USD
    """
    input_price = float(format_price(model_pricing["input_per_1m_tokens"]))
    cached_price = float(format_price(model_pricing["cached_input_per_1m_tokens"]))

    regular_tokens = tokens * (1 - cached_ratio)
    cached_tokens = tokens * cached_ratio

    cost = (regular_tokens * input_price + cached_tokens * cached_price) / 1_000_000
    return cost


if __name__ == "__main__":
    # Initialize the client
    client = ParseClient()

    print("=" * 70)
    print("xAI PRICING ANALYSIS")
    print("=" * 70)

    # Get all pricing data
    print("\n📊 Fetching complete pricing information...")
    all_pricing = client.get_pricing()

    # Analyze chat models
    print("\n💬 CHAT API MODELS:")
    print("-" * 70)
    if "chat_api" in all_pricing:
        for model in all_pricing["chat_api"]:
            print(f"\n  Model: {model['model']}")
            print(f"    Context Window: {model['context']}")
            print(f"    Input Cost: {model['input_per_1m_tokens']} per 1M tokens")
            print(f"    Cached Input: {model['cached_input_per_1m_tokens']} per 1M tokens")
            print(f"    Output Cost: {model['output_per_1m_tokens']} per 1M tokens")

    # Find cost-effective models
    print("\n" + "=" * 70)
    print("💰 COST ANALYSIS:")
    print("-" * 70)

    cheapest = find_cheapest_chat_model(all_pricing)
    if cheapest:
        print(f"\n✅ Cheapest Model: {cheapest['model']}")
        print(f"   Input Cost: {cheapest['input_per_1m_tokens']}")

    most_expensive = find_most_expensive_chat_model(all_pricing)
    if most_expensive:
        print(f"\n⚠️  Most Expensive Model: {most_expensive['model']}")
        print(f"   Input Cost: {most_expensive['input_per_1m_tokens']}")

    # Calculate monthly costs for different scenarios
    print("\n📈 MONTHLY COST PROJECTIONS (100M tokens/month):")
    print("-" * 70)
    if "chat_api" in all_pricing:
        monthly_tokens = 100_000_000
        for model in all_pricing["chat_api"][:2]:  # Show top 2 models
            cost_no_cache = calculate_monthly_cost(monthly_tokens, model, cached_ratio=0.0)
            cost_with_cache = calculate_monthly_cost(monthly_tokens, model, cached_ratio=0.3)
            print(f"\n  {model['model']}:")
            print(f"    Without caching: ${cost_no_cache:,.2f}")
            print(f"    With 30% caching: ${cost_with_cache:,.2f}")
            print(f"    Monthly savings: ${cost_no_cache - cost_with_cache:,.2f}")

    # Get specific category pricing
    print("\n" + "=" * 70)
    print("🎨 IMAGE GENERATION (IMAGINE API):")
    print("-" * 70)
    imagine_pricing = client.get_model_pricing(category="imagine")
    if "imagine_api" in imagine_pricing:
        for model in imagine_pricing["imagine_api"]:
            print(f"\n  Model: {model['model']}")
            print(f"  Media Input: {model['media_input']}")
            print(f"  Output Pricing:")
            for res in model["resolutions"]:
                print(f"    {res['resolution']}: {res['output']}")

    # Check voice pricing
    print("\n" + "=" * 70)
    print("🎤 VOICE API:")
    print("-" * 70)
    voice_pricing = client.get_model_pricing(category="voice")
    if "voice_api" in voice_pricing:
        for voice in voice_pricing["voice_api"]:
            print(f"\n  Mode: {voice['mode']}")
            print(f"  Cost: {voice['cost']}")

    # Check tools pricing
    print("\n" + "=" * 70)
    print("🔧 TOOLS PRICING:")
    print("-" * 70)
    tools_pricing = client.get_model_pricing(category="tools")
    if "tools_pricing" in tools_pricing:
        for tool in tools_pricing["tools_pricing"]:
            print(f"\n  Tool: {tool['tool']} ({tool['tool_name']})")
            print(f"    {tool['description']}")
            print(f"    Cost: {tool['cost_per_1k_calls']}")

    # Check storage pricing
    print("\n" + "=" * 70)
    print("💾 STORAGE & FILES:")
    print("-" * 70)
    storage_pricing = client.get_model_pricing(category="storage")
    if "files_and_collections" in storage_pricing:
        fc = storage_pricing["files_and_collections"]
        if "storage" in fc:
            print("\n  Storage Rates:")
            for item in fc["storage"]:
                print(f"    {item['resource']}: {item['rate']}")
        if "downloads" in fc:
            print("\n  Download Rates:")
            for item in fc["downloads"]:
                print(f"    {item['resource']}: {item['rate']}")

    print("\n" + "=" * 70)
    print("✅ Pricing analysis complete!")
    print("=" * 70)
All endpoints · 2 totalmissing one? ·

Get all xAI model and service pricing information. Returns pricing for Chat API, Imagine API (image/video), Voice API, Tools, Batch API comparisons, and Files & Collections storage costs. All prices are in USD.

Input

No input parameters required.

Response
{
  "type": "object",
  "fields": {
    "chat_api": "array of chat model pricing objects with model name, context window, input/cached/output token costs per 1M tokens",
    "batch_api": "array comparing real-time vs batch API features",
    "voice_api": "array of voice mode pricing (realtime, TTS, STT)",
    "imagine_api": "array of image/video generation model pricing with per-resolution output costs",
    "tools_pricing": "array of server-side tool invocation costs per 1k calls",
    "files_and_collections": "object with storage and download rate arrays"
  },
  "sample": {
    "chat_api": [
      {
        "model": "grok-build-0.1",
        "context": "256k",
        "input_per_1m_tokens": "$1.00",
        "output_per_1m_tokens": "$2.00",
        "cached_input_per_1m_tokens": "$0.20"
      },
      {
        "model": "grok-4.3",
        "context": "1M",
        "input_per_1m_tokens": "$1.25",
        "output_per_1m_tokens": "$2.50",
        "cached_input_per_1m_tokens": "$0.20"
      }
    ],
    "batch_api": [
      {
        "feature": "Token pricing",
        "batch_api": "20%-50% off standard rates",
        "realtime_api": "Standard rates"
      }
    ],
    "voice_api": [
      {
        "cost": "$0.05/ min ($3.00/ hr)",
        "mode": "Realtime"
      }
    ],
    "imagine_api": [
      {
        "model": "grok-imagine-image-quality",
        "media_input": "$0.01 / img",
        "resolutions": [
          {
            "output": "$0.05 / img",
            "resolution": "1K"
          },
          {
            "output": "$0.07 / img",
            "resolution": "2K"
          }
        ]
      }
    ],
    "tools_pricing": [
      {
        "tool": "Web Search",
        "tool_name": "web_search",
        "description": "Search the internet and browse web pages",
        "cost_per_1k_calls": "$5/ 1k calls"
      }
    ],
    "files_and_collections": {
      "storage": [
        {
          "rate": "$0.025 / GiB / day",
          "resource": "File storage"
        }
      ],
      "downloads": [
        {
          "rate": "$0.20 / GiB downloaded",
          "resource": "File downloads"
        }
      ]
    }
  }
}

About the X API

What the API Returns

get_pricing returns a single response object containing six typed arrays and objects: chat_api, batch_api, voice_api, imagine_api, tools_pricing, and files_and_collections. Each chat entry in chat_api includes the model name, context window size, and separate USD rates for input tokens, cached input tokens, and output tokens — all denominated per 1M tokens. The batch_api array provides a feature comparison between real-time and batch processing modes, useful for understanding throughput trade-offs at different price points.

Filtering by Category

get_model_pricing accepts an optional category string parameter with exactly six valid values: chat, imagine, voice, tools, batch, and storage. Passing all (or omitting the parameter and defaulting to the full set) returns the same structure as get_pricing. The response only includes fields relevant to the requested category — for example, category=imagine returns imagine_api with per-model, per-resolution output costs for image and video generation models, while category=storage returns only files_and_collections with storage and download rate arrays.

Voice, Tools, and Storage Details

voice_api entries cover three pricing tiers: realtime voice, text-to-speech (TTS), and speech-to-text (STT). tools_pricing lists server-side tool invocation costs expressed per 1,000 calls. The files_and_collections object contains two arrays — one for storage rates and one for download rates — making it possible to estimate costs for workloads that persist and retrieve files through xAI's storage layer.

Data Scope and Currency

All prices are denominated in USD. The API reflects the pricing published on the xAI developer pricing page at docs.x.ai. No authentication is required to call these endpoints, and neither endpoint accepts pagination or date-range parameters — the response always represents the current published rate card.

Reliability & maintenance

The X API is a managed, monitored endpoint for docs.x.ai — not a raw scraper you maintain. Every endpoint is automatically health-checked on a schedule, and when docs.x.ai changes and a check fails, the API is automatically queued for repair and re-verified. It is built to keep working as the site underneath it changes.

This isn't an official docs.x.ai API — it's an independent, maintained REST wrapper over public data. Where the source has no official API (or only a limited one), Parse gives you a stable contract over a source that never promised one, and keeps it current. Need a new endpoint or field? You can revise it yourself in plain English and the agent rebuilds it against the live site in minutes — contributing the change back to the shared API is free.

Will this API break when the source site changes?+
It's built not to. Every endpoint is health-checked on a schedule with automated test probes. When the source site changes and a check fails, the API is automatically queued for repair and re-verified — that's the self-healing layer. Each API page shows when its endpoints were last verified. And because marketplace APIs are shared, any fix reaches everyone using it.
Is this an official API from the source site?+
No — Parse APIs are independent, managed REST wrappers over publicly available data. That is the point: where a site has no official API (or only a limited one), Parse gives you a maintained, monitored endpoint for that data and keeps it working as the site changes — so you get a stable contract over a source that never promised one.
Can I fix or extend this API myself if I need a new endpoint or field?+
Yes — and you don't have to wait on us. This API was generated by the Parse agent, which stays attached. Describe the change in plain English ("add an endpoint that returns reviews", "fix the price field") in the revise box on the API page or via the revise_api MCP tool, and the agent rebuilds it against the live site in minutes. Contributing the change back to the public API is free.
What happens if I call an endpoint that has an issue?+
Errors are machine-readable: a bad call returns a clean status with the list of available endpoints and a repair hint, so an agent (or you) can recover or trigger a fix instead of failing silently. Confirmed failures feed the automatic repair queue.
Common use cases
  • Build a cost estimator that calculates monthly LLM spend by multiplying token volumes against chat_api input/output rates per 1M tokens.
  • Display a live xAI model comparison table on a developer portal using context window and token cost fields from chat_api.
  • Determine whether batch processing is cost-effective for a workload by querying batch_api to compare real-time vs. batch feature trade-offs.
  • Estimate image generation budgets by pulling per-resolution costs from imagine_api for specific models.
  • Calculate voice feature costs by separating realtime, TTS, and STT tiers from the voice_api response.
  • Monitor xAI pricing changes over time by polling get_pricing and diffing the tools_pricing and files_and_collections fields against a stored baseline.
  • Scope storage and egress costs for a file-heavy pipeline using the rate arrays inside files_and_collections.
Pricing & limitsSee full pricing →
TierPriceCredits/monthRate limit
Free$0/mo1005 req/min
Hobby$30/mo1,00020 req/min
Developer$100/mo5,000100 req/min

One credit = one API call regardless of which marketplace API you call. Exceeding the rate limit returns a 429 response. Authenticate with the X-API-Key header.

Frequently asked questions
Does xAI have an official developer API?+
Yes. xAI provides an official API documented at https://docs.x.ai. The pricing page this API mirrors is part of that official developer documentation.
What does the `category` parameter in `get_model_pricing` accept, and what does each value return?+
The parameter accepts: chat (returns chat_api), imagine (returns imagine_api), voice (returns voice_api), tools (returns tools_pricing), batch (returns batch_api), storage (returns files_and_collections), and all (returns all six fields). Omitting the parameter behaves the same as passing all.
Does the API expose historical pricing data or changelogs?+
No. Both endpoints return the current published rate card only — there are no date-range parameters, versioning fields, or historical snapshots in the response. The API covers the live pricing surface across all six categories. You can fork it on Parse and revise it to add an endpoint that stores and diffs pricing snapshots over time.
Are individual model capability details — like benchmark scores or parameter counts — included in the response?+
Not currently. The API covers pricing fields such as token costs, context window size, and generation rates, but does not include model capability metadata like benchmarks, parameter counts, or release dates. You can fork it on Parse and revise it to add an endpoint that pulls that data from xAI's model documentation.
Does `imagine_api` pricing differentiate between image and video generation models?+
Yes. The imagine_api array contains entries for both image and video generation models, each with their own per-resolution output costs, so you can compare rates across both media types in a single response.
Page content last updated . Spec covers 2 endpoints from docs.x.ai.
Related APIs in Developer ToolsSee all →
crt.sh API
Search for SSL/TLS certificates across public transparency logs by domain, fingerprint, serial number, or public key, and retrieve detailed certificate information including issuer, validity dates, and certificate chain details. Monitor certificate issuance for domains you care about to track security changes and detect unauthorized certificates.
artificialanalysis.ai API
Compare and rank LLM models and providers across performance benchmarks, then dive into detailed specifications for any model to find the best fit for your needs. Discover performance metrics for specialized AI systems handling speech, images, and video, plus benchmark data for different hardware configurations.
python.org API
Access comprehensive Python release information including downloads, versions, and supported operating systems, plus stay updated with the latest Python news and events. Search across Python.org's resources and browse release files, details, and the FTP index all in one place.
nvidia.com API
nvidia.com API
lucide.dev API
Browse and download thousands of Lucide icons with instant search and category filtering to find exactly what you need. Get SVG files and metadata for each icon to integrate them seamlessly into your projects.
alienvault.com API
Search and analyze global threat intelligence data including indicators of compromise, threat pulses, and adversary profiles from the Open Threat Exchange community. Monitor recent security alerts and access detailed information about threats and adversaries to strengthen your cybersecurity defenses.
ask.brave.com API
Ask Brave's AI-powered answer engine to get intelligent responses on any topic complete with cited sources, or use the suggest endpoint to discover relevant information and follow-up questions. Get AI-generated answers that combine web knowledge with source attribution, helping you research topics efficiently and verify information through direct references.
httpbin.org API
Test HTTP requests and inspect what data your client is sending, including your IP address, headers, user agent, and generated UUIDs. Use it to verify how servers receive and process your requests during development and debugging.