Skip to main content

kagi search

Search Kagi and return structured results in JSON or human-readable format. This is the primary command for retrieving search results from your terminal. Search demo

Synopsis

kagi search [OPTIONS] <QUERY>

Description

The kagi search command performs a search query against Kagi’s search index and returns results in a structured format. By default, output is JSON suitable for programmatic processing. With the --pretty flag, results are formatted for human readability. This command has sophisticated authentication behavior: it prefers the API token path when available but can automatically fall back to the session token path if the API path is rejected. This ensures maximum utility regardless of which token type you have configured.

Authentication

Base Search (No Lens)

Preferred: KAGI_API_TOKEN Fallback: KAGI_SESSION_TOKEN (if API path is rejected) The base search command is unique in that it attempts both authentication paths:
  1. First attempt: Uses KAGI_API_TOKEN if available, querying the Search API
  2. On API rejection: Falls back to KAGI_SESSION_TOKEN, querying via the web product
  3. On success: Returns results from whichever path succeeded
Why this matters: You can use base search with either token type, and the CLI intelligently selects the best available option.

Lens Search (--lens)

Required: KAGI_SESSION_TOKEN Lens-aware search requires a subscriber session token. This feature is not available via the Search API and requires web-product authentication. What is a lens? Kagi lenses are custom search scopes you create in your Kagi account. They allow you to search within specific domains, topics, or content types you’ve defined.

Options

<QUERY> (Required)

The search query string. Constraints:
  • Minimum length: 1 character
  • Maximum length: 2000 characters
  • Supports all standard search operators
Examples:
kagi search "rust programming language"
kagi search "site:github.com rust cli"
kagi search '"exact phrase match"'

--pretty

Render output in human-readable format instead of JSON. Default: false (JSON output) When to use: Interactive terminal sessions, quick lookups, reading results JSON Output (default):
{
  "data": [
    {
      "t": 0,
      "url": "https://www.rust-lang.org",
      "title": "Rust Programming Language",
      "snippet": "A language empowering everyone to build reliable and efficient software.",
      "rank": 1
    }
  ]
}
Pretty Output (--pretty):
1. Rust Programming Language
   https://www.rust-lang.org

   A language empowering everyone to build reliable and efficient software.

2. The Rust Programming Language - Documentation
   https://doc.rust-lang.org/book/

   The Rust Programming Language book.
Note: --pretty only changes output formatting. It does not affect:
  • Which authentication is used
  • Transport method (API vs web)
  • Command semantics
  • Error behavior

--lens <INDEX>

Search using a specific Kagi lens. Requires: KAGI_SESSION_TOKEN Type: String value representing your numeric lens index Example: --lens 2 Finding your lens index:
  1. Log into Kagi at kagi.com
  2. Navigate to your lenses in settings
  3. The lens index is the number shown for each lens
Example:
# Use lens #2 (your "Developer Documentation" lens)
kagi search --lens 2 "error handling"

# Combine with pretty output
kagi search --lens 2 --pretty "rust async"
Important: Lens indices are user-specific. Your lens #2 is different from another user’s lens #2.

Output Format

JSON Structure

{
  "data": [
    {
      "t": 0,           // Result type (0 = organic, see types below)
      "rank": 1,        // Position in results
      "title": "...",   // Page title
      "url": "...",     // Full URL
      "snippet": "...", // Description/excerpt
      "published": "..." // Optional: publication date
    }
  ]
}

Result Types

TypeDescription
0Organic search result
1News result
2Image result
3Video result
4Map/local result

Pretty Output Format

Results are numbered and formatted with title, URL, and optional snippet:
{rank}. {title}
   {url}

   {snippet}

Examples

# Simple search with JSON output
kagi search "rust programming language"

# Human-readable output
kagi search --pretty "rust programming language"
# Search within your developer documentation lens (lens #2)
kagi search --lens 2 "error handling patterns"

# Search within your tech news lens (lens #5)
kagi search --lens 5 "artificial intelligence"

Advanced Queries

# Site-specific search
kagi search "site:github.com rust cli"

# Exact phrase
kagi search '"async await rust"'

# Exclude terms
kagi search "rust -game -gaming"

# Date range
kagi search "rust tutorial after:2023-01-01"

Processing Results

# Extract URLs
kagi search "rust" | jq -r '.data[].url'

# Extract titles
kagi search "rust" | jq -r '.data[].title'

# Get first result URL
kagi search "rust" | jq -r '.data[0].url'

# Filter organic results only
kagi search "rust" | jq '.data | map(select(.t == 0))'

# Count results
kagi search "rust" | jq '.data | length'

Combining with Other Tools

# Open first result in browser
kagi search "rust" | jq -r '.data[0].url' | xargs open

# Save results to file
kagi search "rust" > rust-search-results.json

# Create markdown links
kagi search "rust" | jq -r '.data[0:5] | .[] | "- [\(.title)](\(.url))"' > results.md

# Generate CSV
kagi search "rust" | jq -r '.data[] | [.title, .url] | @csv' > results.csv

Exit Codes

CodeMeaning
0Success - search completed, results returned
1Error - see stderr for details
Common errors:
  • Missing credentials
  • Invalid authentication
  • Network failure
  • Rate limiting

Authentication Flow Details

Base Search Flow

Lens Search Flow

Performance Considerations

Response Times

  • Base search: 1-3 seconds typical
  • Lens search: 2-5 seconds typical
  • With fallback: May take 2x time if fallback occurs

Rate Limiting

  • Respect rate limits between requests
  • Add delays when processing multiple queries: sleep 1
  • Consider caching results for repeated queries

Best Practices

  1. Use appropriate token: If you have both, base search uses API first
  2. Pretty for humans: Use --pretty for interactive use
  3. JSON for automation: Default JSON is perfect for piping
  4. Lens for focus: Use lenses to scope searches to relevant domains
  5. Limit results: Use --limit to reduce payload size

Troubleshooting

”No results found”

  • Try a broader query
  • Check your internet connection
  • Verify authentication is working: kagi auth check

”missing credentials”

  • Set your session token: kagi auth set --session-token '...'
  • Or set API token: kagi auth set --api-token '...'
  • Check status: kagi auth status

”auth check failed”

  • Token may be expired - regenerate in Kagi settings
  • Check token hasn’t been revoked
  • Verify subscription/API credit status

Slow responses

  • May be experiencing fallback behavior
  • Check network connectivity
  • Consider rate limiting delays

Comparison with Other Commands

Featurekagi searchkagi newskagi smallweb
AuthenticationOptional (API or Session)NoneNone
OutputJSON or prettyJSONJSON
SourceSearch indexNews feedSmall Web
Requires tokenNo (public)NoNo
  • kagi news - Search news articles specifically
  • kagi enrich web - Web enrichment with different API
  • kagi auth - Manage authentication
  • kagi assistant - AI-powered assistance

See Also