# Search API

Search for businesses using the AIDP REST API with AI-powered natural language queries.

## Base URL

```
https://api.aidp.dev/v1
```

## Authentication

All API requests require authentication via API key:

```http
Authorization: Bearer YOUR_API_KEY
```

Get your API key from the [Developer Dashboard](https://platform.aidp.dev/developers).

***

## Endpoints

### AI-Powered Consumer Search

Search for businesses using natural language queries with AI-generated responses and personalization.

```http
POST /api/v1/consumer/search
```

**Request Body**:

```json
{
  "query": "coffee shop with outdoor seating",
  "category": "restaurants",
  "location": {
    "lat": 45.5231,
    "lon": -122.6765,
    "distance": "5km"
  },
  "limit": 10,
  "offset": 0
}
```

**Request Headers**:

```http
Authorization: Bearer YOUR_API_KEY
Content-Type: application/json
X-Session-ID: session-abc123 (optional, for personalization)
```

**Parameters**:

| Field               | Type   | Required | Description                                         |
| ------------------- | ------ | -------- | --------------------------------------------------- |
| `query`             | string | Yes      | Natural language search query (1-500 chars)         |
| `category`          | string | No       | Business category filter                            |
| `location`          | object | No       | Search location                                     |
| `location.lat`      | number | Yes\*    | Latitude (\*if location provided)                   |
| `location.lon`      | number | Yes\*    | Longitude (\*if location provided)                  |
| `location.distance` | string | No       | Search radius (e.g., "5km", "10mi") Default: "50km" |
| `limit`             | number | No       | Results per page (1-50, default: 10)                |
| `offset`            | number | No       | Pagination offset (default: 0)                      |

**Response**:

```json
{
  "success": true,
  "data": {
    "query": "coffee shop with outdoor seating",
    "response": "I found several great coffee shops with outdoor seating in Portland. Artisan Coffee Roasters is highly rated with a beautiful patio, and they specialize in single-origin beans...",
    "businesses": [
      {
        "id": "biz_abc123",
        "name": "Artisan Coffee Roasters",
        "category": "restaurants",
        "description": "Family-owned coffee roastery specializing in single-origin beans",
        "tagline": "Locally roasted, globally inspired",
        "address": {
          "street": "123 Main St",
          "city": "Portland",
          "state": "OR",
          "postalCode": "97201",
          "country": "USA"
        },
        "coordinates": {
          "lat": 45.5231,
          "lon": -122.6765
        },
        "phone": "+1-503-555-0123",
        "website": "https://artisancoffee.com",
        "verified": true,
        "averageRating": 4.8,
        "reviewCount": 247,
        "distance": 1200,
        "personalizationScore": 0.92
      }
    ],
    "total": 42,
    "sessionId": "session-abc123",
    "pagination": {
      "offset": 0,
      "limit": 10,
      "hasMore": true
    }
  }
}
```

**Key Features**:

* **AI-Generated Response**: Natural language summary of results
* **Personalization**: Session-based recommendations (use `X-Session-ID` header)
* **Relevance Scoring**: Results ranked by relevance + personalization
* **Distance Calculation**: Automatic distance from search location

***

### Business Directory Search

Browse the business directory with filtering and sorting options.

```http
GET /api/v1/directory
```

**Query Parameters**:

| Parameter           | Type   | Required | Description                                                          |
| ------------------- | ------ | -------- | -------------------------------------------------------------------- |
| `query`             | string | No       | Search query                                                         |
| `category`          | string | No       | Business category                                                    |
| `city`              | string | No       | City filter                                                          |
| `state`             | string | No       | State/province filter                                                |
| `country`           | string | No       | Country filter                                                       |
| `verificationLevel` | string | No       | `basic`, `verified`, `premium`                                       |
| `sortBy`            | string | No       | `aiVisibilityScore`, `rating`, `name` (default: `aiVisibilityScore`) |
| `sortOrder`         | string | No       | `asc` or `desc` (default: `desc`)                                    |
| `limit`             | number | No       | Results per page (1-100, default: 20)                                |
| `offset`            | number | No       | Pagination offset (default: 0)                                       |

**Example**:

```http
GET /api/v1/directory?category=restaurants&city=Portland&state=OR&verificationLevel=verified&limit=20
```

**Response**:

```json
{
  "success": true,
  "data": {
    "businesses": [...],
    "pagination": {
      "total": 156,
      "limit": 20,
      "offset": 0,
      "hasMore": true
    }
  }
}
```

***

### Partner API Search

For verified partners with API access (requires partnership agreement).

```http
GET /api/v1/partners/search
```

**Query Parameters**:

| Parameter  | Type   | Required | Description                           |
| ---------- | ------ | -------- | ------------------------------------- |
| `q`        | string | No\*     | Search query                          |
| `category` | string | No\*     | Business category                     |
| `location` | string | No\*     | Location string                       |
| `limit`    | number | No       | Results per page (1-100, default: 20) |
| `offset`   | number | No       | Pagination offset (default: 0)        |

\*At least one of `q`, `category`, or `location` is required.

**Example**:

```http
GET /api/v1/partners/search?q=coffee&category=restaurants&location=Portland&limit=10
```

**Response**:

```json
{
  "success": true,
  "data": {
    "businesses": [...],
    "pagination": {
      "limit": 10,
      "offset": 0,
      "total": 42,
      "hasMore": true
    }
  }
}
```

***

## Response Codes

| Code  | Description                      |
| ----- | -------------------------------- |
| `200` | Success                          |
| `400` | Bad Request - Invalid parameters |
| `401` | Unauthorized - Invalid API key   |
| `404` | Not Found                        |
| `429` | Rate Limit Exceeded              |
| `500` | Internal Server Error            |

***

## Rate Limiting

* **Free Tier**: 1,000 requests/day
* **Pro Tier**: 10,000 requests/day
* **Enterprise**: Custom limits

Rate limit headers:

```http
X-RateLimit-Limit: 1000
X-RateLimit-Remaining: 847
X-RateLimit-Reset: 1640995200
```

***

## Examples

### Node.js (Consumer Search)

```javascript
const axios = require('axios');

const searchBusinesses = async (query, location) => {
  const response = await axios.post(
    'https://api.aidp.dev/v1/api/v1/consumer/search',
    {
      query,
      location: {
        lat: location.lat,
        lon: location.lon,
        distance: '5km',
      },
      limit: 10,
    },
    {
      headers: {
        Authorization: `Bearer ${process.env.AIDP_API_KEY}`,
        'Content-Type': 'application/json',
        'X-Session-ID': 'session-' + Date.now(), // For personalization
      },
    }
  );

  console.log('AI Response:', response.data.data.response);
  return response.data.data.businesses;
};

// Usage
searchBusinesses('coffee shop with outdoor seating', {
  lat: 45.5231,
  lon: -122.6765,
});
```

### Python (Consumer Search)

```python
import requests
import os

def search_businesses(query, lat, lon):
    response = requests.post(
        'https://api.aidp.dev/v1/api/v1/consumer/search',
        json={
            'query': query,
            'location': {
                'lat': lat,
                'lon': lon,
                'distance': '5km'
            },
            'limit': 10
        },
        headers={
            'Authorization': f'Bearer {os.environ["AIDP_API_KEY"]}',
            'Content-Type': 'application/json',
            'X-Session-ID': f'session-{int(time.time())}'
        }
    )

    data = response.json()['data']
    print(f"AI Response: {data['response']}")
    return data['businesses']

# Usage
businesses = search_businesses('coffee shop with outdoor seating', 45.5231, -122.6765)
```

### cURL (Consumer Search)

```bash
curl -X POST https://api.aidp.dev/v1/api/v1/consumer/search \
  -H "Authorization: Bearer YOUR_API_KEY" \
  -H "Content-Type: application/json" \
  -H "X-Session-ID: session-123" \
  -d '{
    "query": "coffee shop with outdoor seating",
    "location": {
      "lat": 45.5231,
      "lon": -122.6765,
      "distance": "5km"
    },
    "limit": 10
  }'
```

### Directory Search Example

```bash
curl -X GET "https://api.aidp.dev/v1/api/v1/directory?category=restaurants&city=Portland&state=OR&limit=20" \
  -H "Authorization: Bearer YOUR_API_KEY"
```

***

## See Also

* [Business API](https://amistan.gitbook.io/aidp-docs/for-developers/api-reference/business) - Manage business profiles
* [Analytics API](https://amistan.gitbook.io/aidp-docs/for-developers/api-reference/analytics) - Track performance
* [Authentication](https://amistan.gitbook.io/aidp-docs/for-developers/authentication) - API key management
* [Rate Limiting](https://amistan.gitbook.io/aidp-docs/for-developers/rate-limiting) - Usage limits

***

**API Version**: v1\
**Last Updated**: December 2025
