Can the Metadata API Be Invoked from Apex?

Question:
Is it possible to use the Salesforce Metadata API from within Apex? Can the Metadata API be invoked from Apex? Many sources state that Salesforce doesn’t allow callouts to its own web services from within Salesforce. However, other posts and resources suggest it might be achievable, especially for specific use cases like creating custom objects or fields. If possible, how can this be implemented?
CRS Info Solutions offers excellent Salesforce training in Delhi, with hands-on projects and certification support. Their practical approach ensures you’re fully prepared for the job market..!
Answer:
Yes, it is indeed possible to invoke the Metadata API from within Apex, though it comes with some caveats. The main challenge lies in Apex’s inability to handle zipped metadata packages, which are often required for many Metadata API operations. However, for simpler tasks such as creating custom fields or objects, direct SOAP calls can be made from Apex by constructing and sending custom SOAP messages. Below is an example of how you can use Apex to create a custom object via the Metadata API.
Here is a simple Apex code snippet that demonstrates this process:
HTTP h = new HTTP();
HTTPRequest req = new HTTPRequest();
req.setMethod('POST');
req.setHeader('Content-Type', 'text/xml');
req.setHeader('SOAPAction', 'create');
// Constructing the SOAP request body
String b = '<?xml version="1.0" encoding="UTF-8"?>';
b += '<soapenv:Envelope xmlns:soapenv="http://schemas.xmlsoap.org/soap/envelope/" xmlns:xsd="http://www.w3.org/2001/XMLSchema" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance">';
b += '<soapenv:Header>';
b += '<ns1:SessionHeader soapenv:mustUnderstand="0" xmlns:ns1="http://soap.sforce.com/2006/04/metadata">';
b += '<ns1:sessionId>' + UserInfo.getSessionId() + '</ns1:sessionId>';
b += '</ns1:SessionHeader>';
b += '</soapenv:Header>';
b += '<soapenv:Body>';
b += '<create xmlns="http://soap.sforce.com/2006/04/metadata">';
b += '<metadata xsi:type="ns2:CustomObject" xmlns:ns2="http://soap.sforce.com/2006/04/metadata">';
b += '<fullName>sample__c</fullName>';
b += '<deploymentStatus>Deployed</deploymentStatus>';
b += '<description>created by the Metadata API</description>';
b += '<enableActivities>true</enableActivities>';
b += '<label>sample Object</label>';
b += '<nameField>';
b += '<displayFormat>AN-{0000}</displayFormat>';
b += '<label>sample__c Name</label>';
b += '<type>AutoNumber</type>';
b += '</nameField>';
b += '<pluralLabel>sample Objects</pluralLabel>';
b += '<sharingModel>ReadWrite</sharingModel>';
b += '</metadata>';
b += '</create>';
b += '</soapenv:Body>';
b += '</soapenv:Envelope>';
req.setBody(b);
req.setCompressed(false);
// Update the endpoint to match your Salesforce instance
req.setEndpoint('https://<your-instance>.salesforce.com/services/Soap/m/25.0');
HTTPResponse resp = h.send(req);
System.debug(resp.getBody());
Explanation:
- Session Header: The
SessionHeader
tag contains the user’s session ID, which is retrieved usingUserInfo.getSessionId()
. - SOAP Request: The body of the request is a custom SOAP message that defines the metadata for the custom object being created.
- Endpoint: Replace
<your-instance>
with your Salesforce instance (e.g.,na12-api.salesforce.com
). - Output: The response from the Metadata API contains details about the result of the request, which can be inspected using
System.debug(resp.getBody())
.
While this method works for certain use cases, it does have limitations:
- Complex operations requiring zipped metadata packages cannot be handled within Apex.
- WSDL2Apex does not fully support the Metadata WSDL due to schema type extensions, making it challenging to generate Apex classes directly from the WSDL.
In cases where zipped packages or complex metadata operations are required, a better approach would be to use an external integration layer, such as a middleware service or a Salesforce-connected app, to handle the Metadata API calls.
If you want to build an interactive object builder, combining this approach with Visualforce or Lightning components can help you provide real-time feedback and success notifications for metadata creation.
Kick Start Your Journey with Salesforce Training in Delhi.
Our comprehensive Salesforce course offers an immersive learning experience, equipping you with the skills needed to thrive in the CRM industry. Covering essential areas like Salesforce Admin, Developer, and AI, the program combines solid theoretical knowledge with practical hands-on training. You’ll gain real-world experience through live projects and assignments, developing the expertise to solve complex business challenges with Salesforce solutions. Our expert instructors are dedicated to enhancing your technical skills and providing valuable industry insights.
Along with technical training, our Salesforce course in Delhi offers personalized mentorship, exam prep, and interview coaching to help you stand out in a competitive job market. You’ll get access to in-depth study materials, real-world project experience, and ongoing support. By the end of the course, you’ll be fully prepared for certification exams and equipped with the practical problem-solving skills employers seek.
Start your Salesforce journey today and unlock exciting career opportunities! Enroll for a FREE Demo..!