How to create object in salesforce through Web-Service using Apex Metadata API

Hi All,
many times we required to create objects into Salesforce through web services i.e. using Metadata API. Here is a sample code by which we can create such custom object into the Salesforce.

for the Apex Metadata Api please refer
Apex Metadata API this link.

// Visualforce Page code

<apex:page controller="MetadataUse" action="{!createObject}">


// Apex code

public with sharing class MetadataUse
    public static void createObject()
      MetadataService.CustomObject customeObject = new MetadataService.CustomObject();
      MetadataService.MetadataPort service = MetadataService.createService();
      customeObject.fullName = 'metadataObject__c';
      customeObject.label = 'Metadata Object';
      customeObject.pluralLabel = 'Metadata Objects';
      customeObject.nameField = new MetadataService.customField();
      customeObject.nameField.type_x = 'Text';
      customeObject.nameField.label = 'Sample Record';
      customeObject.deploymentStatus = 'Deployed';
      customeObject.sharingModel = 'ReadWrite';
      MetadataService.AsyncResult[] results = service.create(new List<MetadataService.Metadata>{customeObject});

Steps :

1] to create custom object just create one Visualforce page and use the above mentioned visualforce code in it.

2] Create new Apex class and use above mentioned Apex code in it. You can change the object names as per your convenience.

3] If you get an error saying that no createService() method in MetadataService class then add the following code into it

public static MetadataService.MetadataPort createService()
            MetadataService.MetadataPort service = new MetadataService.MetadataPort();
            service.SessionHeader = new MetadataService.SessionHeader_element();
            service.SessionHeader.sessionId = UserInfo.getSessionId();
            return service;

and save it.

after this execute the apex page and check whether new object created or not. Surely new object get created.

Hope this post will be helpful to you.


Need more help?

Hi there, was your problem or query resolved? If not & need more assistance, please do reach out to us at, we'll be more than delighted to help. Nanostuffs has 7+ years of extensive Salesforce & iOS/Android experience.
Holler Box