Skip to main content
GET
/
find-specs
Find Specs (Search)
curl --request GET \
  --url https://api.pre.dev/find-specs \
  --header 'Authorization: Bearer <token>'
{
"specs": [
{
"_id": "507f1f77bcf86cd799439011",
"created": "2024-01-15T14:30:00.000Z",
"endpoint": "fast_spec",
"input": "Build a payment processing system with Stripe integration",
"status": "completed",
"success": true,
"outputFormat": "url",
"outputFileUrl": "https://api.pre.dev/s/a6hFJRV6"
}
],
"total": 8,
"hasMore": false
}

GET /find-specs

Search for specifications using powerful regex patterns with optional status and endpoint filtering.

Overview

  • Cost: Free (no credits required)
  • Use Cases: Keyword search, pattern matching, finding related specs
  • Response Time: Instant
  • Search: Case-insensitive regex matching against spec input text
  • Returns: Paginated array of matching specs

Endpoint

GET https://api.pre.dev/find-specs

Headers

Authorization: Bearer YOUR_API_KEY

Query Parameters

ParameterTypeRequiredDefaultDescription
querystring-REQUIRED - Regex pattern to search (case-insensitive)
limitinteger20Results per page (1-100)
skipinteger0Number of records to skip for pagination
endpointstring-Filter by endpoint: fast_spec or deep_spec
statusstring-Filter by status: pending, processing, completed, or failed

Parameter Details

query (REQUIRED)
  • Regex pattern matched against spec input field
  • Case-insensitive by default
  • Supports full regex syntax
  • Must be URL-encoded in request
limit
  • Minimum: 1
  • Maximum: 100
  • Default: 20
skip
  • Minimum: 0
  • Used for pagination
endpoint
  • fast_spec - Only search Fast Spec generations
  • deep_spec - Only search Deep Spec generations
status
  • pending - Only queued specs
  • processing - Only specs currently generating
  • completed - Only successfully finished specs
  • failed - Only failed generations

Regex Pattern Examples

PatternWhat It MatchesExample Use Case
paymentContains “payment” (any case)Find all payment-related specs
^BuildStarts with “Build”Find all “Build X” specs
platform$Ends with “platform”Find platform projects
(API|REST)Contains “API” OR “REST”Find API-related specs
auth.*system”auth” followed by “system”Find authentication systems
\d{3,}Contains 3+ consecutive digitsFind specs with quantities/budgets
saas|sassContains “saas” OR “sass”Catch common misspellings
e-?commerce”ecommerce” or “e-commerce”Match hyphen variations
task.*management”task” then “management”Find task/project mgmt tools
real.?time”realtime” or “real time”Match spacing variations

Response

Success Response

Same structure as /list-specs:
{
  "specs": [
    {
      "_id": "507f1f77bcf86cd799439011",
      "created": "2024-01-15T14:30:00.000Z",
      "endpoint": "fast_spec",
      "input": "Build a payment processing system with Stripe integration",
      "status": "completed",
      "success": true,
      "outputFormat": "url",
      "outputFileUrl": "https://api.pre.dev/s/a6hFJRV6",
      "executionTime": 38500
    }
  ],
  "total": 8,
  "hasMore": false
}

Response Fields

Identical to the list-specs endpoint. See that documentation for complete field descriptions.

Code Examples

cURL Examples

Simple keyword search:
curl -H "Authorization: Bearer YOUR_API_KEY" \
  "https://api.pre.dev/find-specs?query=payment"
Search with URL encoding:
# Search for specs starting with "Build"
curl -H "Authorization: Bearer YOUR_API_KEY" \
  "https://api.pre.dev/find-specs?query=%5EBuild"
Search completed specs only:
curl -H "Authorization: Bearer YOUR_API_KEY" \
  "https://api.pre.dev/find-specs?query=dashboard&status=completed"
Search with OR condition:
# Find specs containing "API" OR "REST"
curl -H "Authorization: Bearer YOUR_API_KEY" \
  "https://api.pre.dev/find-specs?query=(API%7CREST)"
Complex pattern with pagination:
# Find e-commerce specs (handles hyphen variations)
curl -H "Authorization: Bearer YOUR_API_KEY" \
  "https://api.pre.dev/find-specs?query=e-?commerce&limit=50&skip=0"

JavaScript/Node.js

async function findSpecs(query, options = {}) {
  const {
    limit = 20,
    skip = 0,
    endpoint = null,
    status = null
  } = options;

  const params = new URLSearchParams({
    query,
    limit: limit.toString(),
    skip: skip.toString()
  });

  if (endpoint) params.append('endpoint', endpoint);
  if (status) params.append('status', status);

  const response = await fetch(
    `https://api.pre.dev/find-specs?${params}`,
    {
      headers: { 'Authorization': 'Bearer YOUR_API_KEY' }
    }
  );

  if (!response.ok) {
    throw new Error(`API error: ${response.status}`);
  }

  return response.json();
}

// Usage examples

// Simple keyword search
const paymentSpecs = await findSpecs('payment');
console.log(`Found ${paymentSpecs.total} payment specs`);

// Search for specs starting with "Build"
const buildSpecs = await findSpecs('^Build');

// Search with filters
const dashboards = await findSpecs('dashboard', {
  status: 'completed',
  limit: 50
});

// Complex regex: find API or REST specs
const apiSpecs = await findSpecs('(API|REST)');

// Search with pagination
async function searchAllMatches(query) {
  let allMatches = [];
  let skip = 0;
  const limit = 50;

  while (true) {
    const response = await findSpecs(query, { skip, limit });
    allMatches.push(...response.specs);
    
    if (!response.hasMore) break;
    skip += limit;
  }

  return allMatches;
}

// Search for e-commerce (with hyphen variation)
const ecommerce = await findSpecs('e-?commerce');

// Find authentication systems
const authSystems = await findSpecs('auth.*system');

TypeScript

interface FindSpecsOptions {
  limit?: number;
  skip?: number;
  endpoint?: 'fast_spec' | 'deep_spec';
  status?: 'pending' | 'processing' | 'completed' | 'failed';
}

interface SearchResult {
  specs: SpecObject[];
  total: number;
  hasMore: boolean;
  query: string;
}

class SpecSearchClient {
  constructor(private apiKey: string) {}

  async findSpecs(
    query: string,
    options: FindSpecsOptions = {}
  ): Promise<SearchResult> {
    const {
      limit = 20,
      skip = 0,
      endpoint,
      status
    } = options;

    const params = new URLSearchParams({
      query,
      limit: limit.toString(),
      skip: skip.toString()
    });

    if (endpoint) params.append('endpoint', endpoint);
    if (status) params.append('status', status);

    const response = await fetch(
      `https://api.pre.dev/find-specs?${params}`,
      {
        headers: { 'Authorization': `Bearer ${this.apiKey}` }
      }
    );

    if (!response.ok) {
      throw new Error(`API error: ${response.status}`);
    }

    const data = await response.json();
    return { ...data, query };
  }

  async *searchPaginated(
    query: string,
    options: FindSpecsOptions = {}
  ): AsyncGenerator<SpecObject[], void, unknown> {
    let skip = 0;
    const limit = options.limit || 50;

    while (true) {
      const response = await this.findSpecs(query, { ...options, skip, limit });
      
      if (response.specs.length === 0) break;
      
      yield response.specs;
      
      if (!response.hasMore) break;
      skip += limit;
    }
  }

  async searchWithHighlight(
    query: string,
    options: FindSpecsOptions = {}
  ): Promise<Array<SpecObject & { highlight: string }>> {
    const result = await this.findSpecs(query, options);
    
    // Add highlighting to matched text
    const regex = new RegExp(`(${query})`, 'gi');
    
    return result.specs.map(spec => ({
      ...spec,
      highlight: spec.input.replace(regex, '<mark>$1</mark>')
    }));
  }
}

// Usage
const searchClient = new SpecSearchClient('YOUR_API_KEY');

// Simple search
const results = await searchClient.findSpecs('payment', { 
  status: 'completed' 
});
console.log(`Found ${results.total} completed payment specs`);

// Paginated search
for await (const batch of searchClient.searchPaginated('dashboard')) {
  console.log(`Processing ${batch.length} dashboard specs...`);
  batch.forEach(spec => console.log(`  - ${spec.input}`));
}

// Search with highlighting
const highlighted = await searchClient.searchWithHighlight('payment');
highlighted.forEach(spec => {
  console.log(spec.highlight); // HTML with <mark> tags
});

// Complex searches
const apiOrRest = await searchClient.findSpecs('(API|REST)');
const startsWithBuild = await searchClient.findSpecs('^Build');
const hasRealtime = await searchClient.findSpecs('real.?time');

Python

import requests
from typing import Optional, List, Dict, Any, Generator
import urllib.parse

class SpecSearchClient:
    def __init__(self, api_key: str):
        self.api_key = api_key
        self.base_url = 'https://api.pre.dev'
    
    def find_specs(
        self,
        query: str,
        limit: int = 20,
        skip: int = 0,
        endpoint: Optional[str] = None,
        status: Optional[str] = None
    ) -> Dict[str, Any]:
        """
        Search specs using regex pattern.
        
        Args:
            query: Regex pattern to search (case-insensitive)
            limit: Number of results per page (1-100)
            skip: Number of records to skip
            endpoint: Filter by 'fast_spec' or 'deep_spec'
            status: Filter by 'pending', 'processing', 'completed', or 'failed'
        
        Returns:
            Dictionary with 'specs' array, 'total' count, and 'hasMore' flag
        """
        params = {
            'query': query,
            'limit': limit,
            'skip': skip
        }
        
        if endpoint:
            params['endpoint'] = endpoint
        if status:
            params['status'] = status
        
        response = requests.get(
            f'{self.base_url}/find-specs',
            params=params,
            headers={'Authorization': f'Bearer {self.api_key}'}
        )
        response.raise_for_status()
        return response.json()
    
    def search_all(
        self,
        query: str,
        endpoint: Optional[str] = None,
        status: Optional[str] = None,
        batch_size: int = 50
    ) -> List[Dict[str, Any]]:
        """Fetch all specs matching the search query."""
        all_results = []
        skip = 0
        
        while True:
            response = self.find_specs(
                query=query,
                limit=batch_size,
                skip=skip,
                endpoint=endpoint,
                status=status
            )
            all_results.extend(response['specs'])
            
            if not response['hasMore']:
                break
            
            skip += batch_size
        
        return all_results
    
    def search_paginated(
        self,
        query: str,
        endpoint: Optional[str] = None,
        status: Optional[str] = None,
        batch_size: int = 50
    ) -> Generator[List[Dict[str, Any]], None, None]:
        """Generator that yields batches of search results."""
        skip = 0
        
        while True:
            response = self.find_specs(
                query=query,
                limit=batch_size,
                skip=skip,
                endpoint=endpoint,
                status=status
            )
            
            if not response['specs']:
                break
            
            yield response['specs']
            
            if not response['hasMore']:
                break
            
            skip += batch_size

# Usage examples
client = SpecSearchClient('YOUR_API_KEY')

# Simple keyword search
payment_specs = client.find_specs('payment')
print(f"Found {payment_specs['total']} payment specs")

# Search with filters
dashboards = client.find_specs(
    'dashboard',
    status='completed',
    limit=50
)

# Complex regex patterns
api_specs = client.find_specs('(API|REST)')  # OR condition
build_specs = client.find_specs('^Build')    # Starts with
auth_systems = client.find_specs('auth.*system')  # Pattern with wildcard

# Search for e-commerce (handles hyphen variations)
ecommerce = client.find_specs('e-?commerce')

# Get all matches
all_payment_specs = client.search_all('payment', status='completed')
print(f"Total payment specs: {len(all_payment_specs)}")

# Process in batches
for batch in client.search_paginated('dashboard', batch_size=25):
    print(f"Processing {len(batch)} dashboard specs")
    for spec in batch:
        print(f"  - {spec['input'][:60]}...")

# Common search patterns
def search_patterns():
    """Examples of useful search patterns."""
    
    # Find all SaaS projects
    saas_specs = client.find_specs('saas', status='completed')
    
    # Find real-time features (handles spacing)
    realtime = client.find_specs('real.?time')
    
    # Find specs with numbers (budgets, quantities)
    with_numbers = client.find_specs(r'\d{3,}')
    
    # Find authentication/authorization
    auth = client.find_specs('auth(entication|orization)?')
    
    # Find e-commerce variations
    ecommerce = client.find_specs('e-?commerce')
    
    return {
        'saas': saas_specs['total'],
        'realtime': realtime['total'],
        'with_numbers': with_numbers['total'],
        'auth': auth['total'],
        'ecommerce': ecommerce['total']
    }

Common Use Cases

1. Search Bar Implementation

async function handleSearch(searchTerm, filters = {}) {
  try {
    // Escape special regex characters for literal search
    const escapedTerm = searchTerm.replace(/[.*+?^${}()|[\]\\]/g, '\\$&');
    
    const results = await findSpecs(escapedTerm, {
      status: filters.status,
      endpoint: filters.endpoint,
      limit: 20
    });
    
    return {
      results: results.specs,
      total: results.total,
      hasMore: results.hasMore
    };
  } catch (error) {
    console.error('Search failed:', error);
    return { results: [], total: 0, hasMore: false };
  }
}
def find_related_specs(base_spec_input: str, client: SpecSearchClient):
    """Find specs related to a given spec."""
    # Extract key terms (simplified example)
    keywords = base_spec_input.lower().split()[:3]
    pattern = '|'.join(keywords)
    
    related = client.find_specs(pattern, limit=10)
    return related['specs']
const CATEGORY_PATTERNS: Record<string, string> = {
  ecommerce: 'e-?commerce|shop|store|cart',
  authentication: 'auth(entication|orization)?|login|signup',
  realtime: 'real.?time|websocket|live|streaming',
  payment: 'payment|billing|stripe|checkout',
  dashboard: 'dashboard|analytics|metrics|reporting',
  api: '(API|REST|GraphQL)',
  social: 'social|chat|messaging|comment',
  ai: '(AI|ML|machine.?learning|artificial.?intelligence)'
};

async function searchByCategory(category: string) {
  const pattern = CATEGORY_PATTERNS[category];
  if (!pattern) {
    throw new Error(`Unknown category: ${category}`);
  }
  
  return await searchClient.findSpecs(pattern, {
    status: 'completed',
    limit: 50
  });
}

4. Advanced Search with Multiple Criteria

async function advancedSearch({
  mustInclude = [],      // All of these terms
  shouldInclude = [],    // Any of these terms
  mustExclude = [],      // None of these terms
  status = null,
  endpoint = null
}) {
  // Build regex pattern
  let pattern = '';
  
  if (mustInclude.length > 0) {
    // Positive lookahead for each required term
    pattern = mustInclude.map(term => `(?=.*${term})`).join('');
    pattern += '.*';
  }
  
  if (shouldInclude.length > 0) {
    pattern += `(${shouldInclude.join('|')})`;
  }
  
  // Note: mustExclude requires client-side filtering as regex negative lookahead
  // can be complex. Better to filter results after fetching.
  
  const results = await findSpecs(pattern || '.*', { status, endpoint });
  
  // Client-side filtering for exclusions
  if (mustExclude.length > 0) {
    const excludeRegex = new RegExp(mustExclude.join('|'), 'i');
    results.specs = results.specs.filter(
      spec => !excludeRegex.test(spec.input)
    );
    results.total = results.specs.length;
  }
  
  return results;
}

// Usage
const results = await advancedSearch({
  mustInclude: ['task', 'management'],
  shouldInclude: ['team', 'collaboration'],
  mustExclude: ['deprecated'],
  status: 'completed'
});

Regex Tips & Tricks

Common Patterns

// Case variations
'saas|SaaS|SAAS'  // Match any capitalization

// Word boundaries
'\\bapi\\b'       // Match "api" as whole word only

// Optional characters
'e-?commerce'     // Match "ecommerce" or "e-commerce"
'real.?time'      // Match "realtime" or "real time"

// Character classes
'[Pp]ayment'      // Match "Payment" or "payment"
'task[- ]management'  // Match "task management" or "task-management"

// Quantifiers
'\\d{3,}'         // 3 or more digits
'feature.*flag'   // "feature" then "flag" with anything between

// Alternation
'(dashboard|admin|panel)'  // Match any of these

// Start/End anchors
'^Build'          // Must start with "Build"
'platform$'       // Must end with "platform"

URL Encoding

When using cURL or constructing URLs directly, encode special characters:
CharacterEncodedExample PatternEncoded URL
^%5E^Buildquery=%5EBuild
$%24platform$query=platform%24
|%7CAPI|RESTquery=API%7CREST
(%28(API|REST)query=%28API%7CREST%29
)%29(API|REST)query=%28API%7CREST%29
Space%20 or +task managementquery=task+management
Most HTTP clients handle this automatically.

Best Practices

Search Patterns

  • Start with simple keywords, add complexity if needed
  • Use case-insensitive patterns (already default)
  • Handle common variations (hyphens, spaces, plural forms)
  • Test patterns before using in production

Performance

  • Use specific patterns to reduce result sets
  • Combine with status and endpoint filters
  • Implement pagination for large result sets
  • Cache frequent searches

User Experience

  • Show loading states during search
  • Display result counts
  • Highlight matched terms in results
  • Provide search suggestions or examples
  • Handle empty results gracefully

Error Handling

  • Validate regex patterns client-side when possible
  • Catch and display API errors clearly
  • Provide fallback for invalid regex
  • Show helpful messages for no results

Limitations

  • Search only matches against the input field
  • Maximum 100 results per request (use pagination for more)
  • Regex is case-insensitive by default
  • Very complex regex patterns may impact performance

Back: List Specs

List all specs with pagination and filtering.

Authorizations

Authorization
string
header
default:YOUR_API_KEY
required

API key for authentication. Get your API key from https://pre.dev/projects/playground (Solo) or https://pre.dev/enterprise/dashboard?page=api (Enterprise). Use format: Bearer YOUR_API_KEY

Query Parameters

query
string
required

REQUIRED - Regex pattern to search (case-insensitive)

Example:

"payment"

limit
integer
default:20

Number of results per page (1-100)

Required range: 1 <= x <= 100
Example:

20

skip
integer
default:0

Number of records to skip for pagination

Required range: x >= 0
Example:

0

endpoint
enum<string>

Filter by endpoint type

Available options:
fast_spec,
deep_spec
Example:

"fast_spec"

status
enum<string>

Filter by processing status

Available options:
pending,
processing,
completed,
failed
Example:

"completed"

Response

Search results retrieved successfully

specs
object[]
required

Array of spec objects matching the filters

total
integer
required

Total number of specs matching the filters

Example:

42

hasMore
boolean
required

Whether more pages are available

Example:

true

I