Sub topic 13
Metadata API for deploying configuration
This chapter assumes you know how the REST API works, how to authenticate with OAuth 2.0, and how the SOAP API is structured. You should also know what custom objects, fields, and Apex classes are in Salesforce. The Metadata API builds on the SOAP API's WSDL-based model, so the earlier SOAP chapter helps here.
What the Metadata API is for
Salesforce separates data from metadata. Data is the records in your org, such as Accounts and Contacts. Metadata is the configuration that describes how the org behaves: custom objects, fields, page layouts, flows, permission sets, and Apex classes.
The Metadata API reads, creates, updates, and deletes that configuration. Its main job is moving configuration between orgs, for example from a sandbox to production. It does not touch record data. To change a record, use the REST API or Bulk API 2.0 instead.
Typical uses:
- Deploying a release from a sandbox to production.
- Retrieving an org's configuration to store in version control.
- Creating or changing configuration from a script or a build pipeline.
- Backing up configuration before a risky change.
Metadata components and package.xml
Every piece of configuration is a metadata component. Each component has a metadata type, such as CustomObject, ApexClass, Flow, or PermissionSet. A component is stored as a file, usually XML, and some types also have a companion source file. An Apex class, for example, is a .cls file plus a .cls-meta.xml file.
A manifest file named package.xml lists which components a retrieve or deploy covers. It names each type and then the members of that type. A * wildcard selects all members of a type, although a few types do not support it.
<?xml version="1.0" encoding="UTF-8"?>
<Package xmlns="http://soap.sforce.com/2006/04/metadata">
<types>
<members>Invoice__c</members>
<name>CustomObject</name>
</types>
<types>
<members>InvoiceTriggerHandler</members>
<name>ApexClass</name>
</types>
<version>60.0</version>
</Package>The version element sets the API version used to interpret the files. Keep it consistent with the version your tooling and org support.
How a deployment works
The Metadata API is a SOAP-style API, and its main calls are asynchronous. You do not get the result in the response to the call you send.
- You package the components and
package.xmlinto a ZIP file. - You call
deploy()with the ZIP file and receive anAsyncResultthat contains an ID. - You poll
checkDeployStatus()with that ID until the deployment finishes. - Salesforce reports success, or it reports failures per component.
Retrieval follows the same pattern. retrieve() starts the job, you poll checkRetrieveStatus(), and the result is a ZIP file that holds the components.
Newer API versions also offer a REST interface for deployment (/services/data/vXX.X/metadata/deployRequest). The Salesforce CLI uses these endpoints, so most developers never call them directly.
Deployment options
deploy() accepts DeployOptions that control how strict the deployment is.
| Option | Effect |
|---|---|
| `checkOnly` | Validates the deployment and runs tests, but saves nothing. |
| `rollbackOnError` | Rolls back the whole deployment if any component fails. It is required for production deployments, which are always all-or-nothing. |
| `testLevel` | Chooses which Apex tests run, for example `NoTestRun`, `RunSpecifiedTests`, `RunLocalTests`, or `RunAllTestsInOrg`. |
| `runTests` | Lists the test classes to run when `testLevel` is `RunSpecifiedTests`. |
| `singlePackage` | Indicates the ZIP file holds one package directory. |
| `ignoreWarnings` | Lets the deployment proceed when it produces warnings. |
Two behaviors matter in practice:
- Production deployments that include Apex run tests. Salesforce requires tests to run, and the code must meet the minimum coverage threshold (75% overall at the time of writing; check current documentation). Deployments of only non-code metadata do not need the same coverage.
- Sandbox deployments are more lenient. You can often skip tests, which makes the feedback loop faster.
A common release pattern is to run a checkOnly deployment first. After it passes, you can run a quick deploy of that validated deployment. Quick deploy reuses the test results from the validation, so the final deployment is much shorter. The validation result stays usable only for a limited window, so check the current retention period.
Using the Salesforce CLI
Most teams do not write SOAP envelopes by hand. The Salesforce CLI (sf) wraps the Metadata API and works with source format, a layout that splits large metadata types into many small files. Splitting makes version-control diffs readable. The CLI converts source format to the older metadata format when it talks to the API.
# Retrieve components listed in a manifest from the org
sf project retrieve start --manifest manifest/package.xml --target-org my-sandbox
# Validate a deployment without saving it, running local tests
sf project deploy validate --manifest manifest/package.xml \
--target-org my-prod --test-level RunLocalTests
# Deploy the validated job without running tests again
sf project deploy quick --job-id 0AfXXXXXXXXXXXXXXX --target-org my-prodReplace the job ID with the ID that the validate command prints. The CLI authenticates using an org alias that you set up earlier with sf org login web or a JWT-based login for CI systems.
Authentication and permissions
The Metadata API accepts the same OAuth 2.0 access tokens as the other APIs. A SOAP call passes the token as a session ID in a SessionHeader. The REST-style deploy endpoints use the usual Authorization: Bearer header.
The user behind the token needs the Modify Metadata Through Metadata API Functions permission, or the broader Modify All Data permission. For CI pipelines, use a dedicated integration user with only the permissions needed. Do not use an administrator's personal login.
Limits and constraints
- Size. A deployment ZIP file is limited in size (about 39 MB) and in file count (10,000 files). Large orgs split deployments into several smaller ones.
- Concurrency. Only a limited number of deployments can be queued at once, and a deployment locks configuration while it runs. Do not edit the same components in the org during a deploy.
- Time. Salesforce cancels deployments that run too long. Slow tests are the usual cause.
- Type coverage. Not every setting is available as a metadata type, and the supported types change with each release. Check the Metadata Coverage Report for the types in your API version.
- Not for data. Metadata deployment will not move records. Reference data, such as custom settings records, needs a separate data load.
Common errors
| Symptom | Likely cause | Fix |
|---|---|---|
| `Cannot find component` or missing dependency | A component references another that is not in the ZIP file or the target org. | Add the dependency to the manifest, or deploy it first. |
| Test coverage failure in production | Apex classes fall below the coverage threshold, or a test fails. | Run `RunLocalTests` in a sandbox first and fix failing tests. |
| Deployment succeeds in a sandbox, fails in production | The orgs differ in features, editions, or existing configuration. | Compare settings and enabled features. Use a full-copy sandbox for rehearsal. |
| `INVALID_SESSION_ID` | The token expired or belongs to a different org. | Refresh the token and confirm the instance URL. |
| Field deletion blocked | Other components still reference the field. | Remove the references first, then deploy the deletion with a `destructiveChanges.xml` file. |
Deleting components needs special handling. You add a destructiveChanges.xml file, which uses the same format as package.xml, to the ZIP file. The file lists the members to remove. A normal package.xml cannot delete anything.
Metadata API compared with other APIs
| Question | Metadata API | Tooling API | REST API |
|---|---|---|---|
| Works on | Configuration as whole components | Configuration as fine-grained objects | Record data |
| Style | Asynchronous, file-based | Synchronous, query and DML-like | Synchronous, JSON |
| Best for | Releases and migration | Developer tools, such as an IDE | Integrations |
The Tooling API, covered in the next chapter, is better when you need to inspect or change one small piece of configuration immediately. The Metadata API is better when you want to move many components together and have them validated as a unit.
Summary
The Metadata API moves configuration, not data. It works through asynchronous deploy and retrieve jobs that use ZIP files and a package.xml manifest. Deployment options control validation, rollback, and test execution, and the CLI hides most of the SOAP details. Choose it for releases and migrations, and choose other APIs for records or for fine-grained development tooling.
Exercise
Your team wants to move a new custom object, its page layout, and an Apex trigger from a sandbox to production. Which API fits, how do you reduce the risk of a failed release, and why can't the same API copy the 5,000 sample Account records you created in the sandbox?
Show answer
Use the Metadata API, usually through the Salesforce CLI. List the components in a package.xml manifest and run a checkOnly validation with a test level such as RunLocalTests first. After it passes, use a quick deploy so the tests do not run again. This lowers risk because production deployments with Apex are all-or-nothing and the validation catches missing dependencies and test failures before anything is saved. The Metadata API handles configuration only. Account records are data, so move them with the REST API or Bulk API 2.0 (for 5,000 records, Bulk API 2.0 or a Composite request fits).
Exercise
A deployment job ID was returned immediately, but the changes are not in the org yet. Is something wrong? What would you do next?
Show answer
Nothing is wrong. Metadata API deployments are asynchronous, so the call returns a job ID and the work happens afterward. Poll checkDeployStatus with that ID (or run sf project deploy report) until the status is Succeeded or Failed, then read the component and test failure details if it failed.