# Sync contacts from your app (/developers/guides/sync-contacts)

> Keep Luso8 contacts up to date from your product's signups, with upserts, bulk imports and list enrollment.

> **Preview:** this feature is in preview. The contract is stable enough to build against, but details may change before general availability.

This guide shows how to push people from your own product into Luso8 as they sign up or change their details, and how to add them to a list that a [campaign](/luso8/campaigns) can use. You will build an idempotent **upsert**: find the contact by email, update it if it exists, create it if it does not.

## What you need [#what-you-need]

- A Luso8 workspace where you are an Owner or Administrator.
- An [API key](/developers/api-keys) with the `contacts:write` and `lists:write` scopes.
- The ID of the list you want new signups in. Open the list in **Data → Lists** and copy the ID from the URL, or call `GET /api/v1/lists`.

Store the key as `LUSO8_API_KEY` in your server environment. Never send it to the browser.

## 1. Find a contact by email [#1-find-a-contact-by-email]

`GET /api/v1/contacts?search={email}`

`search` matches names, emails and phone numbers, so filter the results for an exact email match:

```js tab="Node.js"
const BASE = 'https://api.luso8.rexplore.ai/api/v1';
const headers = {
  Authorization: `Bearer ${process.env.LUSO8_API_KEY}`,
  'Content-Type': 'application/json',
};

async function findContactByEmail(email) {
  const url = new URL(`${BASE}/contacts`);
  url.searchParams.set('search', email);
  url.searchParams.set('limit', '10');
  const res = await fetch(url, { headers });
  if (!res.ok) throw new Error(`Search failed: ${res.status} ${await res.text()}`);
  const contacts = await res.json();
  return contacts.find((c) => c.email?.toLowerCase() === email.toLowerCase()) ?? null;
}
```

```python tab="Python"
import os
import requests

BASE = "https://api.luso8.rexplore.ai/api/v1"
session = requests.Session()
session.headers["Authorization"] = f"Bearer {os.environ['LUSO8_API_KEY']}"

def find_contact_by_email(email: str) -> dict | None:
    res = session.get(f"{BASE}/contacts", params={"search": email, "limit": 10}, timeout=30)
    res.raise_for_status()
    for contact in res.json():
        if (contact.get("email") or "").lower() == email.lower():
            return contact
    return None
```

## 2. Create or update it [#2-create-or-update-it]

`POST /api/v1/contacts`

`PUT /api/v1/contacts/{contact_id}`

Map your user fields to Luso8 contact fields. All fields are optional; send the ones you have. `PUT` only changes the fields you send.

| Luso8 field | Example |
| --- | --- |
| `email` | `ada@example.com` |
| `first_name`, `last_name` | `Ada`, `Lovelace` |
| `phone`, `mobile_phone` | `+265991234567` (E.164 recommended) |
| `company_name` | `Analytical Engines Ltd` |
| `job_title` | `Head of Operations` |
| `country`, `town` | `Malawi`, `Lilongwe` |
| `source` | `website-signup` |
| `notes` | Free text |

```js tab="Node.js"
async function upsertContact(user) {
  const body = {
    email: user.email,
    first_name: user.firstName,
    last_name: user.lastName,
    phone: user.phone,
    company_name: user.company,
    job_title: user.jobTitle,
    country: user.country,
    source: 'website-signup',
  };

  const existing = await findContactByEmail(user.email);
  const res = existing
    ? await fetch(`${BASE}/contacts/${existing.id}`, { method: 'PUT', headers, body: JSON.stringify(body) })
    : await fetch(`${BASE}/contacts`, { method: 'POST', headers, body: JSON.stringify(body) });

  if (!res.ok) throw new Error(`Upsert failed: ${res.status} ${await res.text()}`);
  return res.json(); // the saved contact, including its id
}
```

```python tab="Python"
def upsert_contact(user: dict) -> dict:
    body = {
        "email": user["email"],
        "first_name": user.get("first_name"),
        "last_name": user.get("last_name"),
        "phone": user.get("phone"),
        "company_name": user.get("company"),
        "job_title": user.get("job_title"),
        "country": user.get("country"),
        "source": "website-signup",
    }
    body = {k: v for k, v in body.items() if v is not None}

    existing = find_contact_by_email(user["email"])
    if existing:
        res = session.put(f"{BASE}/contacts/{existing['id']}", json=body, timeout=30)
    else:
        res = session.post(f"{BASE}/contacts", json=body, timeout=30)
    res.raise_for_status()
    return res.json()
```

## 3. Add the contact to a list [#3-add-the-contact-to-a-list]

`POST /api/v1/lists/{list_id}/contacts`

The body takes one or more contact IDs. Contacts already in the list are left as they are.

```js tab="Node.js"
async function addToList(listId, contactIds) {
  const res = await fetch(`${BASE}/lists/${listId}/contacts`, {
    method: 'POST',
    headers,
    body: JSON.stringify({ contact_ids: contactIds }),
  });
  if (!res.ok) throw new Error(`Add to list failed: ${res.status} ${await res.text()}`);
  return res.json();
}

// In your signup handler:
const contact = await upsertContact(user);
await addToList(process.env.LUSO8_SIGNUPS_LIST_ID, [contact.id]);
```

```python tab="Python"
def add_to_list(list_id: str, contact_ids: list[str]) -> dict:
    res = session.post(f"{BASE}/lists/{list_id}/contacts", json={"contact_ids": contact_ids}, timeout=30)
    res.raise_for_status()
    return res.json()

# In your signup handler:
contact = upsert_contact(user)
add_to_list(os.environ["LUSO8_SIGNUPS_LIST_ID"], [contact["id"]])
```

If a campaign is enrolling that list, new members can be added to the campaign from the campaign's **Contacts** tab, or with `POST /api/v1/campaigns/{campaign_id}/contacts/from-lists` (scope `campaigns:write`).

## 4. Backfill existing users in bulk [#4-backfill-existing-users-in-bulk]

`POST /api/v1/contacts/bulk`

For a first import, send batches of contacts in one request instead of one call per user. The body is an array of the same contact objects you send to `POST /api/v1/contacts`.

```js tab="Node.js"
async function backfill(users, batchSize = 200) {
  for (let i = 0; i < users.length; i += batchSize) {
    const batch = users.slice(i, i + batchSize).map((u) => ({
      email: u.email,
      first_name: u.firstName,
      last_name: u.lastName,
      company_name: u.company,
      source: 'backfill',
    }));
    const res = await fetch(`${BASE}/contacts/bulk`, { method: 'POST', headers, body: JSON.stringify(batch) });
    if (!res.ok) throw new Error(`Batch ${i / batchSize} failed: ${res.status} ${await res.text()}`);
  }
}
```

```python tab="Python"
def backfill(users: list[dict], batch_size: int = 200) -> None:
    for i in range(0, len(users), batch_size):
        batch = [
            {
                "email": u["email"],
                "first_name": u.get("first_name"),
                "last_name": u.get("last_name"),
                "company_name": u.get("company"),
                "source": "backfill",
            }
            for u in users[i : i + batch_size]
        ]
        res = session.post(f"{BASE}/contacts/bulk", json=batch, timeout=120)
        res.raise_for_status()
```

Run the backfill before you switch on real-time sync, and use upserts from then on so repeated events never create duplicates.

## 5. Handle rate limits and failures [#5-handle-rate-limits-and-failures]

Each key can make 600 requests per minute. A signup handler makes two or three calls per user, which is plenty for most products, but backfills and bursts can hit the limit:

- On `429`, wait for the `Retry-After` header and retry. See [Rate limits](/developers/rate-limits) for a ready-made helper.
- On `5xx` or network errors, retry with exponential backoff. The upsert is safe to repeat.
- On `422`, log the `detail` array: it names the invalid field. See [Errors](/developers/errors).
- Don't block your own signup on Luso8. Run the sync in a background job or queue, so a slow request never delays your user.

## Next steps [#next-steps]

<LinkGrid>
<LinkItem href="/developers/api-reference" title="API reference">
All contact, list and campaign endpoints.
</LinkItem>

<LinkItem href="/developers/webhooks" title="Webhooks">
Start a Luso8 workflow when a user signs up.
</LinkItem>

<LinkItem href="/luso8/crm/contacts" title="Contacts in Luso8">
Custom fields, enrichment and filters.
</LinkItem>

<LinkItem href="/luso8/campaigns" title="Campaigns">
Turn your list into an outreach sequence.
</LinkItem>
</LinkGrid>