Metadata API
This blog post shows how to utilize the Metadata API to create/update/delete any metadata in our Salesforce instance. The Metadata WSDL file is provided by Salesforce. An apex class is generated from that WSDL and used to manipulate the Metadata.
Metadata API supports 2 types of development.
- File-Based development – This type of call requires the Zip file to deploy a metadata. Therefore VF Page is also required to utilize JavaScript to create a Zip file. This type of call is asynchronous.
- CRUD-Based development – These calls are synchronous and are made directly by Apex. There is no need of Zip files.
Follow the below steps to download and edit the WSDL and generate an Apex class:
- Go to Setup --> API --> Generate Metadata WSDL. It will open the WSDL in a new tab.
- Copy, paste and save the content in a .wsdl file.
- Find type="xsd:anyType" and replace it with type="xsd:string".
- Find <port binding="tns:MetadataBinding". There should be a name attribute in this tag. Change the name attribute of this port tag to name="MetadataWebServ"
- Go to Setup --> Apex Classes --> Click "Generate from WSDL" button.
- Upload the .wsdl file and create an Apex class. I hope that the apex class is generated without any errors at this step.
- Before making an API call, add your Salesforce instance in the Remote site settings.
You can download the WSDL file for reference: Download Metadata WSDL
You can download the Apex Class file for reference: Download Apex Class
Code Reference:
1. Starting the Metadata Service
Code Reference:
1. Starting the Metadata Service
private static final Integer METADATA_API_VERSION =
Integer.valueOf(new MetadataService.MetadataWebServ().endpoint_x.substringAfterLast('/'));
private static MetadataService.MetadataWebServ createService()2. describeMetadata()
{
MetadataService.MetadataWebServ service = new MetadataService.MetadataWebServ();
service.SessionHeader = new MetadataService.SessionHeader_element();
service.SessionHeader.sessionId = UserInfo.getSessionId(); //Passing the Session ID
return service;
}
MetadataService.MetadataWebServ service = createService();
MetadataService.DescribeMetadataResult describeResult = service.describeMetadata(METADATA_API_VERSION);
List<String> metadataTypeNames = new List<String>(); //This list will store all types of metadata
for(MetadataService.DescribeMetadataObject metadataObject : describeResult.metadataObjects)
{
metadataTypeNames.add(metadataObject.xmlName);
// Include child Metadata Types (such as CustomField, ValidationRule etc..)
if(metadataObject.childXmlNames!=null)
for(String childXmlName : metadataObject.childXmlNames)
if(childXmlName!=null)
metadataTypeNames.add(childXmlName);
}
First published on Blogger in 2017. Some screenshots and APIs have changed since; the code is kept as written.