AD SPACE AVAILABLE · BRAND PARTNERS WELCOME

Integrating the Lexica Search API: Programmatic Retrieval of AI Art, Prompts, and Metadata

Mah Han Shih · 365Finds Editorial
Indexed 88,650 Wiki articles

Put 365 Wiki to work with your AI

Copy the prompt below, paste it into the AI you already use, then ask your question.

Download full Skill

Try it with the prompt first. If you use 365 Wiki often, install the full 365Wiki Skill so you do not have to paste it again. No regular AI? Gemini or Microsoft Copilot on the web will work.

365Wiki Skill

Developers building AI prompt assistants, moodboarding tools, or visual search engines often face a frustrating bottleneck: compiling massive datasets of high-quality AI imagery alongside authentic generation parameters without fragile web scrapers. Lexica solves this with a lightweight, public REST API endpoint that allows direct programmatic querying of its vast repository of indexed Stable Diffusion and Aperture generations.

The Lexica Search API requires no API key, supports both natural language keyword search and reverse image similarity retrieval, and returns rich generation metadata—including prompts, seeds, guidance scales, and CDN URLs. However, productionizing this endpoint demands careful engineering around pagination limits, rate thresholds, and strict commercial licensing compliance.

At 365Finds, our evaluation indicates that the Lexica Search API is the fastest, lowest-friction resource for bootstrapping prompt discovery and visual exploration features. Yet, because it lacks an enterprise SLA and explicit pagination, teams must deploy it behind a caching proxy rather than relying on it as a primary persistent datastore.


1. Core API Architecture and Search Modalities

Lexica exposes a single public GET endpoint that powers its web exploration interface:

GET https://lexica.art/api/v1/search?q={query}

The endpoint accepts a single query parameter, q, which determines the search behavior based on whether the input is text or a publicly accessible image URL.

Search Modalities

ModalityParameter StructureDescriptionTypical Use Case
Text Keyword Search?q=cyberpunk+cityscapeSemantic and keyword matching across indexed prompt textsPrompt inspiration, autocomplete plugins, keyword moodboards
Reverse Image Search?q=https://example.com/art.jpgVisual feature embedding search matching visual structure and styleVisual similarity engines, style transfer references, image clustering

The URL query parameter must be standard URL-encoded (RFC 3986). A request with an empty query returns an empty result set or HTTP 400 Bad Request.


2. Response Data Contract and JSON Schema

A successful request returns an application/json payload containing an images array with up to 50 matching records.

Complete Response Payload Structure

{
  "images": [
    {
      "id": "0482ee68-0368-4eca-8846-5930db866b33",
      "gallery": "https://lexica.art?q=0482ee68-0368-4eca-8846-5930db866b33",
      "src": "https://image.lexica.art/md/0482ee68-0368-4eca-8846-5930db866b33",
      "srcSmall": "https://image.lexica.art/sm/0482ee68-0368-4eca-8846-5930db866b33",
      "prompt": "cute chubby blue fruits icons for mobile game ui, isometric vector, unreal engine 5 render, 8k",
      "width": 512,
      "height": 512,
      "seed": "1413536227",
      "grid": false,
      "model": "stable-diffusion",
      "guidance": 7,
      "promptid": "d9868972-dad8-477d-8e5a-4a0ae1e9b72b",
      "nsfw": false
    }
  ]
}

Field Definitions and Downstream Pipeline Application

[!NOTE] Schema Reality Check: Negative Prompts: While Lexica's internal generation tool allows users to specify negative prompts, the public /api/v1/search endpoint exposes only the positive prompt field in its returned schema. Developers attempting to extract negative prompts from the public search payload will find that this metadata is omitted or merged into legacy generation strings.


3. End-to-End Code Integration

TypeScript / Node.js Implementation

This production-grade TypeScript client includes URL encoding, strict type definitions, timeout handling, and automatic NSFW filtering:

interface LexicaImage {
  id: string;
  gallery: string;
  src: string;
  srcSmall: string;
  prompt: string;
  width: number;
  height: number;
  seed: string;
  grid: boolean;
  model: string;
  guidance: number;
  promptid: string;
  nsfw: boolean;
}

interface LexicaSearchResponse {
  images: LexicaImage[];
}

export async function searchLexicaArt(
  query: string,
  options: { filterNsfw?: boolean; timeoutMs?: number } = {}
): Promise<LexicaImage[]> {
  const { filterNsfw = true, timeoutMs = 8000 } = options;
  const controller = new AbortController();
  const timer = setTimeout(() => controller.abort(), timeoutMs);

  const endpoint = `https://lexica.art/api/v1/search?q=${encodeURIComponent(query)}`;

  try {
    const response = await fetch(endpoint, {
      method: "GET",
      headers: {
        "Accept": "application/json",
        "User-Agent": "CreativeToolIntegration/1.0"
      },
      signal: controller.signal
    });

    if (!response.ok) {
      throw new Error(`Lexica API returned HTTP ${response.status}: ${response.statusText}`);
    }

    const data: LexicaSearchResponse = await response.json();
    const images = data.images || [];

    if (filterNsfw) {
      return images.filter(img => !img.nsfw);
    }

    return images;
  } finally {
    clearTimeout(timer);
  }
}

Python / HTTPX Implementation

For Python backends powering prompt recommendation workers, httpx provides synchronous and asynchronous support:

import httpx
from typing import List, Dict, Any, Optional

class LexicaClient:
    BASE_URL = "https://lexica.art/api/v1/search"

    def __init__(self, timeout: float = 10.0):
        self.client = httpx.Client(
            timeout=timeout,
            headers={"User-Agent": "PromptRecommenderEngine/1.0"}
        )

    def search(self, query: str, filter_nsfw: bool = True) -> List[Dict[str, Any]]:
        params = {"q": query}
        response = self.client.get(self.BASE_URL, params=params)
        
        if response.status_code == 429:
            raise RuntimeError("Lexica API rate limit encountered. Implement backoff.")
        response.raise_for_status()

        data = response.json()
        results = data.get("images", [])

        if filter_nsfw:
            return [img for img in results if not img.get("nsfw", False)]
        return results

    def visual_search(self, image_url: str) -> List[Dict[str, Any]]:
        """Executes reverse visual similarity search using a public image URL."""
        return self.search(query=image_url)

    def close(self):
        self.client.close()

4. Production Engineering: Bottlenecks and Workarounds

Because Lexica does not maintain an enterprise developer portal for this search endpoint, integrating it into scalable SaaS tools requires mitigating several architectural constraints:

A. The 50-Item Pagination Ceiling

The /api/v1/search endpoint does not support pagination parameters (page, offset, or limit). Each call returns a maximum of 50 images matching the relevance ranking.

B. Rate Limits and Cloudflare Defenses

Lexica does not publish formal Transactions Per Second (TPS) limits. However, unthrottled concurrent requests from a single IP will quickly trigger HTTP 429 (Too Many Requests) or Cloudflare verification challenges.

C. CDN Asset Caching

Directly embedding src URLs in client-facing web applications subjects your users to Lexica's CDN availability and bandwidth throttling. For mission-critical design applications, download and mirror selected images to your own AWS S3 or Cloudflare R2 bucket.


5. Commercial Licensing, Terms, and Attribution

Integrating Lexica assets into commercial software requires strict legal diligence. Lexica's Terms of Service establish clear boundaries between non-monetized hobbyist use and commercial products:

+-----------------------------------------------------------------------------------+
|                           LEXICA LICENSING FRAMEWORK                              |
+-----------------------------------------------------------------------------------+
|  Tier               | Scope                  | Rights & Constraints               |
+---------------------+------------------------+------------------------------------+
|  Free / Anonymous   | Personal Use Only      | Creative Commons CC BY-NC 4.0      |
|                     | Non-monetized          | Commercial use strictly prohibited |
+---------------------+------------------------+------------------------------------+
|  Starter Plan       | Solo Creators /        | Full commercial usage rights       |
|  (Paid)             | Freelancers            | Across personal & community art    |
+---------------------+------------------------+------------------------------------+
|  Pro Plan           | Teams (2-5 users)      | Full commercial usage rights       |
|  (Paid)             | Commercial SaaS        | Across personal & community art    |
+---------------------+------------------------+------------------------------------+
|  Max Plan           | Teams (5+ users) /     | Full commercial rights +           |
|  (Paid)             | Enterprise             | Private generation capabilities    |
+---------------------+------------------------+------------------------------------+

Essential Compliance Rules

  1. Commercial SaaS Requires a Paid Account: If your software charges users, displays advertising, or is integrated into an enterprise workflow, you cannot rely on free CC BY-NC 4.0 terms. Your organization must maintain an active Lexica team subscription (Starter, Pro, or Max depending on company size).
  2. Community Art Commercial Rights: Under an active paid subscription, commercial rights apply to community images discovered via the search API, not just images generated by your own account.
  3. No Direct Stock Asset Reselling: You cannot scrape Lexica imagery to create a competing raw stock photo library, digital wallpaper marketplace, or NFT collection. Assets must be incorporated into original creative compositions or utilized within interactive tooling.
  4. Mandatory Attribution: When surfacing artwork in prompt visualizers or moodboard tools, include the gallery link or a clear reference acknowledging the image source.

6. 365Finds Research Verdict and Recommendation

At 365Finds, our research leads to a clear recommendation:

References