beginner
Fundamentals

Salesforce APIs Explained: Metadata API vs REST API vs DML Operations

Learn the key differences between Metadata API, REST API, and DML operations in Salesforce. Understand when to use each approach for data vs metadata operations.

14 min read
Warren Walters
apex
metadata-api
rest-api
dml
salesforce-development
beginner

TL;DR

Salesforce offers three main ways to interact with your org: DML operations for working with data records, REST API for external data operations, and Metadata API for creating or modifying the structure of your org (like custom objects and fields). Understanding the difference between data and metadata is key to choosing the right approach.

Introduction

One of the most common questions new Salesforce developers ask is: "Why can't I create a custom field using regular Apex code?" The answer lies in understanding the fundamental difference between data and metadata in Salesforce.

Think of it this way: metadata is the blueprint of your house (walls, rooms, doors), while data is the furniture inside. You wouldn't rearrange your furniture the same way you'd knock down walls. Similarly, Salesforce uses different tools for different jobs.

In this guide, we'll explore three essential approaches for working with Salesforce:

  • DML Operations - For working with records (your data)
  • REST API - For external applications to access data
  • Metadata API - For modifying your org's structure

By the end, you'll know exactly which tool to reach for in any situation.

Understanding Data vs Metadata

Before diving into the APIs, let's clarify what data and metadata actually mean in Salesforce.

What is Data?

Data refers to the actual records stored in your Salesforce org. These are the things that change frequently:

  • Contact records (John Smith, Jane Doe)
  • Account records (Acme Corp, Global Industries)
  • Opportunity records (Q1 Deal, Enterprise Sale)
  • Custom object records

Think of data as the information your business needs to operate day-to-day. It's dynamic and constantly changing.

What is Metadata?

Metadata refers to the structure and configuration of your Salesforce org. This includes:

  • Custom objects (defining what an object is)
  • Custom fields (adding new fields to objects)
  • Page layouts (how fields are arranged)
  • Validation rules (business logic)
  • Workflows and process automation

Metadata is like the framework of your org. It defines what's possible but doesn't contain the actual business data.

Why Does This Matter?

Salesforce treats data and metadata operations completely differently for important reasons:

  1. Safety - Changing metadata affects your entire org structure
  2. Performance - Metadata changes require validation and can't be done in bulk
  3. Governance - Metadata changes need careful tracking and deployment
  4. Impact - A metadata change affects all users instantly

Now let's look at each approach for working with Salesforce.

DML Operations: Working with Data Records

DML (Data Manipulation Language) operations are your everyday tools for working with records in Apex. They're built directly into the Apex language and are the most common way to interact with data.

What Are DML Operations?

DML operations allow you to create, read, update, and delete records in your Salesforce org. The main DML statements are:

  • insert - Create new records
  • update - Modify existing records
  • delete - Remove records
  • undelete - Restore deleted records
  • upsert - Insert or update based on whether the record exists
  • merge - Combine duplicate records

When to Use DML Operations

Use DML operations when you need to:

  • Create new records from Apex code
  • Update existing record data
  • Delete or archive old records
  • Work with data inside triggers or batch jobs
  • Perform bulk operations on up to 10,000 records per transaction

DML Code Examples

Here's how to create a new Account record:

// Create a single account
Account newAccount = new Account(
    Name = 'Acme Corporation',
    Industry = 'Technology',
    Phone = '(555) 123-4567'
);
insert newAccount;
 
System.debug('New Account ID: ' + newAccount.Id);

Updating existing records:

// Query an existing account
Account acc = [SELECT Id, Name, Phone FROM Account WHERE Name = 'Acme Corporation' LIMIT 1];
 
// Update the phone number
acc.Phone = '(555) 987-6543';
update acc;
 
System.debug('Account updated successfully');

Bulk DML operations (recommended approach):

// Create multiple contacts at once
List<Contact> newContacts = new List<Contact>();
 
for (Integer i = 0; i < 5; i++) {
    newContacts.add(new Contact(
        FirstName = 'Contact',
        LastName = 'Number ' + i,
        Email = 'contact' + i + '@example.com'
    ));
}
 
// Insert all contacts in one DML statement
insert newContacts;
 
System.debug('Inserted ' + newContacts.size() + ' contacts');

DML Governor Limits

Salesforce enforces limits to ensure shared resources aren't overused:

  • 150 DML statements per transaction (synchronous)
  • 10,000 records total can be processed per transaction
  • Always process records in bulk, not one at a time

What You CAN'T Do with DML

Here's where developers get confused. You cannot use DML to:

  • Create custom objects
  • Add custom fields to objects
  • Modify page layouts
  • Create validation rules
  • Change org structure

Trying this code will fail:

// THIS WILL NOT WORK!
CustomObject__c newObject = new CustomObject__c();
insert newObject; // Error: sObject type 'CustomObject__c' is not supported

REST API: External Data Operations

The REST API allows external applications to interact with your Salesforce data using standard HTTP methods. It's designed for integration scenarios where systems outside Salesforce need to access your data.

What is REST API?

REST (Representational State Transfer) API is a web service that uses HTTP requests to perform operations on Salesforce data. It uses standard HTTP methods:

  • GET - Retrieve records
  • POST - Create new records
  • PATCH - Update existing records
  • DELETE - Remove records

When to Use REST API

Use REST API when you need to:

  • Integrate Salesforce with external applications
  • Build mobile apps that connect to Salesforce
  • Allow third-party systems to read/write Salesforce data
  • Create web services that work with Salesforce
  • Access Salesforce from non-Apex programming languages

REST API vs DML Operations

While both work with data, they serve different purposes:

AspectREST APIDML Operations
Where it runsExternal to SalesforceInside Salesforce (Apex)
AuthenticationOAuth/Session ID requiredAutomatic (running as user)
LanguagesAny (JavaScript, Python, Java, etc.)Apex only
Use caseExternal integrationsInternal business logic
FormatJSON or XMLApex objects

REST API Code Example

Here's how to create a record using REST API from JavaScript:

// Create a new Contact via REST API
const createContact = async () => {
    const endpoint = 'https://yourinstance.salesforce.com/services/data/v65.0/sobjects/Contact/';
 
    const contactData = {
        FirstName: 'John',
        LastName: 'Smith',
        Email: 'john.smith@example.com'
    };
 
    const response = await fetch(endpoint, {
        method: 'POST',
        headers: {
            'Authorization': 'Bearer YOUR_ACCESS_TOKEN',
            'Content-Type': 'application/json'
        },
        body: JSON.stringify(contactData)
    });
 
    const result = await response.json();
    console.log('New Contact ID:', result.id);
};

From Python:

import requests
 
# Update an Account via REST API
def update_account(account_id, new_phone):
    endpoint = f'https://yourinstance.salesforce.com/services/data/v65.0/sobjects/Account/{account_id}'
 
    headers = {
        'Authorization': 'Bearer YOUR_ACCESS_TOKEN',
        'Content-Type': 'application/json'
    }
 
    data = {
        'Phone': new_phone
    }
 
    response = requests.patch(endpoint, json=data, headers=headers)
 
    if response.status_code == 204:
        print('Account updated successfully')
    else:
        print('Error:', response.json())

REST API Capabilities

REST API can do much more than basic CRUD operations:

  • Query records using SOQL
  • Execute SOSL searches
  • Work with object metadata (read-only)
  • Access org limits and resources
  • Perform composite operations (multiple actions in one call)

Important Note About Metadata

While REST API can read metadata (like field definitions), it cannot create or modify metadata. For that, you need the Metadata API.

Metadata API: Modifying Org Structure

The Metadata API is specifically designed to create, modify, and manage the structure of your Salesforce org. This is the tool you need when working with custom objects, fields, and other metadata components.

What is Metadata API?

Metadata API allows you to programmatically create and modify the building blocks of your Salesforce org. It's commonly used for:

  • Deploying changes between orgs (dev to production)
  • Automating org setup
  • Creating configuration packages
  • Managing large-scale metadata changes

When to Use Metadata API

Use Metadata API when you need to:

  • Create custom objects programmatically
  • Add custom fields to objects
  • Deploy metadata between sandboxes and production
  • Automate org configuration
  • Build package installers
  • Manage page layouts, workflows, and validation rules

Key Differences from DML and REST API

FeatureMetadata APIDML/REST API
PurposeModify org structureWork with data records
What it changesObjects, fields, layoutsAccount, Contact, etc. records
FrequencyInfrequent, during deploymentsConstant, day-to-day operations
SpeedAsynchronous (slower)Synchronous (fast)
ImpactAffects all usersAffects specific records

Metadata API Access Methods

There are several ways to work with Metadata API:

1. From Apex (Limited Support)

Salesforce provides limited Metadata API access from Apex for custom metadata types:

// Create a Custom Metadata record from Apex
Metadata.CustomMetadata customMetadata = new Metadata.CustomMetadata();
customMetadata.fullName = 'MyCustomMetadataType.MyRecord';
customMetadata.label = 'My Record';
 
// Add a field value
Metadata.CustomMetadataValue fieldValue = new Metadata.CustomMetadataValue();
fieldValue.field = 'MyField__c';
fieldValue.value = 'Some Value';
customMetadata.values.add(fieldValue);
 
// Deploy the metadata
Metadata.DeployContainer container = new Metadata.DeployContainer();
container.addMetadata(customMetadata);
 
// Enqueue deployment with callback
Id deployId = Metadata.Operations.enqueueDeployment(container, null);
System.debug('Deployment queued: ' + deployId);

Important: This only works for Custom Metadata Types, not standard custom objects or fields.

2. Via Tooling API (HTTP Callout)

For creating custom objects and fields, you need to use the Tooling API with HTTP callouts:

// Create a custom field using Tooling API
public class CustomFieldCreator {
 
    public static void createCustomField() {
        // Build the custom field definition
        String fieldDefinition = JSON.serialize(new Map<String, Object>{
            'FullName' => 'Account.CustomField__c',
            'Metadata' => new Map<String, Object>{
                'type' => 'Text',
                'label' => 'Custom Field',
                'length' => 100
            }
        });
 
        // Make HTTP callout to Tooling API
        HttpRequest req = new HttpRequest();
        req.setEndpoint('callout:SalesforceOrg/services/data/v65.0/tooling/sobjects/CustomField');
        req.setMethod('POST');
        req.setHeader('Content-Type', 'application/json');
        req.setBody(fieldDefinition);
 
        Http http = new Http();
        HttpResponse res = http.send(req);
 
        if (res.getStatusCode() == 201) {
            System.debug('Custom field created successfully');
        } else {
            System.debug('Error: ' + res.getBody());
        }
    }
}

Note: This requires setting up a Named Credential for authentication.

3. Using Salesforce CLI or Deployment Tools

The most common way to work with Metadata API is through deployment tools:

# Using Salesforce CLI to deploy metadata
sf project deploy start --source-dir force-app/main/default
 
# Retrieve metadata from an org
sf project retrieve start --manifest manifest/package.xml

Metadata API Use Cases

Here are real-world scenarios where Metadata API is essential:

Scenario 1: Automated Org Setup You're setting up 50 sandbox environments and need to create the same custom objects and fields in each.

Solution: Use Metadata API to deploy a package containing all custom objects and fields to each sandbox automatically.

Scenario 2: Multi-Org Configuration Your company manages multiple Salesforce orgs for different regions, and each needs the same customizations.

Solution: Create a metadata package and deploy it to all orgs using Metadata API, ensuring consistency.

Scenario 3: Dynamic Field Creation You're building an app that needs to create custom fields based on user input (rare, but possible).

Solution: Use Tooling API (part of Metadata API) to create fields dynamically, though this is typically not recommended for most use cases.

Comparison Table: When to Use Each Approach

Here's a quick reference guide to help you choose the right tool:

TaskUse ThisWhy
Create 100 Contact recordsDML OperationsFast, efficient, built into Apex
Update Account data from external appREST APIExternal system integration
Add custom field to Account objectMetadata APIModifying org structure
Delete old Opportunity recordsDML OperationsWorking with data records
Query Salesforce data from mobile appREST APIExternal application access
Deploy custom object to productionMetadata APIDeploying metadata changes
Trigger to update related recordsDML OperationsInternal business logic
Create validation ruleMetadata APIModifying org configuration
Third-party system reads ContactsREST APIExternal integration
Batch job processes 10,000 recordsDML OperationsBulk data processing

Best Practices

For DML Operations

  1. Always bulkify your code - Process records in lists, not one at a time
  2. Handle exceptions - Use try-catch blocks to manage errors gracefully
  3. Check governor limits - Be aware of the 150 DML statement limit
  4. Use Database methods - Consider Database.insert() with partial success options
  5. Query efficiently - Avoid SOQL queries inside loops

Example of bulkified code:

// GOOD: Bulkified approach
List<Contact> contactsToUpdate = [SELECT Id, Phone FROM Contact WHERE Phone = null];
for (Contact con : contactsToUpdate) {
    con.Phone = '(000) 000-0000';
}
update contactsToUpdate; // Single DML statement
 
// BAD: Non-bulkified approach
for (Contact con : [SELECT Id FROM Contact WHERE Phone = null]) {
    con.Phone = '(000) 000-0000';
    update con; // DML inside loop - hits limits quickly!
}

For REST API

  1. Implement proper authentication - Use OAuth 2.0 for security
  2. Handle rate limits - Respect API call limits per 24 hours
  3. Use composite API - Combine multiple operations to reduce API calls
  4. Cache access tokens - Don't request new tokens for every call
  5. Implement retry logic - Handle temporary failures gracefully

For Metadata API

  1. Test in sandbox first - Never deploy metadata directly to production
  2. Use version control - Track all metadata changes in Git
  3. Deploy during maintenance windows - Metadata changes can impact users
  4. Back up before major changes - Always have a way to roll back
  5. Document all changes - Keep clear records of what was modified and why

Common Mistakes to Avoid

Mistake 1: Trying to Create Custom Objects with DML

// THIS WILL NOT WORK!
CustomObject__c myObject = new CustomObject__c();
insert myObject;

Why it fails: Custom objects are metadata, not data. You can't create the object definition itself with DML.

Solution: Use Metadata API or Tooling API to create custom objects.

Mistake 2: Using DML Inside Loops

// BAD: DML inside loop
for (Account acc : accountList) {
    acc.Name = acc.Name + ' Updated';
    update acc; // This will hit governor limits!
}

Why it's bad: Each update counts as a separate DML statement. With 150 limit, you can only process 150 records.

Solution: Collect all records and perform one DML operation:

// GOOD: Bulkified approach
List<Account> accountsToUpdate = new List<Account>();
for (Account acc : accountList) {
    acc.Name = acc.Name + ' Updated';
    accountsToUpdate.add(acc);
}
update accountsToUpdate; // Single DML statement for all records

Mistake 3: Confusing REST API with Apex REST

REST API (external) is different from Apex REST classes (custom endpoints):

  • REST API: Salesforce-provided API to access your org externally
  • Apex REST: Custom API endpoints you build using Apex

Don't confuse the two when planning your integration architecture.

Mistake 4: Not Understanding Metadata Deployment Impact

Deploying metadata changes affects all users immediately. Always:

  • Test thoroughly in sandbox
  • Deploy during low-usage hours
  • Communicate changes to users
  • Have a rollback plan

Mistake 5: Ignoring Governor Limits

Each approach has its own limits:

  • DML: 150 statements, 10,000 records per transaction
  • REST API: 15,000 API calls per 24 hours (varies by license)
  • Metadata API: 50 MB max deploy size, 10,000 files per deploy

Plan your architecture around these constraints.

Real-World Decision Examples

Let's walk through some scenarios to see which approach to use:

Scenario 1: E-commerce Integration

Requirement: Your e-commerce website needs to create Contact records in Salesforce when customers place orders.

Decision: Use REST API

Why: The e-commerce system is external to Salesforce, so it needs REST API to create Contact records. The alternative (DML) only works inside Salesforce.

Scenario 2: Nightly Data Cleanup

Requirement: Delete all Opportunity records older than 5 years every night.

Decision: Use DML Operations in a Scheduled Batch Apex class

Why: This is an internal data operation running within Salesforce. DML is the natural choice for bulk record deletion.

Scenario 3: Multi-Org Deployment

Requirement: Deploy a custom object with 20 fields to 10 different Salesforce orgs.

Decision: Use Metadata API with Salesforce CLI

Why: Creating custom objects and fields requires Metadata API. Using CLI automates deployment across multiple orgs.

Scenario 4: Trigger After Record Creation

Requirement: When a new Account is created, automatically create three related Contact records.

Decision: Use DML Operations in an Apex trigger

Why: This is internal Salesforce logic that needs to work with data records. DML is designed for this.

Scenario 5: Mobile App Integration

Requirement: Your mobile app needs to display and update Salesforce records on the go.

Decision: Use REST API

Why: Mobile apps run outside Salesforce and need a standard HTTP-based interface. REST API is perfect for this.

Conclusion

Understanding the difference between data and metadata is fundamental to becoming a proficient Salesforce developer. Let's recap:

  • DML Operations are your go-to tool for working with records inside Salesforce using Apex
  • REST API enables external applications to interact with your Salesforce data
  • Metadata API allows you to modify the structure and configuration of your org

The key to mastering Salesforce development is knowing which tool to use for each situation. When in doubt, ask yourself:

  1. Am I working with data (records) or metadata (structure)?
  2. Is this operation happening inside Salesforce (Apex) or outside (external system)?
  3. Do I need to modify the org configuration or just the record data?

As you practice building Salesforce solutions, these distinctions will become second nature. Start with simple DML operations, experiment with REST API integrations, and gradually work your way up to metadata deployments.

Remember: every expert Salesforce developer started exactly where you are now. Keep practicing, make mistakes in your sandbox, and learn from each experience. You've got this!

Next Steps

Ready to put this knowledge into practice? Here are some suggestions:

  1. Practice DML operations - Create a simple Apex class that performs bulk insert/update operations
  2. Explore REST API - Try calling Salesforce REST API from Postman or a simple JavaScript app
  3. Learn deployment basics - Set up Salesforce CLI and practice deploying metadata between orgs
  4. Build a trigger - Create a trigger that uses DML to maintain related records
  5. Study governor limits - Understand the boundaries and how to work within them

The Lightning Challenge platform has hands-on exercises to help you master these concepts. Start with DML fundamentals and work your way up to more advanced scenarios.

Happy coding, and welcome to the world of Salesforce development!

WW

About Warren Walters

Salesforce MVP and transformative mentor with 8+ years in the Salesforce realm. Founder of Lightning Challenge, dedicated to nurturing the next generation of Salesforce talent through hands-on practice and real-world coding challenges.

Visit Profile →
Share:

Related Posts