> **For coding agents and LLMs:** This is one page from the Social Fetch docs (markdown export). The sections below mirror the orientation block in [`/llms.txt`](https://www.socialfetch.dev/llms.txt); use [`/llms.json`](https://www.socialfetch.dev/llms.json) when you need a structured operation inventory. The catalog covers documented operations with on-site reference pages.

## This page

- **On-site (HTML):** [https://www.socialfetch.dev/docs/api/v1/facebook/ad-library/ads/search/get](https://www.socialfetch.dev/docs/api/v1/facebook/ad-library/ads/search/get)
- **Markdown (.mdx) URL:** [https://www.socialfetch.dev/docs/api/v1/facebook/ad-library/ads/search/get.mdx](https://www.socialfetch.dev/docs/api/v1/facebook/ad-library/ads/search/get.mdx)

## API base URL and authentication

- **API origin (from OpenAPI `servers`):** `https://api.socialfetch.dev`
- **Authentication:** send `x-api-key: sfk_...` on `/v1/**` routes unless the operation is explicitly anonymous (check OpenAPI `security`, the [API reference hub](https://www.socialfetch.dev/docs/api.mdx), [`/llms.txt`](https://www.socialfetch.dev/llms.txt), or [`/llms.json`](https://www.socialfetch.dev/llms.json) for each route).
- **OpenAPI JSON:** [https://www.socialfetch.dev/openapi.json](https://www.socialfetch.dev/openapi.json)

## Recommended docs entrypoints (this site)

- [Documentation overview](https://www.socialfetch.dev/docs.mdx) — top-level orientation (markdown).
- [Quickstart](https://www.socialfetch.dev/docs/quickstart.mdx) — authenticate with `x-api-key`, validate auth with `whoami`, and understand the JSON envelope.
- [SDK](https://www.socialfetch.dev/docs/sdk.mdx) — official TypeScript SDK guide, including `SocialFetchClient`, `Result`, and `unwrap()`.
- [SDK reference](https://www.socialfetch.dev/docs/sdk-reference.mdx) — exhaustive SDK method inventory and route mapping for agents, tooling, and power users.
- [Choose the right endpoint](https://www.socialfetch.dev/docs/choose-endpoint.mdx) — task-oriented route selection for smoke tests, profiles, list endpoints, and single-item lookups.
- [Capability matrix](https://www.socialfetch.dev/docs/capability-matrix.mdx) — fast comparison of identifiers, pagination, outcomes, media download, and SDK coverage.
- [`/llms.json`](https://www.socialfetch.dev/llms.json) — structured machine-readable operation inventory with parameter names, pagination, outcomes, credits, and SDK mapping.
- [API reference hub](https://www.socialfetch.dev/docs/api.mdx) — human-friendly index of operations with links into generated pages.
- [Errors](https://www.socialfetch.dev/docs/errors.mdx) — shared error envelope and HTTP status guidance.
- [Credits](https://www.socialfetch.dev/docs/credits.mdx) — metering, `402`, and planning batch jobs.
- Outcome semantics such as `found`, `not_found`, and `private` are documented in [Errors](https://www.socialfetch.dev/docs/errors.mdx) and on operation pages when present in the OpenAPI contract.

## Markdown docs convention

- Every docs page has a markdown twin: append **`.mdx`** to the docs pathname (for example `/docs/quickstart` → `/docs/quickstart.mdx`).
- Agents that send `Accept: text/markdown` on `/docs/**` HTML URLs may receive markdown directly (same URL, `Vary: Accept`).

---
# Search Facebook Ad Library ads (https://www.socialfetch.dev/docs/api/v1/facebook/ad-library/ads/search/get)

## Summary

Search Facebook Ad Library ads by keyword.

**Tags:** `Facebook`

## HTTP

- **Method:** GET
- **Path:** `/v1/facebook/ad-library/ads/search`
- **Base URL:** `https://api.socialfetch.dev`

## Capability summary

- **SDK mapping:** `client.facebook.searchAdLibraryAds({ query, sortBy?, searchType?, adType?, country?, status?, mediaType?, startDate?, endDate?, cursor?, trim? })`
- **Pagination:** cursor via `cursor`, next cursor: `data.page.nextCursor`, has more: `data.page.hasMore`
- **Ordering / list behavior:** Supported sort options: impressions, most-recent.
- **Trimmed response mode:** supported via `trim=true`

## Credits

- **Base:** 1 credit per successful lookup.
- **Maximum on success (200):** 1 credit.
- **Normalization failure (502):** 1 credit charged.
- **Authoritative field:** `meta.creditsCharged`.

## Authentication

- **`x-api-key`**: API key (`sfk_...`)

## Parameters

### `query` (query)

- **Required:** yes
- **Constraints:** type `string`; minLength: 1; maxLength: 4096
- **Description:** Search query text for Facebook Ad Library ads.

### `sortBy` (query)

- **Required:** no
- **Constraints:** type `string`; enum: impressions, most-recent
- **Description:** Optional sort order for returned ads.

### `searchType` (query)

- **Required:** no
- **Constraints:** type `string`; enum: keyword-unordered, exact-phrase
- **Description:** Optional keyword matching mode for the search query.

### `adType` (query)

- **Required:** no
- **Constraints:** type `string`; enum: all, political-and-issue
- **Description:** Optional filter for all ads or political and issue ads.

### `country` (query)

- **Required:** no
- **Constraints:** type `string`; minLength: 2; maxLength: 3
- **Description:** Optional country code filter. Use ALL to search all countries.

### `status` (query)

- **Required:** no
- **Constraints:** type `string`; enum: all, active, inactive
- **Description:** Optional ad status filter.

### `mediaType` (query)

- **Required:** no
- **Constraints:** type `string`; enum: all, image, video, meme, image-and-meme, none
- **Description:** Optional creative media filter.

### `startDate` (query)

- **Required:** no
- **Constraints:** type `string`; pattern: `^\d{4}-\d{2}-\d{2}$`
- **Description:** Optional start date filter in YYYY-MM-DD format.

### `endDate` (query)

- **Required:** no
- **Constraints:** type `string`; pattern: `^\d{4}-\d{2}-\d{2}$`
- **Description:** Optional end date filter in YYYY-MM-DD format.

### `cursor` (query)

- **Required:** no
- **Constraints:** type `string`; minLength: 1
- **Description:** Opaque pagination cursor from a previous response.

### `trim` (query)

- **Required:** no
- **Constraints:** type `boolean`
- **Description:** When true, returns a smaller response with fewer fields.

## Behavior notes

- **`sortBy`**: Optional sort order for returned ads.
- **`trim`**: When true, returns a smaller response with fewer fields.

## Pagination

This endpoint uses **cursor-based pagination** via the `cursor` query parameter.

- Read **hasMore** from `data.page.hasMore`.
- When that value is `true`, read **nextCursor** from `data.page.nextCursor` and pass it as the `cursor` query parameter on the **next** request (URL-encode when building a query string).
- Omit `cursor` on the **first** request.
- Stop when **hasMore** is `false` or **nextCursor** is null (end of list).

## Responses (status codes)

- **200**: Facebook Ad Library ads matching the requested search.
- **400**: Invalid search parameters or cursor
- **401**: Missing or invalid API key
- **402**: Insufficient credits
- **500**: Unexpected or billing error
- **502**: Lookup could not be completed from the response (unexpected or invalid data).
- **503**: Service temporarily unavailable; safe to retry with backoff.

## Response body (200)

Facebook Ad Library ads matching the requested search.

### Field outline

- **data** (required) — type `object`. Endpoint-specific response payload.
  - **query** (required) — type `string`. Search query that was evaluated for this response.
  - **ads** (required) — type `array`. Ads returned for the requested search. This array may be empty when no ads match the filters.
    - _items:_
      - **id** (required) — type `string`; minLength: 1. Stable identifier for the ad.
      - **adId** (required) — type `string`; nullable. Platform ad id when available.
      - **url** (required) — type `string`; nullable. Public Facebook Ad Library URL for this ad when available.
      - **page** (required) — type `object`. Advertiser page summary for this ad.
        - **id** (required) — type `string`; nullable. Facebook page id for the advertiser when available.
        - **name** (required) — type `string`; nullable. Display name for the advertiser page when available.
        - **url** (required) — type `string`; nullable. Public Facebook URL for the advertiser page when available.
        - **isDeleted** (required) — type `boolean`; nullable. Whether the advertiser page is marked deleted.
        - **profilePictureUrl** (required) — type `string`; nullable. Profile picture URL for the advertiser page when available.
        - **likeCount** (required) — type `integer`; minimum: 0; nullable. Advertiser page like count when available.
        - **categories** (required) — type `array`. Public categories for the advertiser page when available.
          - _items:_
            - type `string`; minLength: 1
      - **campaign** (required) — type `object`. Campaign collation metadata for this ad.
        - **collationId** (required) — type `string`; nullable. Campaign collation id when available.
        - **collationCount** (required) — type `integer`; minimum: 0; nullable. Number of ads in the campaign collation when available.
      - **isActive** (required) — type `boolean`. Whether the ad is currently active.
      - **publisherPlatforms** (required) — type `array`. Publisher platforms where the ad ran or is running.
        - _items:_
          - type `string`; minLength: 1
      - **startedAt** (required) — type `string`; nullable. ISO-8601 timestamp for when the ad started, when available.
      - **endedAt** (required) — type `string`; nullable. ISO-8601 timestamp for when the ad ended, when available.
      - **categories** (required) — type `array`. Ad categories reported by the platform.
        - _items:_
          - type `string`; minLength: 1
      - **countries** (required) — type `array`. Countries targeted or reached by the ad when available.
        - _items:_
          - type `string`; minLength: 1
      - **impressions** (required) — type `object`; nullable. Impressions metadata when available.
        - **text** (required) — type `string`; nullable. Human-readable impressions label when available.
        - **index** (required) — type `integer`; nullable. Impressions index when available.
      - **spend** (required) — type `object`; nullable. Spend metadata when available.
        - **amount** (required) — type `string`; nullable. Spend amount text when available.
        - **currency** (required) — type `string`; nullable. Currency code for spend when available.
      - **creative** (required) — type `object`. Creative content for this ad.
        - **bodyText** (required) — type `string`; nullable. Primary ad body text when available.
        - **title** (required) — type `string`; nullable. Ad title when available.
        - **caption** (required) — type `string`; nullable. Ad caption when available.
        - **linkUrl** (required) — type `string`; nullable. Primary link URL when available.
        - **linkDescription** (required) — type `string`; nullable. Link description when available.
        - **callToAction** (required) — type `string`; nullable. Call-to-action label when available.
        - **callToActionType** (required) — type `string`; nullable. Call-to-action type when available.
        - **displayFormat** (required) — type `string`; nullable. Display format for the creative when available.
        - **images** (required) — type `array`. Image assets attached to the creative.
          - _items:_
        - **videos** (required) — type `array`. Video assets attached to the creative.
          - _items:_
        - **cards** (required) — type `array`. Carousel cards attached to the creative.
          - _items:_
  - **page** (required) — type `object`. Pagination information for the current response.
    - **nextCursor** (required) — type `string`; nullable. Cursor to pass as `cursor` in the next request when `hasMore` is true; otherwise null.
    - **hasMore** (required) — type `boolean`. Whether another page of ads can be requested.
    - **totalResultsEstimate** (required) — type `integer`; minimum: 0; nullable. Estimated total number of matching ads when available.
- **meta** (required) — type `object`. Metadata describing the request and billing outcome.
  - **requestId** (required) — type `string`; minLength: 1. Unique request identifier for tracing this API call.
  - **creditsCharged** (required) — type `integer`; minimum: 0. Credits charged for this request.
  - **version** (required) — type `string`; enum: v1. Public API version that served the response.

### Example JSON (found)

```json
{
  "data": {
    "query": "running",
    "ads": [
      {
        "id": "615470338018648",
        "adId": null,
        "url": "https://www.facebook.com/ads/library?id=615470338018648",
        "page": {
          "id": "115531458627129",
          "name": "Example Advertiser",
          "url": "https://www.facebook.com/example",
          "isDeleted": false,
          "profilePictureUrl": "https://example.com/page.jpg",
          "likeCount": 3823,
          "categories": [
            "Pet Service"
          ]
        },
        "campaign": {
          "collationId": "888075953335279",
          "collationCount": 1
        },
        "isActive": true,
        "publisherPlatforms": [
          "FACEBOOK",
          "INSTAGRAM"
        ],
        "startedAt": "2025-02-28T00:00:00.000Z",
        "endedAt": "2025-02-28T00:00:00.000Z",
        "categories": [
          "UNKNOWN"
        ],
        "countries": [],
        "impressions": {
          "text": null,
          "index": -1
        },
        "spend": null,
        "creative": {
          "bodyText": "Example ad body text.",
          "title": null,
          "caption": null,
          "linkUrl": "https://example.com/product",
          "linkDescription": null,
          "callToAction": "Learn more",
          "callToActionType": "LEARN_MORE",
          "displayFormat": "IMAGE",
          "images": [
            {
              "url": "https://example.com/image.jpg",
              "resizedUrl": "https://example.com/image-resized.jpg",
              "watermarkedResizedUrl": null
            }
          ],
          "videos": [],
          "cards": []
        }
      }
    ],
    "page": {
      "nextCursor": "eyJjIjoiQVFIX2V4YW1wbGUiLCJmIjp7InF1ZXJ5IjoicnVubmluZyJ9fQ",
      "hasMore": true,
      "totalResultsEstimate": 50001
    }
  },
  "meta": {
    "requestId": "req_01example_found",
    "creditsCharged": 1,
    "version": "v1"
  }
}
```

### Example JSON (paginated)

```json
{
  "data": {
    "query": "running",
    "ads": [
      {
        "id": "615470338018649",
        "adId": null,
        "url": "https://www.facebook.com/ads/library?id=615470338018649",
        "page": {
          "id": "115531458627129",
          "name": "Example Advertiser",
          "url": "https://www.facebook.com/example",
          "isDeleted": false,
          "profilePictureUrl": "https://example.com/page.jpg",
          "likeCount": 3823,
          "categories": [
            "Pet Service"
          ]
        },
        "campaign": {
          "collationId": "888075953335279",
          "collationCount": 1
        },
        "isActive": true,
        "publisherPlatforms": [
          "FACEBOOK",
          "INSTAGRAM"
        ],
        "startedAt": "2025-02-28T00:00:00.000Z",
        "endedAt": "2025-02-28T00:00:00.000Z",
        "categories": [
          "UNKNOWN"
        ],
        "countries": [],
        "impressions": {
          "text": null,
          "index": -1
        },
        "spend": null,
        "creative": {
          "bodyText": "Example ad body text.",
          "title": null,
          "caption": null,
          "linkUrl": "https://example.com/product",
          "linkDescription": null,
          "callToAction": "Learn more",
          "callToActionType": "LEARN_MORE",
          "displayFormat": "IMAGE",
          "images": [
            {
              "url": "https://example.com/image.jpg",
              "resizedUrl": "https://example.com/image-resized.jpg",
              "watermarkedResizedUrl": null
            }
          ],
          "videos": [],
          "cards": []
        }
      }
    ],
    "page": {
      "nextCursor": "eyJjIjoiQVFIX3NlY29uZF9wYWdlIiwiZiI6eyJxdWVyeSI6InJ1bm5pbmcifX0",
      "hasMore": true,
      "totalResultsEstimate": null
    }
  },
  "meta": {
    "requestId": "req_01example_page_2",
    "creditsCharged": 1,
    "version": "v1"
  }
}
```

### Example JSON (empty)

```json
{
  "data": {
    "query": "unlikely search",
    "ads": [],
    "page": {
      "nextCursor": null,
      "hasMore": false,
      "totalResultsEstimate": 0
    }
  },
  "meta": {
    "requestId": "req_01example_empty",
    "creditsCharged": 1,
    "version": "v1"
  }
}
```

### Example JSON (video)

```json
{
  "data": {
    "query": "running",
    "ads": [
      {
        "id": "615470338018650",
        "adId": null,
        "url": "https://www.facebook.com/ads/library?id=615470338018650",
        "page": {
          "id": "115531458627129",
          "name": "Example Advertiser",
          "url": "https://www.facebook.com/example",
          "isDeleted": false,
          "profilePictureUrl": "https://example.com/page.jpg",
          "likeCount": 3823,
          "categories": [
            "Pet Service"
          ]
        },
        "campaign": {
          "collationId": "888075953335279",
          "collationCount": 1
        },
        "isActive": true,
        "publisherPlatforms": [
          "FACEBOOK",
          "INSTAGRAM"
        ],
        "startedAt": "2025-02-28T00:00:00.000Z",
        "endedAt": "2025-02-28T00:00:00.000Z",
        "categories": [
          "UNKNOWN"
        ],
        "countries": [],
        "impressions": {
          "text": null,
          "index": -1
        },
        "spend": null,
        "creative": {
          "bodyText": "Example ad body text.",
          "title": null,
          "caption": null,
          "linkUrl": "https://example.com/product",
          "linkDescription": null,
          "callToAction": "Learn more",
          "callToActionType": "LEARN_MORE",
          "displayFormat": "VIDEO",
          "images": [],
          "videos": [
            {
              "hdUrl": "https://example.com/video-hd.mp4",
              "sdUrl": "https://example.com/video-sd.mp4",
              "previewImageUrl": "https://example.com/video-preview.jpg"
            }
          ],
          "cards": []
        }
      }
    ],
    "page": {
      "nextCursor": null,
      "hasMore": false,
      "totalResultsEstimate": 50001
    }
  },
  "meta": {
    "requestId": "req_01example_video",
    "creditsCharged": 1,
    "version": "v1"
  }
}
```

### Example JSON (inactive)

```json
{
  "data": {
    "query": "running",
    "ads": [
      {
        "id": "615470338018651",
        "adId": null,
        "url": "https://www.facebook.com/ads/library?id=615470338018651",
        "page": {
          "id": "115531458627129",
          "name": "Example Advertiser",
          "url": "https://www.facebook.com/example",
          "isDeleted": false,
          "profilePictureUrl": "https://example.com/page.jpg",
          "likeCount": 3823,
          "categories": [
            "Pet Service"
          ]
        },
        "campaign": {
          "collationId": "888075953335279",
          "collationCount": 1
        },
        "isActive": false,
        "publisherPlatforms": [
          "FACEBOOK",
          "INSTAGRAM"
        ],
        "startedAt": "2025-02-28T00:00:00.000Z",
        "endedAt": "2025-03-01T00:00:00.000Z",
        "categories": [
          "UNKNOWN"
        ],
        "countries": [],
        "impressions": {
          "text": null,
          "index": -1
        },
        "spend": null,
        "creative": {
          "bodyText": "Example ad body text.",
          "title": null,
          "caption": null,
          "linkUrl": "https://example.com/product",
          "linkDescription": null,
          "callToAction": "Learn more",
          "callToActionType": "LEARN_MORE",
          "displayFormat": "IMAGE",
          "images": [
            {
              "url": "https://example.com/image.jpg",
              "resizedUrl": "https://example.com/image-resized.jpg",
              "watermarkedResizedUrl": null
            }
          ],
          "videos": [],
          "cards": []
        }
      }
    ],
    "page": {
      "nextCursor": null,
      "hasMore": false,
      "totalResultsEstimate": 50001
    }
  },
  "meta": {
    "requestId": "req_01example_inactive",
    "creditsCharged": 1,
    "version": "v1"
  }
}
```

### Machine-readable error codes

When an error JSON body is returned, it may include one of these `error.code` values (derived from the OpenAPI schemas for this operation; additional codes may exist at runtime):

- `bad_request`

## Error handling & retries

Interpret HTTP status codes using the descriptions below. Do not assume a JSON body unless the OpenAPI schema defines one for that status.

- **400**: Invalid search parameters or cursor **Retry:** Fix the request; retrying the same invalid payload will not help.
- **401**: Missing or invalid API key **Retry:** Fix the API key first; retrying without changes will not help.
- **402**: Insufficient credits **Retry:** Do not retry without resolving billing/credits (retrying the same request will not help).
- **500**: Unexpected or billing error
- **502**: Lookup could not be completed from the response (unexpected or invalid data). **Retry:** May be transient; a few retries with backoff are reasonable.
- **503**: Service temporarily unavailable; safe to retry with backoff. **Retry:** Usually safe to retry with exponential backoff and jitter.

### Suggested client defaults

- Send the API key using the `x-api-key` header on every request.
- On `503` (and sometimes `502`), retry with backoff; cap retries and surface a clear error to the user.
- On `402`, surface an actionable billing message rather than blind retries.

## Examples

### TypeScript SDK

```typescript
import { SocialFetchClient } from "@socialfetch/sdk";

const client = new SocialFetchClient({
  apiKey: process.env.SOCIALFETCH_API_KEY!,
});

const result = await client.facebook.searchAdLibraryAds({
  query: "value",
});

if (!result.ok) {
  console.error(result.error);
} else {
  console.log(result.value.data);
}
```

### Node.js

```javascript
const response = await fetch(
  "https://api.socialfetch.dev/v1/facebook/ad-library/ads/search?query=value",
  {
    headers: {
      "x-api-key": "YOUR_API_KEY",
    }
  }
);

const data = await response.json();
console.log(data);
```

### cURL

```bash
curl "https://api.socialfetch.dev/v1/facebook/ad-library/ads/search?query=value" \
  -H "x-api-key: YOUR_API_KEY"
```

### Python

```python
import requests

response = requests.get(
    "https://api.socialfetch.dev/v1/facebook/ad-library/ads/search?query=value",
    headers={"x-api-key": "YOUR_API_KEY"},
)
data = response.json()
print(data)
```

### Example: optional query parameters

First request illustrating common optional query flags (adjust values to your integration):

```javascript
const url = "https://api.socialfetch.dev/v1/facebook/ad-library/ads/search?sortBy=impressions";
const response = await fetch(url, {
  headers: { "x-api-key": "YOUR_API_KEY" },
});
const data = await response.json();
```

### Example: next page (pagination)

After a successful response, if pagination is not finished, request the next page using `cursor` (URL-encode when composing the query string):

```javascript
const previous = await response.json();
const nextCursor = previous?.data?.page?.nextCursor;
const hasMore = previous?.data?.page?.hasMore;
if (!hasMore || nextCursor == null) {
  // no more pages
} else {
  const nextUrl = new URL("https://api.socialfetch.dev/v1/facebook/ad-library/ads/search");
  nextUrl.searchParams.set("cursor", nextCursor);
  // optionally preserve sort: nextUrl.searchParams.set("sortBy", "latest");
  const nextResponse = await fetch(nextUrl.toString(), {
    headers: { "x-api-key": "YOUR_API_KEY" },
  });
  const nextData = await nextResponse.json();
}
```