# Accounts

Manage connected LinkedIn accounts with the SDK: list accounts, refresh profile info, connect new ones, disconnect, and regenerate tokens.

Manage your connected LinkedIn accounts programmatically. See the [Admin overview](/sdks/admin-overview) for initialization.

## Get all accounts

```typescript
try {
  const { accounts, pendingConnectionSessions } = await admin.accounts.getAll();

  for (const account of accounts) {
    console.log(`${account.name} (${account.status}) – ${account.id}`);
    console.log(`Profile: ${account.url}`);
    console.log(`Headline: ${account.headline ?? 'not parsed yet'}`);
    if (account.reconnectionLink) {
      console.log(`Reconnect: ${account.reconnectionLink}`);
    }
  }

  for (const session of pendingConnectionSessions) {
    console.log(`Pending session: ${session.sessionId} (${session.status})`);
  }
} catch (e) {
  if (e instanceof LinkedApiError) {
    console.error(`Critical Error - Type: ${e.type}, Message: ${e.message}`);
  } else {
    console.error('An unexpected, non-API error occurred:', e);
  }
}
```

```python
from linkedapi import LinkedApiError

try:
    result = admin.accounts.get_all()
    accounts = result.accounts
    pending_connection_sessions = result.pending_connection_sessions

    for account in accounts:
        print(f"{account.name} ({account.status}) – {account.id}")
        print(f"Profile: {account.url}")
        print(f"Headline: {account.headline or 'not parsed yet'}")
        if account.reconnection_link:
            print(f"Reconnect: {account.reconnection_link}")

    for session in pending_connection_sessions:
        print(f"Pending session: {session.session_id} ({session.status})")
except LinkedApiError as e:
    print(f"Critical Error - Type: {e.type}, Message: {e.message}")
except Exception as error:
    print("An unexpected, non-API error occurred:", error)
```

### Data

- `accounts` – array of connected accounts, each containing:
  - `id` – account UUID.
  - `name` – LinkedIn account name.
  - `url` – public LinkedIn profile URL for the connected account.
  - `avatarUrl` / `avatar_url` – LinkedIn profile image URL, or `null` / `None` when it has not been parsed yet.
  - `headline` – LinkedIn headline shown below the account name, or `null` / `None` when it has not been parsed yet.
  - `countryCode` – country code selected during connection.
  - `identificationToken` – token used in the `identification-token` header for Account API calls.
  - `status` – `active`, `frozen`, or `reconnection_required`.
  - `connectedAt` – ISO 8601 timestamp.
  - `reconnectionSessionId` / `reconnection_session_id` – present when `status` is `reconnection_required`.
  - `reconnectionLink` / `reconnection_link` – present when `status` is `reconnection_required`.
- `pendingConnectionSessions` – array of pending sessions, each containing `sessionId` and `status`.

For `reconnection_required` accounts, `getAll` creates a new reconnection session automatically when no active reconnection session exists.

## Refresh account profile info

Use `reparseAccountInfo` to refresh the stored LinkedIn profile URL, avatar URL, headline, and name for a connected account. The method starts a background workflow and returns its `workflowId`; call `getAll` after the workflow completes to read the updated account fields.

```typescript
const { workflowId } = await admin.accounts.reparseAccountInfo({
  accountId: 'f9b4346a-...',
});

console.log('Reparse workflow:', workflowId);
```

```python
from linkedapi import ReparseAccountInfoParams

result = admin.accounts.reparse_account_info(
    ReparseAccountInfoParams(account_id="f9b4346a-...")
)

print("Reparse workflow:", result.workflow_id)
```

### Params

- `accountId` / `account_id` – UUID of the account to refresh.

### Result

- `workflowId` / `workflow_id` – workflow ID for the background reparse operation.

`avatarUrl` / `avatar_url` and `headline` can remain empty when LinkedIn does not render those values or the account session needs reconnection.

## Connect a new account

Connecting a LinkedIn account is a multi-step process:

```typescript
// 1. Create a connection session
const { sessionId, connectionLink } = await admin.accounts.createConnectionSession();
console.log('Open this link to connect:', connectionLink);

// 2. Poll until the session completes
const POLL_INTERVAL_MS = 3000;
const MAX_WAIT_MS = 2 * 60 * 1000;
const deadline = Date.now() + MAX_WAIT_MS;
const sleep = (ms: number) => new Promise((resolve) => setTimeout(resolve, ms));

let session;

do {
  if (Date.now() >= deadline) {
    throw new Error('Timed out waiting for connection session completion');
  }

  await sleep(POLL_INTERVAL_MS);
  session = await admin.accounts.getConnectionSession({ sessionId });
} while (session.session.status === 'pending' ||
         session.session.status === 'preparing' ||
         session.session.status === 'serving' ||
         session.session.status === 'streaming');

if (session.session.status === 'success') {
  console.log('Account connected successfully!');

  // 3. Get the new account details
  const { accounts } = await admin.accounts.getAll();
  console.log('Total accounts:', accounts.length);
}
```

```python
import time

from linkedapi import GetConnectionSessionParams

# 1. Create a connection session
created = admin.accounts.create_connection_session()
session_id = created.session_id
print("Open this link to connect:", created.connection_link)

# 2. Poll until the session completes
POLL_INTERVAL_SECONDS = 3
MAX_WAIT_SECONDS = 2 * 60
deadline = time.monotonic() + MAX_WAIT_SECONDS

in_progress_statuses = {"pending", "preparing", "serving", "streaming"}

while True:
    if time.monotonic() >= deadline:
        raise TimeoutError("Timed out waiting for connection session completion")

    time.sleep(POLL_INTERVAL_SECONDS)
    session = admin.accounts.get_connection_session(
        GetConnectionSessionParams(session_id=session_id)
    )
    if session.session.status not in in_progress_statuses:
        break

if session.session.status == "success":
    print("Account connected successfully!")

    # 3. Get the new account details
    accounts = admin.accounts.get_all().accounts
    print("Total accounts:", len(accounts))
```

### createConnectionSession data

- `sessionId` – session UUID for tracking.
- `connectionLink` – URL to open in a browser to complete the LinkedIn login.

### createConnectionSession errors

- `noAvailableSeats` – no available seats. All seats are occupied by active accounts or pending connection sessions.
- `dailyConnectionAttemptsExceeded` – too many connection attempts in the last 24 hours.

## Reconnect an account

Use `createReconnectionSession` for accounts with `status` equal to `reconnection_required`. The method cancels the previous active reconnection session, if one exists, and returns a fresh reconnection link. If an in-progress reconnection session is applying a pending proxy change, Linked API returns that existing session instead so the proxy change state is preserved.

```typescript
const { reconnectionSessionId, reconnectionLink } =
  await admin.accounts.createReconnectionSession({
    accountId: 'f9b4346a-...',
  });

console.log('Open this link to reconnect:', reconnectionLink);
```

```python
from linkedapi import CreateReconnectionSessionParams

created = admin.accounts.create_reconnection_session(
    CreateReconnectionSessionParams(account_id="f9b4346a-...")
)

print("Open this link to reconnect:", created.reconnection_link)
```

### createReconnectionSession params

- `accountId` / `account_id` – UUID of the account to reconnect.

### createReconnectionSession data

- `reconnectionSessionId` / `reconnection_session_id` – session UUID for tracking.
- `reconnectionLink` / `reconnection_link` – URL to open in a browser to complete LinkedIn reconnection.

### createReconnectionSession errors

- `invalidRequestPayload` – the account is not in `reconnection_required` status or cannot be reconnected.

### getConnectionSession params

- `sessionId` – session UUID.

### Session statuses

| Status | Description |
|--------|-------------|
| `pending` | Session created, waiting for user to open the link |
| `preparing` | Browser is being provisioned |
| `serving` | Browser is ready, waiting for user to connect |
| `streaming` | User is connected and logging in |
| `success` | Login completed, account is being created |
| `expired` | Session timed out |
| `error` | An error occurred |
| `cancelled` | Session was cancelled |

## Cancel connection session

```typescript
await admin.accounts.cancelConnectionSession({ sessionId: '990eef7a-...' });
```

```python
from linkedapi import CancelConnectionSessionParams

admin.accounts.cancel_connection_session(
    CancelConnectionSessionParams(session_id="990eef7a-...")
)
```

### Params

- `sessionId` – session UUID.

## Disconnect account

```typescript
await admin.accounts.disconnect({ accountId: 'f9b4346a-...' });
```

```python
from linkedapi import DisconnectParams

admin.accounts.disconnect(DisconnectParams(account_id="f9b4346a-..."))
```

### Params

- `accountId` – UUID of the account to disconnect.

> **Warning:** This action is irreversible. The account must be reconnected from scratch.

## Regenerate identification token

```typescript
const { token } = await admin.accounts.regenerateIdentificationToken({
  accountId: 'f9b4346a-...',
});

console.log('New token:', token);
```

```python
from linkedapi import RegenerateTokenParams

result = admin.accounts.regenerate_identification_token(
    RegenerateTokenParams(account_id="f9b4346a-...")
)

print("New token:", result.token)
```

### Params

- `accountId` – UUID of the account.

### Data

- `token` – the new identification token.

> **Important:** Update the `identificationToken` in all your SDK instances immediately after regeneration.

## Errors

All account methods may throw:

- `linkedApiTokenRequired` – missing token.
- `invalidLinkedApiToken` – invalid or expired token.
- `accountNotFound` – account does not exist or does not belong to you.
- `tooManyRequests` – rate limit exceeded.

For the complete HTTP API reference, see [Admin API: Accounts](/docs/admin-accounts) and [Connection Sessions](/docs/admin-connection-sessions).
