> ## Documentation Index
> Fetch the complete documentation index at: https://developer.salesforge.ai/llms.txt
> Use this file to discover all available pages before exploring further.

# Getting paginated contacts

> Page through every contact in a workspace with a cursor that remembers where you left off.

The contacts endpoint returns contacts one page at a time. Each response includes a cursor that marks where the page ended. Send it back in your next request to get the following page, and stop when the API tells you there are no more.

`GET /public/v2/workspaces/{workspaceID}/contacts`

> [!WARNING]
>
> Offset pagination (`limit` with `offset`) will be deprecated soon. See [Coming from offset pagination?](#coming-from-offset-pagination).

## Prerequisites

Prepare these values before you start:

* `WORKSPACE_ID`
* `SALESFORGE_API_KEY`

Send the raw API key in the `Authorization` header:

```http theme={null}
Authorization: YOUR_API_KEY
```

For the shared authentication pattern, see [Authentication](https://developer.salesforge.ai/authentication.md).

## How it works

**1. Request the first page**

Add `pagination=cursor` to your request. Use `limit` to set the page size. The default is 10 and the maximum is 1000.

```http theme={null}
GET /public/v2/workspaces/{workspaceID}/contacts?pagination=cursor&limit=100
```

> [!WARNING]
>
> A request with no `pagination` and no `cursor` still uses offset pagination, which will be deprecated soon. See [Coming from offset pagination?](#coming-from-offset-pagination).

**2. Read the response**

The response has the contacts for this page and the information you need to get the next one:

```json theme={null}
{
  "data": [
    {
      "id": "lead_123",
      "firstName": "Ada",
      "lastName": "Lovelace",
      "email": "ada@example.com",
      "company": "Analytical Engines",
      "linkedinUrl": "",
      "position": "Founder",
      "tags": ["pa-20261104"],
      "customVars": {},
      "sequences": []
    }
  ],
  "limit": 100,
  "hasMore": true,
  "nextCursor": "eyJ2IjoxLCJ3Ijoid2tzXzEyMyIsImkiOiJsZWFkXzEyMyJ9"
}
```

* `data` is the list of contacts on this page.
* `limit` is the page size the API used.
* `hasMore` is `true` when more contacts are available.
* `nextCursor` is the value to send in your next request. It is missing on the last page.

**3. Request the next page**

Send `nextCursor` as the `cursor` parameter. You don't need to send `pagination=cursor` again. Keep the same workspace, `limit`, and filters.

```http theme={null}
GET /public/v2/workspaces/{workspaceID}/contacts?cursor=NEXT_CURSOR&limit=100
```

**4. Stop when hasMore is false**

Repeat the previous step until `hasMore` is `false`. Check `hasMore` to decide when to stop. Don't count pages, and don't stop because a page has fewer contacts than `limit`.

## Code examples

Each example reads every contact in a workspace, one page at a time.

```javascript JavaScript theme={null}
const BASE_URL = "https://api.salesforge.ai/public/v2";

async function* getContacts(workspaceId, apiKey, limit = 100) {
  let cursor;
  let hasMore = true;

  while (hasMore) {
    const params = new URLSearchParams({ limit: String(limit) });
    if (cursor) {
      params.set("cursor", cursor);
    } else {
      params.set("pagination", "cursor");
    }

    const response = await fetch(
      `${BASE_URL}/workspaces/${workspaceId}/contacts?${params}`,
      { headers: { Authorization: apiKey } },
    );
    if (!response.ok) {
      throw new Error(`Request failed with status ${response.status}`);
    }

    const page = await response.json();
    yield* page.data;

    cursor = page.nextCursor;
    hasMore = page.hasMore;
  }
}

for await (const contact of getContacts(
  process.env.WORKSPACE_ID,
  process.env.SALESFORGE_API_KEY,
)) {
  console.log(contact.id, contact.email);
}
```

```typescript TypeScript theme={null}
const BASE_URL = "https://api.salesforge.ai/public/v2";

interface Contact {
  id: string;
  firstName: string;
  lastName: string;
  email: string;
  company: string;
  linkedinUrl: string;
  position: string;
  tags: string[];
  customVars: Record<string, string>;
}

interface ContactsPage {
  data: Contact[];
  limit: number;
  hasMore: boolean;
  nextCursor?: string;
}

async function* getContacts(
  workspaceId: string,
  apiKey: string,
  limit = 100,
): AsyncGenerator<Contact> {
  let cursor: string | undefined;
  let hasMore = true;

  while (hasMore) {
    const params = new URLSearchParams({ limit: String(limit) });
    if (cursor) {
      params.set("cursor", cursor);
    } else {
      params.set("pagination", "cursor");
    }

    const response = await fetch(
      `${BASE_URL}/workspaces/${workspaceId}/contacts?${params}`,
      { headers: { Authorization: apiKey } },
    );
    if (!response.ok) {
      throw new Error(`Request failed with status ${response.status}`);
    }

    const page = (await response.json()) as ContactsPage;
    yield* page.data;

    cursor = page.nextCursor;
    hasMore = page.hasMore;
  }
}

for await (const contact of getContacts(
  process.env.WORKSPACE_ID!,
  process.env.SALESFORGE_API_KEY!,
)) {
  console.log(contact.id, contact.email);
}
```

```go Go theme={null}
package main

import (
	"encoding/json"
	"fmt"
	"log"
	"net/http"
	"net/url"
	"os"
	"strconv"
)

const baseURL = "https://api.salesforge.ai/public/v2"

type Contact struct {
	ID        string `json:"id"`
	FirstName string `json:"firstName"`
	LastName  string `json:"lastName"`
	Email     string `json:"email"`
}

type ContactsPage struct {
	Data       []Contact `json:"data"`
	Limit      int       `json:"limit"`
	HasMore    bool      `json:"hasMore"`
	NextCursor string    `json:"nextCursor"`
}

func fetchPage(workspaceID, apiKey string, query url.Values) (*ContactsPage, error) {
	endpoint := fmt.Sprintf("%s/workspaces/%s/contacts?%s", baseURL, workspaceID, query.Encode())

	req, err := http.NewRequest(http.MethodGet, endpoint, nil)
	if err != nil {
		return nil, err
	}
	req.Header.Set("Authorization", apiKey)

	resp, err := http.DefaultClient.Do(req)
	if err != nil {
		return nil, err
	}
	defer resp.Body.Close()

	if resp.StatusCode != http.StatusOK {
		return nil, fmt.Errorf("request failed with status %d", resp.StatusCode)
	}

	var page ContactsPage
	if err := json.NewDecoder(resp.Body).Decode(&page); err != nil {
		return nil, err
	}
	return &page, nil
}

func main() {
	workspaceID := os.Getenv("WORKSPACE_ID")
	apiKey := os.Getenv("SALESFORGE_API_KEY")
	limit := 100

	query := url.Values{}
	query.Set("pagination", "cursor")
	query.Set("limit", strconv.Itoa(limit))

	for {
		page, err := fetchPage(workspaceID, apiKey, query)
		if err != nil {
			log.Fatal(err)
		}

		for _, contact := range page.Data {
			fmt.Println(contact.ID, contact.Email)
		}

		if !page.HasMore {
			break
		}

		query = url.Values{}
		query.Set("cursor", page.NextCursor)
		query.Set("limit", strconv.Itoa(limit))
	}
}
```

```python Python theme={null}
import os

import requests

BASE_URL = "https://api.salesforge.ai/public/v2"


def get_contacts(workspace_id, api_key, limit=100):
    url = f"{BASE_URL}/workspaces/{workspace_id}/contacts"
    headers = {"Authorization": api_key}
    params = {"pagination": "cursor", "limit": limit}

    while True:
        response = requests.get(url, headers=headers, params=params, timeout=30)
        response.raise_for_status()
        page = response.json()

        yield from page["data"]

        if not page["hasMore"]:
            break
        params = {"cursor": page["nextCursor"], "limit": limit}


for contact in get_contacts(os.environ["WORKSPACE_ID"], os.environ["SALESFORGE_API_KEY"]):
    print(contact["id"], contact["email"])
```

## Filter contacts

You can filter the list. Send the same filters on every page of the same listing.

| Filter | What it does |
| - | - |
| `tag_ids[]` | Returns contacts that have the given tags. |
| `validation_statuses[]` | Returns contacts with the given email validation statuses. |
| `not_in_sequence_id` | Returns contacts that are not in the given sequence. |
| `has_valid_linkedin` | Returns contacts that have a valid LinkedIn profile. |
| `not_in_esps[]` | Leaves out contacts on the given email service providers. |

For example, to read all contacts with one tag:

```http theme={null}
GET /public/v2/workspaces/{workspaceID}/contacts?pagination=cursor&limit=100&tag_ids[]=TAG_ID
```

> [!NOTE]
>
> The API returns a `400` error for query parameters it doesn't know. Check the spelling of each filter.

## Rules to remember

* A cursor is an opaque string. Don't build it, edit it, or store it for a long time. Use the `nextCursor` from the last response.
* A cursor works only for the workspace that created it. If you use it with another workspace, the API returns a `400` error.
* Keep the same filters and `limit` on every request in the same listing.
* Contacts come back in a fixed order, so you don't get the same contact twice while you page.
* A response doesn't include a total number of contacts. To get the total, call `GET /public/v2/workspaces/{workspaceID}/contacts/count` with the same filters.
* Listing contacts is rate limited per account: 60 requests per minute, a burst of 10, and 2 requests in flight. Read the pages one after another, and when you get `429`, wait for `Retry-After` before you send the request again. See [Rate limits](https://developer.salesforge.ai/salesforge-api/concepts/rate-limits.md).

## Coming from offset pagination?

> [!WARNING]
>
> Offset pagination will be deprecated soon. Requests that use `offset`, or that send neither `pagination` nor `cursor`, still work today. Move to cursor pagination before the deprecation.

Offset pagination reads a page by skipping a number of contacts, as in `limit=100&offset=5000`. Cursor pagination replaces the offset with a cursor that marks where the last page ended. Offset requests also get slower as the offset grows.

To migrate, make these changes in your code:

**1. Choose cursor mode on the first request**

Send `pagination=cursor` and remove `offset`.

| Offset pagination | Cursor pagination |
| - | - |
| `?limit=100&offset=0` | `?pagination=cursor&limit=100` |

**2. Replace the offset with a cursor**

Don't increase `offset` by `limit` after each page. Send the `nextCursor` from the last response as `cursor`.

| Offset pagination | Cursor pagination |
| - | - |
| `?limit=100&offset=100` | `?cursor=NEXT_CURSOR&limit=100` |

**3. Change how your loop stops**

Stop when `hasMore` is `false`. Don't stop by comparing `offset` with `total`, and don't stop when a page is smaller than `limit`.

**4. Replace total with the count endpoint**

Cursor responses have no `total` and no `offset`. If you show a total or a progress bar, call `GET /public/v2/workspaces/{workspaceID}/contacts/count` once, with the same filters.

Here is how the response changes:

```json Offset response theme={null}
{
  "total": 250000,
  "offset": 100,
  "limit": 100,
  "data": []
}
```

```json Cursor response theme={null}
{
  "data": [],
  "limit": 100,
  "hasMore": true,
  "nextCursor": "eyJ2IjoxLCJ3Ijoid2tzXzEyMyIsImkiOiJsZWFkXzEyMyJ9"
}
```

> [!WARNING]
>
> You can't use `offset` together with `cursor` or `pagination=cursor`. The API returns a `400` error.

## Errors

| Status | Cause | Fix |
| - | - | - |
| `400` | You sent `offset` together with `cursor` or `pagination=cursor`. | Remove `offset`. |
| `400` | The cursor is invalid, or it belongs to another workspace. | Use the `nextCursor` from the last response for the same workspace. |
| `400` | The `pagination` value is not `offset` or `cursor`. | Use `cursor`. |
| `400` | The request has a query parameter the API doesn't know. | Check the filter names. |
| `401` | The API key is missing or invalid. | Check the `Authorization` header. |

## Related resources

* [Authentication](https://developer.salesforge.ai/authentication.md)
* [Contacts and leads](https://developer.salesforge.ai/salesforge-api/concepts/leads-contacts.md)
* [Enroll contacts with preflight](https://developer.salesforge.ai/products/salesforge/enroll-contacts-with-preflight.md)


This documentation is built and hosted on [Mintlify](https://mintlify.com), a developer documentation platform.