---
schema_version: "1"
id: f611512819007707a8e0347151c3d9ce696a4a2f453d62dc9919674bc8332b49
title: Lead
collection: legacydeveloper
version: current
locale: en-us
portal_url: https://docs.salesforce.com/legacydeveloper/current/en-us/object_reference/sforce_api_objects_lead.md
canonical_url: https://developer.salesforce.com/docs/atlas.en-us.object_reference.meta/object_reference/sforce_api_objects_lead.htm
source_site: developer.salesforce.com
content_type: documentation
content_hash: 7a6e3ff62ae6fb2260cc4cc973f9afb3ad237aec49b2817aed4e7d2d4f391e5b
description: Represents a prospect or lead.
---
# Lead

Represents a prospect or lead.

## Supported Calls

create(), delete(), describeLayout(), describeSObjects(), getDeleted(), getUpdated(), merge(), query(), retrieve(), search(), undelete(), update(), upsert()

## Fields

| Field | Details |
| --- | --- |
| ActionCadenceAssigneeId | 
Type

reference

Properties

Filter, Group, Nillable, Sort

Description

The ID of the sales rep designated to work the lead through their assigned cadence. This field is available in API version 48.0 and later when the Sales Engagement license is enabled. To see this field, the user also needs the Sales Engagement User or Sales Engagement Quick Cadence Creator user permission set.



 |
| ActionCadenceId | 

Type

reference

Properties

Filter, Group, Nillable, Sort

Description

The ID of the lead’s assigned cadence. This field is available in API version 48.0 and later when the Sales Engagement license is enabled. To see this field, the user also needs the Sales Engagement User or Sales Engagement Quick Cadence Creator user permission set.



 |
| ActionCadenceState | 

Type

picklist

Properties

Filter, Group, Nillable, Restricted picklist, Sort

Description

The state of the current action cadence tracker. This field is available in API version 50.0 and later when the Sales Engagement license is enabled. To see this field, the user also needs the Sales Engagement User or Sales Engagement Quick Cadence Creator user permission set.

Possible values are:

- Complete
- Error
- Initializing
- Paused
- Processing
- Running





 |
| ActiveTrackerCount | 

Type

int

Properties

Filter, Group, Nillable, Sort

Description

The number of cadences that are actively running on this lead. This field is available in API version 57.0 and later when the Sales Engagement license is enabled. To see this field, the user also needs the Sales Engagement User or Sales Engagement Quick Cadence Creator user permission set.



 |
| ActivityMetricId | 

Type

reference

Properties

Filter, Group, Nillable, Sort

Description

When Einstein Activity Capture with Activity Metrics is enabled, the ID of the related activity metric.

This field is a relationship field.

This field is available in API version 41.0 and later.

Relationship Name

ActivityMetric

Refers To

ActivityMetric



 |
| ActivityMetricRollupId | 

Type

reference

Properties

Filter, Group, Nillable, Sort

Description

When Einstein Activity Capture with Activity Metrics is enabled, the ID of the related activity metric rollup.

This field is a relationship field.

This field is available in API version 41.0 and later.

Relationship Name

ActivityMetricRollup

Refers To

ActivityMetricRollup



 |
| Address | 

Type

address

Properties

Filter, Nillable

Description

The compound form of the address. Read-only. For details on compound address fields, see [Address Compound Fields](https://developer.salesforce.com/docs/atlas.en-us.object_reference.meta/object_reference/compound_fields_address.htm "Standard addresses—addresses built into standard objects in Salesforce—are accessible in the SOAP API and REST API as an Address, a structured compound data type, as well as individual address elements. If you enabled Custom Address Fields, you can also add custom fields that mimic the standard address field behavior.").



 |
| AnnualRevenue | 

Type

currency

Properties

Create, Filter, Nillable, Sort, Update

Description

Annual revenue for the lead’s company.



 |
| City | 

Type

string

Properties

Create, Filter, Group, Nillable, Sort, Update

Description

City for the lead’s address.



 |
| CleanStatus | 

Type

picklist

Properties

Create, Filter, Group, Nillable, Restricted picklist, Sort, Update

Description

Indicates the record's clean status compared with Data.com. .

Several values for CleanStatus appear with different labels on the lead record.

Values include:

- Acknowledged - Reviewed
- Different
- Inactive
- Matched - In Sync
- NotFound - Not Found
- Pending - Not Compared
- SelectMatch - Select Match Skipped





 |
| Company | 

Type

string

Properties

Create, Filter, Group, Nillable, Sort, Update

Description

Required. The lead’s company.

If person account record types have been enabled, and if the value of Company is null, the lead converts to a person account.





 |
| CompanyDunsNumber | 

Type

string

Properties

Create, Filter, Group, Nillable, Sort, Update

Description

The Data Universal Numbering System (D-U-N-S) number, which is a unique, nine-digit number assigned to every business location in the Dun & Bradstreet database that has a unique, separate, and distinct operation. Industries and companies use D-U-N-S numbers as a global standard for business identification and tracking. Maximum size is 9 characters.

This field is only available to organizations that use Data.com Prospector or Data.com Clean.





 |
| ConvertedAccountId | 

Type

reference

Properties

Create, Filter, Group, Nillable, Sort

Description

Object reference ID that points to the account into which the lead converted.

This is a relationship field.

Relationship Name

ConvertedAccount

Relationship Type

Lookup

Refers To

Account



 |
| ConvertedContactId | 

Type

reference

Properties

Create, Filter, Group, Nillable, Sort

Description

Object reference ID that points to the contact into which the lead converted.

This is a relationship field.

Relationship Name

ConvertedContact

Relationship Type

Lookup

Refers To

Contact



 |
| ConvertedDate | 

Type

date

Properties

Create, Filter, Group, Nillable, Sort

Description

Date on which this lead was converted.



 |
| ConvertedOpportunityId | 

Type

reference

Properties

Create, Filter, Group, Nillable, Sort

Description

Object reference ID that points to the opportunity into which the lead has been converted.

This is a relationship field.

Relationship Name

ConvertedOpportunity

Relationship Type

Lookup

Refers To

Opportunity



 |
| ConnectionReceivedId | 

Type

reference

Properties

Filter, Group, Nillable, Sort

Description

ID of the PartnerNetworkConnection that shared this record with your org. This field is available when Salesforce to Salesforce is enabled.



 |
| ConnectionSentId | 

Type

reference

Properties

Filter, Group, Nillable, Sort

Description

ID of the PartnerNetworkConnection that this record is shared with. This field is available Salesforce to Salesforce is enabled. In API version 16.0 and later, this value is null. Use PartnerNetworkRecordConnection object to forward records to connections.



 |
| Country | 

Type

string

Properties

Create, Filter, Group, Nillable, Sort, Update

Description

The lead’s country.



 |
| CountryCode | 

Type

picklist

Properties

Create, Filter, Group, Nillable, Sort, Update

Description

The ISO country code for the lead’s address.



 |
| CurrencyIsoCode | 

Type

picklist

Properties

Create, Defaulted on create, Filter, Group, Nillable, Restricted picklist, Sort, Update

Description

Available only for organizations with the multicurrency feature enabled. Contains the ISO code for any currency allowed by the organization.



 |
| DandBCompanyId | 

Type

reference

Properties

Create, Filter, Group, Nillable, Sort, Update

Description

Reference ID to a Dun & Bradstreet® company record, associated with an account added from Data.com.

Relationship Name

DandbCompany

Refers To

DandbCompany



 |
| Description | 

Type

textarea

Properties

Create, Nillable, Update

Description

The lead’s description.



 |
| Division | 

Type

picklist

Properties

Create, Defaulted on create, Filter, Group, Restricted picklist, Sort, Update

Description

A logical segment of your organization's data. For example, if your company is organized into different business units, you could create a division for each business unit, such as North America, Healthcare, or Consulting. Available only when the Division permission is enabled.



 |
| Email | 

Type

email

Properties

Create, Filter, Group, idLookup, Nillable, Sort, Update

Description

The lead’s email address.



 |
| EmailBouncedDate | 

Type

dateTime

Properties

Filter, Nillable, Sort, Update

Description

If bounce management is activated and an email sent to the lead bounced, the date and time of the bounce. Email bounce functionality isn't triggered by record updates, including updates to this field.



 |
| EmailBouncedReason | 

Type

string

Properties

Filter, Group, Nillable, Sort, Update

Description

If bounce management is activated and an email sent to the lead bounced, the reason for the bounce. Email bounce functionality isn't triggered by record updates, including updates to this field.



 |
| ExportStatus | 

Type

picklist

Properties

Filter, Restricted picklist, Sort

Description

Derived field for the record map for Partner Connect. The export status of this opportunity to the partner’s connected org. To see this field, enable Partner Connect and add the Export Vendor Records to an Authorized Partner Org user permission to the cosell export user. See [Set Up Partner Connect as a Vendor](https://help.salesforce.com/s/articleView?id=slack.prm_pc_setup_vendor_parent.htm&type=5&language=en_US) in Salesforce Help. Available in API version 62.0 and later.



 |
| Fax | 

Type

phone

Properties

Create, Filter, Group, Nillable, Sort, Update

Description

The lead’s fax number.



 |
| FirstCallDateTime | 

Type

datetime

Properties

Filter, Nillable, Sort

Description

The date and time of the first call placed to the lead. This field is available in API version 48.0 when the Sales Engagement license is enabled. To see this field, the user also needs the Sales Engagement User or Sales Engagement Quick Cadence Creator user permission set.



 |
| FirstEmailDateTime | 

Type

datetime

Properties

Filter, Nillable, Sort

Description

The date and time of the first email sent to the lead. This field is available in API version 48.0 when the Sales Engagement license is enabled. To see this field, the user also needs the Sales Engagement User or Sales Engagement Quick Cadence Creator user permission set.



 |
| FirstName | 

Type

string

Properties

Create, Filter, Group, Nillable, Sort, Update

Description

The lead’s first name up to 40 characters.



 |
| GeocodeAccuracy | 

Type

picklist

Properties

Create, Filter, Group, Nillable, Restricted picklist, Sort, Update

Description

Accuracy level of the geocode for the address. For details on geolocation compound fields, see [Compound Field Considerations and Limitations](https://developer.salesforce.com/docs/atlas.en-us.object_reference.meta/object_reference/compound_fields_limitations.htm#compound_fields_limitations "Address and geolocation compound fields are convenient and result in more concise, clear code. Here are some things to consider when using them in your apps.").



 |
| GenderIdentity | 

Type

picklist

Properties

Create, Filter, Group, Nillable, Restricted picklist, Sort, Update

Description

The lead’s internal experience of their gender, which may or may not correspond to their designated sex at birth.



 |
| HasOptedOutOfEmail | 

Type

boolean

Properties

Create, Defaulted on create, Filter, Update

Description

Indicates whether the lead doesn’t want to receive email from Salesforce (true) or does (false). Label is **Email Opt Out**.



 |
| HasOptedOutOfFax | 

Type

boolean

Properties

Create, Defaulted on create, Filter, Group, Sort, Update

Description

Indicates whether the lead doesn’t want to receive faxes from Salesforce (true) or does (false). Label is **FaxOpt Out**.



 |
| IndividualId | 

Type

reference

Properties

Create, Filter, Group, Nillable, Sort, Update

Description

ID of the data privacy record associated with this lead. This field is available if you enabled Data Protection and Privacy in Setup.

Relationship Name

Individual

Relationship Type

Lookup

Refers To

Individual



 |
| Industry | 

Type

picklist

Properties

Create, Filter, Group, Nillable, Sort, Update

Description

Industry in which the lead works.



 |
| IsConverted | 

Type

boolean

Properties

Create, Defaulted on create, Filter, Group, Sort

Description

Indicates whether the lead has been converted (true) or not (false). Label is **Converted**.



 |
| IsDeleted | 

Type

boolean

Properties

Defaulted on create, Filter

Description

Indicates whether the object has been moved to the Recycle Bin (true) or not (false). Label is **Deleted**.



 |
| IsPriorityRecord | 

Type

boolean

Properties

Defaulted on create, Group

Description

Shows whether the user has marked the lead as important (True) or not (False). The default value is false. Available in API version 59.0 and later.



 |
| IsUnreadByOwner | 

Type

boolean

Properties

Create, Defaulted on create, Filter, Group, Sort, Update

Description

If true, lead has been assigned, but not yet viewed. See Unread Leads for more information. Label is **Unread By Owner**.



 |
| Jigsaw | 

Type

string

Properties

Create, Filter, Group, Nillable, Sort, Update

Description

References the ID of a contact in Data.com. If a lead has a value in this field, it means that a contact was imported as a lead from Data.com. If the contact (converted to a lead) wasn’t imported from Data.com, the field value is null. Maximum size is 20 characters. Available in API version 22.0 and later. Label is **Data.com Key**.

![Important](https://developer.salesforce.com/docs/atlas.en-us.object_reference.meta/object_reference/images/icon_note_important.png)

#### Important

The Jigsaw field is exposed in the API to support troubleshooting for import errors and reimporting of corrected data. Don’t modify the value in the Jigsaw field.















 |
| JigsawContactId | 

Type

string

Properties

Filter, Group, Nillable, Sort

Description

The ID of the contact in reference to Jigsaw.

![Important](https://developer.salesforce.com/docs/atlas.en-us.object_reference.meta/object_reference/images/icon_note_important.png)

#### Important

The Jigsaw field is exposed in the API to support troubleshooting for import errors and reimporting of corrected data. Don’t modify the value in the Jigsaw field.















 |
| LastActivityDate | 

Type

date

Properties

Filter, Group, Nillable, Sort

Description

Value is the most recent of either:

- Due date of the most recent event logged against the record.
- Due date of the most recently closed task associated with the record.





 |
| LastName | 

Type

string

Properties

Create, Filter, Group, Sort, Update

Description

Required. Last name of the lead up to 80 characters.



 |
| LastReferencedDate | 

Type

dateTime

Properties

Filter, Nillable, Sort

Description

The timestamp when the current user last accessed this record indirectly, for example, through a list view or related record.



 |
| LastViewedDate | 

Type

datetime

Properties

Filter, Nillable, Sort

Description

The timestamp when the current user last viewed this record or list view. If this value is null, the user might have only accessed this record or list view (LastReferencedDate) but not viewed it.



 |
| Latitude | 

Type

double

Properties

Create, Filter, Nillable, Sort, Update

Description

Used with Longitude to specify the precise geolocation of an address. Acceptable values are numbers between –90 and 90 up to 15 decimal places. For details on geolocation compound fields, see [Compound Field Considerations and Limitations](https://developer.salesforce.com/docs/atlas.en-us.object_reference.meta/object_reference/compound_fields_limitations.htm#compound_fields_limitations "Address and geolocation compound fields are convenient and result in more concise, clear code. Here are some things to consider when using them in your apps.")



 |
| LeadSource | 

Type

picklist

Properties

Create, Filter, Group, Nillable, Sort, Update

Description

The origin or source of the lead.



 |
| Longitude | 

Type

double

Properties

Create, Filter, Nillable, Sort, Update

Description

Used with Latitude to specify the precise geolocation of an address. Acceptable values are numbers between –180 and 180 up to 15 decimal places. For details on geolocation compound fields, see [Compound Field Considerations and Limitations](https://developer.salesforce.com/docs/atlas.en-us.object_reference.meta/object_reference/compound_fields_limitations.htm#compound_fields_limitations "Address and geolocation compound fields are convenient and result in more concise, clear code. Here are some things to consider when using them in your apps.").



 |
| MasterRecordId | 

Type

reference

Properties

Filter, Group, Nillable, Sort

Description

If this record was deleted as the result of a merge, this field contains the ID of the record that was kept. If this record was deleted for any other reason, or hasn’t been deleted, the value is null.

When using Apex triggers to determine which record was deleted in a merge event, this field’s value is the ID of the record that remains in Trigger.old. In Trigger.new, the value is null.

This is a relationship field.

Relationship Name

MasterRecord

Relationship Type

Lookup

Refers To

Lead



 |
| MiddleName | 

Type

string

Properties

Create, Filter, Group, Nillable, Sort, Update

Description

The lead’s middle name. Maximum size is 40 characters.



 |
| MobilePhone | 

Type

phone

Properties

Create, Filter, Group, Nillable, Sort, Update

Description

The lead’s mobile phone number.



 |
| Name | 

Type

string

Properties

Filter, Group, Sort

Description

Concatenation of FirstName, MiddleName, LastName, and Suffix up to 203 characters, including whitespaces.



 |
| NumberOfEmployees | 

Type

int

Properties

Create, Filter, Group, Nillable, Sort, Update

Description

Number of employees at the lead’s company. Label is **Employees**.



 |
| OwnerId | 

Type

reference

Properties

Create, Defaulted on create, Filter, Group, Sort, Update

Description

ID of the lead’s owner.

This is a polymorphic relationship field.

Relationship Name

Owner

Relationship Type

Lookup

Refers To

Group, User



 |
| PartnerAccountId | 

Type

reference

Properties

Filter, Group, Nillable, Sort

Description

ID of the partner account for the partner user that owns this lead. Available if Partner Relationship Management is enabled or if digital experiences is enabled and you have partner portal licenses.

In API version 16.0 and later, the Partner Account field is set to the appropriate account for the partner user that owns the lead. If the owner of the lead isn’t a partner user, this field has no value.





 |
| Phone | 

Type

phone

Properties

Create, Filter, Group, Nillable, Sort, Update

Description

The lead’s phone number.



 |
| PhotoUrl | 

Type

url

Properties

Filter, Group, Nillable, Sort

Description

Path to be combined with the URL of a Salesforce instance (_Example:_ https://yourInstance.salesforce.com/) to generate a URL to request the social network profile image associated with the lead. Generated URL returns an HTTP redirect (code 302) to the social network profile image for the lead.





 |
| PostalCode | 

Type

string

Properties

Create, Filter, Group, Nillable, Sort, Update

Description

Postal code for the address of the lead. Label is **Zip/Postal Code**.



 |
| Pronouns | 

Type

picklist

Properties

Create, Filter, Group, Nillable, Restricted picklist, Sort, Update

Description

The lead’s personal pronouns, reflecting their gender identity. Others can use these pronouns to refer to the lead in the third person. The entry is selected from a picklist of available values, which the administrator sets. Maximum 40 characters.

Possible values are:

- He/Him
- He/They
- Not Listed
- She/Her
- She/They
- They/Them





 |
| Rating | 

Type

picklist

Properties

Create, Filter, Group, Nillable, Sort, Update

Description

Rating of the lead.



 |
| RecordTypeId | 

Type

reference

Properties

Create, Filter, Nillable, Update

Description

ID of the record type assigned to this object.



 |
| Salutation | 

Type

picklist

Properties

Create, Filter, Group, Nillable, Sort, Update

Description

Salutation for the lead.



 |
| ScheduledResumeDateTime | 

Type

dateTime

Properties

Filter, Nillable, Sort

Description

The date and time when the action cadence tracker is going to resume after it’s paused or on a wait step. This field is available in API version 54.0 and later when the Sales Engagement license is enabled. To see this field, the user also needs the Sales Engagement User or Sales Engagement Quick Cadence Creator user permission set.



 |
| ScoreIntelligenceId | 

Type

reference

Properties

Filter, Group, Nillable, Sort

Description

The ID of the intelligent field record that contains lead score.



 |
| State | 

Type

string

Properties

Create, Filter, Group, Nillable, Sort, Update

Description

State for the address of the lead.



 |
| StateCode | 

Type

picklist

Properties

Create, Filter, Group, Nillable, Sort, Update

Description

The ISO state code for the lead’s address.



 |
| Status | 

Type

picklist

Properties

Create, Defaulted on create, Filter, Group, Sort, Update

Description

Status code for this converted lead. Status codes are defined in Status and represented in the API by the LeadStatus object.



 |
| Street | 

Type

textarea

Properties

Create, Filter, Group, Nillable, Sort, Update

Description

Street number and name for the address of the lead.



 |
| Suffix | 

Type

string

Properties

Create, Filter, Group, Nillable, Sort, Update

Description

The lead’s name suffix. Maximum size is 40 characters.



 |
| Title | 

Type

string

Properties

Create, Filter, Group, Nillable, Sort, Update

Description

Title for the lead, such as CFO or CEO. The maximum size is 128 characters. When converting a lead to a person account, the conversion fails if the lead Title field contains more than 80 characters.



 |
| Website | 

Type

url

Properties

Create, Filter, Group, Nillable, Sort, Update

Description

Website for the lead.



 |

![Note](https://developer.salesforce.com/docs/atlas.en-us.object_reference.meta/object_reference/images/icon_note.png)

#### Note

When importing lead data, users need the Set Audit Fields upon Record Creation permission to assign values to audit fields such as CreatedDate. Audit fields are automatically updated during API operations unless you set these fields yourself.

## Converted Leads

Leads have a special state to indicate that they’ve been converted into an account, a contact, and an opportunity. Your client application can convert leads via the convertLead() call. Users can also convert leads in Salesforce. After a lead has been converted, it’s read only. However, you can query converted lead records. Only users with the View and Edit Converted Leads permission can update converted lead records.

Leads have several fields that indicate their converted status. These special fields are set when converting the lead in the user interface.

- ConvertedAccountId
- ConvertedContactId
- ConvertedDate
- ConvertedOpportunityId
- IsConverted
- Status

## Unread Leads

Leads have a special state to indicate that they haven’t been viewed or edited by the lead owner. In Salesforce, it’s helpful for users to know which leads have been assigned to them but that they haven’t touched yet. IsUnreadByOwner is true if the lead owner hasn’t yet viewed or edited the lead, and false if the lead owner has viewed or edited the lead at least one time.

## Lead Status Picklist

Each Status value corresponds to either a converted or unconverted status in the lead status picklist, as defined in the user interface. To obtain the lead status values in the picklist, a client application can query LeadStatus.

You can't convert a lead via the API by changing Status to one of the converted lead status values. When you convert qualified leads into an account, contact, and opportunity, you can select one of the converted status types for the lead. Leads with a converted status type are no longer available in the Leads tab, although you can include them in reports.

## Usage

If lead data is imported and you need to set the value for an audit field, such as CreatedDate, contact Salesforce Support. Audit fields are automatically updated during API operations unless you request to set these fields yourself.

To update a lead or to convert one with convertLead(), log in to your client application with the Edit permission on leads.

When you create, update, or upsert a lead, your client application can have the lead assigned to multiple user records based on assignment rules that have been configured in Salesforce.

To use this feature, your client application needs to set either of these options (but not both) in the AssignmentRuleHeader used in create or update:

<table class="featureTable sort_table" summary="">



          <thead class="thead sorted" align="left">
            <tr>
              <th class="featureTableHeader  " id="d1100926e3840">Field</th>

              <th class="featureTableHeader  " id="d1100926e3843">Field Type</th>

              <th class="featureTableHeader  " id="d1100926e3846">Details</th>

            </tr>

          </thead>

          <tbody class="tbody">
            <tr>
              <td class="entry" headers="d1100926e3840" data-title="Field"><span class="keyword parmname">assignmentRuleId</span></td>

              <td class="entry" headers="d1100926e3843" data-title="Field Type">reference </td>

              <td class="entry" headers="d1100926e3846" data-title="Details">ID of the assignment rule to use. Can be an inactive assignment
                rule. If unspecified and <span class="keyword parmname">useDefaultRule</span> is
                <samp class="codeph nolang">true</samp>, then the default
                assignment rule is used. <p class="p">To find the ID for a given assignment
                  rule, query the AssignmentRule object (specifying <samp class="codeph nolang">RuleType="leadAssignment"</samp>),
                  iterate through the returned AssignmentRule records, find the
                  one you want to use, retrieve its ID, and then specify its ID in
                  this field in the AssignmentRuleHeader.</p>
              </td>

            </tr>

            <tr>
              <td class="entry" headers="d1100926e3840" data-title="Field">
                <span class="keyword parmname" id="i1453138"><a name="i1453138"><!-- --></a>useDefaultRule</span>
              </td>

              <td class="entry" headers="d1100926e3843" data-title="Field Type">boolean </td>

              <td class="entry" headers="d1100926e3846" data-title="Details">Specifies whether to use the default rule for rule-based
                assignment (<samp class="codeph nolang">true</samp>) or not
                (<samp class="codeph nolang">false</samp>). Default rules are
                assigned in the user interface.</td>

            </tr>

          </tbody>

        </table>

## Java Sample

The following Java sample shows how to automatically assign a newly created lead.

package wsc;

import com.sforce.soap.enterprise.Connector;
import com.sforce.soap.enterprise.EnterpriseConnection;
import com.sforce.ws.ConnectionException;
import com.sforce.ws.ConnectorConfig;
import com.sforce.soap.enterprise.sobject.Lead;
import com.sforce.soap.enterprise.QueryResult; 
import com.sforce.soap.enterprise.SaveResult; 
import com.sforce.soap.enterprise.sobject.SObject;

public class LeadAssignment {

    static final String USERNAME = "REPLACE USER NAME";
    static final String PASSWORD = "REPLACE PASSWORD";
    static EnterpriseConnection connection;
	
    static LeadAssignment \_leadAssignment;
	
    // Main
    public static void main(String\[\] args)
    { 
        // Establish connection and login
        ConnectorConfig config = new ConnectorConfig();
        config.setUsername(USERNAME);
        config.setPassword(PASSWORD);
        try {
            connection = Connector.newConnection(config);
            System.out.println("Logged in, endpoint: " + config.getAuthEndpoint());
        } catch (ConnectionException e1) {
            e1.printStackTrace();
        } 

        // Create lead 
        \_leadAssignment = new LeadAssignment(); 
        try { 
            \_leadAssignment.CreateLead(); 
        } catch (Exception e) { 
            e.printStackTrace(); 
        } 
        
        // Logout
        try {
            connection.logout();
            System.out.println("Logged out");
        } catch (ConnectionException ce) {
            ce.printStackTrace();
        }	            
    }
    
    public void CreateLead() throws ConnectionException
    {    	
        // Create a new Lead and assign various properties 
        Lead lead = new Lead(); 
     
        lead.setFirstName("Joe"); 
        lead.setLastName("Smith"); 
        lead.setCompany("ABC Corporation"); 
        lead.setLeadSource("API"); 
        // The lead assignment rule will assign any new leads that 
        // have "API" as the LeadSource to a particular user 
        
        // In this sample we will look for a particular rule and if found 
        // use the id for the lead assignment. If it is not found we will 
        // instruct the call to use the current default rule. You can't use 
        // both of these values together. 
        QueryResult qr = connection.query("SELECT Id FROM AssignmentRule WHERE Name = " +
                             "'Mass Mail Campaign' AND SobjectType = 'Lead'"); 
        if (qr.getSize() == 0) {
            connection.setAssignmentRuleHeader(null, true);
        } else {
            connection.setAssignmentRuleHeader(qr.getRecords()\[0\].getId(), false);
        }         
			 
        // Every operation that results in a new or updated lead will 
        // use the specified rule until the header is removed from the 
        // connection. 
        SaveResult\[\] sr = connection.create(new SObject\[\] {lead}); 
        for (int i=0;i<sr.length;i++) { 
            if (sr\[i\].isSuccess()) {
                System.out.println("Successfully created lead with id of: " + 
                                   sr\[i\].getId() + ".");
            } else {
                System.out.println("Error creating lead: " + 
                                   sr\[i\].getErrors()\[0\].getMessage());
            }
        } 		

        // This call effectively removes the header, the next lead will 
        // be assigned to the default lead owner. 
        connection.clearAssignmentRuleHeader();
    }    
}

## C# Sample

The following C# sample shows how to automatically assign a newly created lead.

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.ServiceModel;
using LeadSample.sforce;

namespace LeadSample
{
    class LeadAssignment
    {
        private static SoapClient client;
        private static SoapClient apiClient;
        private static SessionHeader header;
        private static LoginResult loginResult;
        private static readonly string Username = "REPLACE USERNAME";
        private static readonly string Password = "REPLACE PASSWORD AND SECURITY TOKEN";

        // Create the proxy binding and login
        private LeadAssignment()
        {
            client = new SoapClient();

            try
            {
                loginResult = client.login(null, Username, Password);
            }
            catch (Exception e)
            {
                Console.WriteLine("Unexpected login error: " + e.Message);
                Console.WriteLine(e.StackTrace);
                return;
            }
            // Access API endpoint and create new client
            header = new SessionHeader();
            header.sessionId = loginResult.sessionId;
            apiClient = new SoapClient("Soap", loginResult.serverUrl);
        }

        \[STAThread\]
        static void Main(string\[\] args)
        {
            LeadAssignment leadAssignment = new LeadAssignment();
            try
            {
                leadAssignment.CreateLead();
            }
            catch (Exception e)
            {
                Console.WriteLine(e.Message);
                Console.WriteLine(e.StackTrace);
                Console.WriteLine(e.InnerException);
            }
            // logout
            client.logout(header);
        }

        public void CreateLead()
        {
            // Create a new Lead and assign various properties
            Lead lead = new Lead();

            lead.FirstName = "John";
            lead.LastName = "Brown";
            lead.Company = "ABC Corporation";
            lead.LeadSource = "Advertisement";
            // Setting the lead source for a pre-existing lead assignment rule. This 
            // rule was created outside of this sample and will assign any new leads
            // that have "Advertisement" as the LeadSource to a particular user.

            // Create the assignment rule header and add it to the proxy binding
            AssignmentRuleHeader arh = new AssignmentRuleHeader();

            // In this sample we will look for a particular rule and if found
            // use the id for the lead assignment. If it is not found we will
            // instruct the call to use the current default rule. Both these
            // values can't be used together.
            QueryResult qr = null;
            string query = "SELECT Id FROM AssignmentRule WHERE Name = " +
                "'Mass Mail Campaign' AND SobjectType = 'Lead'";
            try
            {
                LimitInfo\[\] limitArray = apiClient.query(
                    header, // sessionheader
                    null,   // queryoptions
                    null,   // mruheader
                    null,   // packageversionheader
                    query,  // SOQL query
                    out qr);
            }
            catch (Exception e)
            {
                Console.WriteLine("Unexpected query error: " + e.Message);
                Console.WriteLine(e.StackTrace);
            }
            if (qr.size == 0)
            {
                arh.useDefaultRule = true;
            }
            else
            {
                arh.assignmentRuleId = qr.records\[0\].Id;
            }

            // Create the lead using our Assignment Rule header
            LimitInfo\[\] li;
            SaveResult\[\] sr;
            apiClient.create(
                header, // sessionheader
                arh,    // assignmentruleheader
                null,   // mruheader
                null,   // allowfieldtrunctionheader
                null,   // disablefeedtrackingheader
                null,   // streamingenabledheader
                null,   // allornoneheader
                null,   // duplicateruleheader
                null,   // localeoptions
                null,   // debuggingheader
                null,   // packageversionheader
                null,   // emailheader
                new sObject\[\] { lead },
                out li,
                out sr);
            foreach (SaveResult s in sr)
            {
                if (s.success)
                {
                    Console.WriteLine("Successfully created Lead with ID: {0}", s.id);
                }
                else
                {
                    Console.WriteLine("Error creating Lead: {0}", s.errors\[0\].message);
                }
            }
        }
    }
}

## Associated Objects

This object has these associated objects. If the API version isn’t specified, they’re available in the same API versions as this object. Otherwise, they’re available in the specified API version and later.

[LeadChangeEvent](https://developer.salesforce.com/docs/atlas.en-us.264.0.object_reference.meta/object_reference/sforce_api_associated_objects_change_event.htm) (API version 44.0)

Change events are available for the object.

[LeadFeed](https://developer.salesforce.com/docs/atlas.en-us.264.0.object_reference.meta/object_reference/sforce_api_associated_objects_feed.htm) (API version 18.0)

Feed tracking is available for the object.

[LeadHistory](https://developer.salesforce.com/docs/atlas.en-us.264.0.object_reference.meta/object_reference/sforce_api_associated_objects_history.htm)

History is available for tracked fields of the object.

[LeadOwnerSharingRule](https://developer.salesforce.com/docs/atlas.en-us.object_reference.meta/object_reference/sforce_api_objects_leadownersharingrule.htm "Represents the rules for sharing a lead with users other than the owner.")

Sharing rules are available for the object.

[LeadShare](https://developer.salesforce.com/docs/atlas.en-us.object_reference.meta/object_reference/sforce_api_objects_leadshare.htm "Represents a sharing entry on a Lead.")

Sharing is available for the object.

#### See Also

- [LeadOwnerSharingRule](https://developer.salesforce.com/docs/atlas.en-us.object_reference.meta/object_reference/sforce_api_objects_leadownersharingrule.htm "Represents the rules for sharing a lead with users other than the owner.")
- [LeadShare](https://developer.salesforce.com/docs/atlas.en-us.object_reference.meta/object_reference/sforce_api_objects_leadshare.htm "Represents a sharing entry on a Lead.")
- [LeadStatus](https://developer.salesforce.com/docs/atlas.en-us.object_reference.meta/object_reference/sforce_api_objects_leadstatus.htm "Represents the status of a Lead record, such as Open, Qualified, or Converted.")
- [PartnerNetworkConnection](https://developer.salesforce.com/docs/atlas.en-us.object_reference.meta/object_reference/sforce_api_objects_partnernetworkconnection.htm "Represents a Salesforce to Salesforce connection between Salesforce organizations.")