> To build or manage a Wix site with an AI agent, follow https://www.wix.com/headless/skill.md
> It builds a new Wix site or puts your own site online, from a prompt, and keeps changing it afterwards. The pages are code in any web technology, and Wix runs the backend.
> It works through the Wix plugin (the Wix MCP and the Wix skills), the Wix CLI or no Wix login, and puts the site live on Wix hosting or on another host.
> Business features include a store, bookings, events and tickets, a restaurant, a blog, forms, members and many more.
> Read the Wix skills online at https://www.wix.com/skills
> 
> Portal Navigation:
> 
> - Append `.md` to any URL under `https://dev.wix.com/docs/` to get its markdown version.
> - Pages are either content pages (article or reference text) or menu pages (a list of links to child pages).
> - To get a menu page, truncate any URL to a parent path and append `.md` (e.g. `https://dev.wix.com/docs/sdk.md`, `https://dev.wix.com/docs/sdk/core-modules.md`).
> - If a reference page seems to be missing its schema (parameters, return types, or type definitions), append `?schema=true` to its `.md` URL (e.g. `https://dev.wix.com/docs/contexts/contexts/stores/category-info/use-category-info-context.md?schema=true`).
> - Top-level index of all portals: https://dev.wix.com/docs/llms.txt
> - Full concatenated docs: https://dev.wix.com/docs/llms-full.txt

# FindOrCreateLabel

# Package: contacts

# Namespace: ContactLabelsServiceV4

# Method link: https://dev.wix.com/docs/api-reference/crm/members-contacts/contacts/labels/find-or-create-label.md

## Permission Scopes:
Manage Contact Labels: SCOPE.DC-CONTACTS.MANAGE-LABELS

## Introduction

Retrieves a label with a specified name, or creates one if it doesn't exist.

Successful calls to this method always return a label,
which can be specified in subsequent calls.

For example, in the Contacts API, Label Contact and Unlabel Contact
calls will fail if you include a non-existent label.
To ensure successful calls, you can call this method first,
and then use the response in the Label Contact and Unlabel Contact calls.

To find an existing label without potentially creating a new one, call
Get Label or Query Labels.

---

## REST API

### Schema

```
 Method: findOrCreateLabel
 Description: Retrieves a label with a specified name, or creates one if it doesn't exist.  Successful calls to this method always return a label, which can be specified in subsequent calls.  For example, in the Contacts API, Label Contact and Unlabel Contact calls will fail if you include a non-existent label. To ensure successful calls, you can call this method first, and then use the response in the Label Contact and Unlabel Contact calls.  To find an existing label without potentially creating a new one, call Get Label or Query Labels.
 URL: https://www.wixapis.com/contacts/v4/labels
 Method: POST
 # Note: If the parameter `a.b` is listed under required parameters, `b` is only required if `a` is also present.
 Required parameters:  displayName
 Method parameters: 
   param name: displayName | type: displayName | description: Display name to retrieve or create.  If an existing label is an exact match for the specified display name, the existing label is returned. If not, a new label is created and returned. | required: true | validation: minLength 1, maxLength 180
   param name: language | type: language | description: Language for localization. 2-letter language code in [ISO 639-1 alpha-2](https://en.wikipedia.org/wiki/List_of_ISO_639_language_codes) format.  | validation: format LANGUAGE
 Return type: FindOrCreateLabelResponse
  - name: label | type: ContactLabel | description: Label that was found or created.  
     - name: namespace | type: string | description: Label namespace.  Labels created by calling the Find Or Create Label method are automatically assigned to the `custom` namespace.  | read-only: true | validation: minLength 1, maxLength 25
     - name: namespaceDisplayName | type: string | description: Display name for the namespace, used to organize the list of labels in the site dashboard.  | read-only: true | validation: minLength 1, maxLength 180
     - name: key | type: string | description: Label key.  `key` is generated when the label is created. It can't be modified, even if `displayName` is updated.  | read-only: true | validation: minLength 1, maxLength 80
     - name: displayName | type: string | description: Label display name shown in the dashboard.  | validation: minLength 1, maxLength 180
     - name: labelType | type: LabelType | description: Label type indicating how the label was created.  | read-only: true 
         - enum:
         -     SYSTEM: Default system label for the contact list.
         -     USER_DEFINED: Label created by calling the Find Or Create Label method.
         -     WIX_APP_DEFINED: Label created by an app built by Wix.
     - name: createdDate | type: string | description: Date and time the label was created.  | read-only: true | validation: format date-time
     - name: updatedDate | type: string | description: Date and time the label was last updated.  | read-only: true | validation: format date-time
  - name: newLabel | type: boolean | description: Indicates whether the label was just created or already existed.  Returns `true` if the label was just created.  

 Possible Errors:
   HTTP Code: 428 | Status Code: FAILED_PRECONDITION | Application Code: LABELS_QUOTA_REACHED | Description: Maximum number of labels reached. Labels must be deleted before any more can be created.


```

### Examples

### Find or Create Label
```curl
curl -X POST 'https://www.wixapis.com/contacts/v4/labels'  \
  -H 'Content-Type: application/json' \
  -H 'Authorization: <AUTH>' \
  --data-binary '{ "displayName": "My Label" }'
```

---

## JavaScript SDK

### Schema

```
 Method: wixClientAdmin.crm.labels.findOrCreateLabel(displayName, options)
 Description: Retrieves a label with a specified name, or creates one if it doesn't exist.  Successful calls to this method always return a label, which can be specified in subsequent calls.  For example, in the Contacts API, Label Contact and Unlabel Contact calls will fail if you include a non-existent label. To ensure successful calls, you can call this method first, and then use the response in the Label Contact and Unlabel Contact calls.  To find an existing label without potentially creating a new one, call Get Label or Query Labels.
 # Note: If the parameter `a.b` is listed under required parameters, `b` is only required if `a` is also present.
 Required parameters:  displayName
 Method parameters: 
   param name: displayName | type: string | description: Display name to retrieve or create.  If an existing label is an exact match for the specified display name, the existing label is returned. If not, a new label is created and returned. | required: true | validation: minLength 1, maxLength 180
   param name: options | type: FindOrCreateLabelOptions  none  
        - name: language | type: string | description: Language for localization. 2-letter language code in [ISO 639-1 alpha-2](https://en.wikipedia.org/wiki/List_of_ISO_639_language_codes) format.  | validation: format LANGUAGE
 Return type: PROMISE<FindOrCreateLabelResponse>
  - name: label | type: ContactLabel | description: Label that was found or created.  
     - name: namespace | type: string | description: Label namespace.  Labels created by calling the Find Or Create Label method are automatically assigned to the `custom` namespace.  | read-only: true | validation: minLength 1, maxLength 25
     - name: namespaceDisplayName | type: string | description: Display name for the namespace, used to organize the list of labels in the site dashboard.  | read-only: true | validation: minLength 1, maxLength 180
     - name: key | type: string | description: Label key.  `key` is generated when the label is created. It can't be modified, even if `displayName` is updated.  | read-only: true | validation: minLength 1, maxLength 80
     - name: displayName | type: string | description: Label display name shown in the dashboard.  | validation: minLength 1, maxLength 180
     - name: labelType | type: LabelType | description: Label type indicating how the label was created.  | read-only: true 
         - enum:
         -     SYSTEM: Default system label for the contact list.
         -     USER_DEFINED: Label created by calling the Find Or Create Label method.
         -     WIX_APP_DEFINED: Label created by an app built by Wix.
     - name: _createdDate | type: Date | description: Date and time the label was created.  | read-only: true 
     - name: _updatedDate | type: Date | description: Date and time the label was last updated.  | read-only: true 
  - name: newLabel | type: boolean | description: Indicates whether the label was just created or already existed.  Returns `true` if the label was just created.  

 Possible Errors:
   HTTP Code: 428 | Status Code: FAILED_PRECONDITION | Application Code: LABELS_QUOTA_REACHED | Description: Maximum number of labels reached. Labels must be deleted before any more can be created.


```

### Examples

### Create a new label and add it to a contact (with elevated permissions)
This function creates a new label, gets the label's key, and then adds the label to the contact.

```javascript
import { contacts, labels } from '@wix/crm';
import { auth } from '@wix/essentials';

/* Sample contactId value: '2712ae1d-3f64-46c2-ac3a-94a6c2e29847'
 * 
 * Sample displayName value: 'Supplier'
 */

export async function addNewLabelToContact(displayName, contactId) {
  
  try {
    const elevatedCreateLabel = auth.elevate(labels.findOrCreateLabel);
    const elevatedLabelContact = auth.elevate(contacts.labelContact);
    const newLabel = await elevatedCreateLabel(displayName);
    const labelKeys = [newLabel.label.key];
    // Retrieve the new label's key
    if (newLabel.newLabel) {
      // Label contact
      const contact = await elevatedLabelContact(contactId, labelKeys);
      const contactLabels = contact.contact.info.labelKeys.items;

      return contactLabels;
    }
    else {
      return "Label was not added to contact.";
    }
  } catch (error) {
    console.log(error);
    // Handle the error
  }
}

/* Promise resolves to: 
 * [
 *   "custom.contact",
 *   "custom.supplier"
 * ]
 */
```

### Create a new label and add it to a contact
This function creates a new label, gets the label's key, and then adds the label to the contact.

```javascript
import { contacts, labels } from '@wix/crm';

/* Sample contactId value: '2712ae1d-3f64-46c2-ac3a-94a6c2e29847'
 * 
 * Sample displayName value: 'Supplier'
 */

export async function addNewLabelToContact(displayName, contactId) {
  
  try {
    const newLabel = await labels.findOrCreateLabel(displayName);
    const labelKeys = [newLabel.label.key];
    // Retrieve the new label's key
    if (newLabel.newLabel) {
      // Label contact
      const contact = await contacts.labelContact(contactId, labelKeys);
      const contactLabels = contact.contact.info.labelKeys.items;

      return contactLabels;
    }
    else {
      return "Label was not added to contact.";
    }
  } catch (error) {
    console.log(error);
    // Handle the error
  }
}

/* Promise resolves to: 
 * [
 *   "custom.contact",
 *   "custom.supplier"
 * ]
 */
```

### Find a label (with elevated permissions)
```javascript
import { labels } from '@wix/crm';
import { auth } from '@wix/essentials';

/* Sample displayName value: 'Active Customer' */

export async function myFindLabelFunction(displayName) {
  
  try {
    const elevatedFindLabel = auth.elevate(labels.findOrCreateLabel);
    const label = await elevatedFindLabel(displayName);    
    console.log('This label already exists:', label);
 
    return label;  
  } catch (error) {
    console.log(error);
    // Handle the error
  }
}

/* Promise resolves to: 
 * {
 *   "label": {
 *     "namespace": "custom",
 *     "namespaceDisplayName": "Labels",
 *     "key": "custom.active-customer",
 *     "displayName": "Active Customer",
 *     "labelType": "USER_DEFINED",
 *     "legacyId": "74f1e5c6-d9d5-4485-b272-13081ea35f38",
 *     "_createdDate": "2023-12-25T06:13:21.000Z",
 *     "_updatedDate": "2023-12-25T06:13:21.000Z"
 *   },
 *   "newLabel": false
 * }
 */
```

### Find a label
```javascript
import { labels } from '@wix/crm';

/* Sample displayName value: 'Active Customer' */

export async function myFindLabelFunction(displayName) {
  
  try {
    const label = await labels.findOrCreateLabel(displayName);    
    console.log('This label already exists:', label);
 
    return label;  
  } catch (error) {
    console.log(error);
    // Handle the error
  }
}

/* Promise resolves to: 
 * {
 *   "label": {
 *     "namespace": "custom",
 *     "namespaceDisplayName": "Labels",
 *     "key": "custom.active-customer",
 *     "displayName": "Active Customer",
 *     "labelType": "USER_DEFINED",
 *     "legacyId": "74f1e5c6-d9d5-4485-b272-13081ea35f38",
 *     "_createdDate": "2023-12-25T06:13:21.000Z",
 *     "_updatedDate": "2023-12-25T06:13:21.000Z"
 *   },
 *   "newLabel": false
 * }
 */
```

### Create a label (with elevated permissions)
```javascript
import { labels } from '@wix/crm';
import { auth } from '@wix/essentials';

/*  Sample displayName value: 'At Risk' */

const elevatedFindOrCreateLabel = auth.elevate(labels.findOrCreateLabel);

export async function myCreateLabelFunction(displayName) {
  
  try {
    const newLabel = await elevatedFindOrCreateLabel(displayName);    
    console.log('Successfully created a new label:', newLabel);
 
    return newLabel;  
  } catch (error) {
    console.log(error);
    // Handle the error
  }
}

/* Promise resolves to: 
 * {
 *   "label": {
 *     "namespace": "custom",
 *     "namespaceDisplayName": "Labels",
 *     "key": "custom.at-risk",
 *     "displayName": "At Risk",
 *     "labelType": "USER_DEFINED",
 *     "legacyId": "65bd6a68-e10e-4831-8d92-c90e75be1570",
 *     "_createdDate": "2023-12-25T08:38:36.138Z",
 *     "_updatedDate": "2023-12-25T08:38:36.138Z"
 *   },
 *   "newLabel": true
 * }
 */
```

### Create a label
```javascript
import { labels } from '@wix/crm';

/*  Sample displayName value: 'At Risk' */

export async function myCreateLabelFunction(displayName) {
  
  try {
    const newLabel = await labels.findOrCreateLabel(displayName);    
    console.log('Successfully created a new label:', newLabel);
 
    return newLabel;  
  } catch (error) {
    console.log(error);
    // Handle the error
  }
}

/* Promise resolves to: 
 * {
 *   "label": {
 *     "namespace": "custom",
 *     "namespaceDisplayName": "Labels",
 *     "key": "custom.at-risk",
 *     "displayName": "At Risk",
 *     "labelType": "USER_DEFINED",
 *     "legacyId": "65bd6a68-e10e-4831-8d92-c90e75be1570",
 *     "_createdDate": "2023-12-25T08:38:36.138Z",
 *     "_updatedDate": "2023-12-25T08:38:36.138Z"
 *   },
 *   "newLabel": true
 * }
 */
```

### findOrCreateLabel (self-managed)
Self-managed SDK calls require you to [create a client](https://dev.wix.com/docs/sdk/articles/work-with-the-sdk/about-the-wix-client.md).

```javascript
import { createClient } from '@wix/sdk';
import { labels } from '@wix/crm';
// Import the auth strategy for the relevant access type
// Import the relevant host module if needed

const myWixClient = createClient ({
  modules: { labels },
  // Include the auth strategy and host as relevant
});


async function findOrCreateLabel(displayName,options) {
  const response = await myWixClient.labels.findOrCreateLabel(displayName,options);
};
```

---