function readOnly(count){ }
Starting November 20, the site will be set to read-only. On December 4, 2023,
forum discussions will move to the Trailblazer Community.
+ Start a Discussion
Harshwardhan Singh KarkiHarshwardhan Singh Karki 

How can we insert records of custom metadata type using tooling api(Using http callout) from regular user?

I have A custom metadata type named "ImportNotes_Setting__mdt" with fields , DeveloperName , MasterLabel as standard and custom fields are , ImportId__c,Notes__c, IsDelete__c ,so  i need to insert records from user for this custom metadata type using tooling api (Http callout) .

Code executed to insert record of custom metadata type which is  returning error {"message":"entity type cannot be inserted: ImportNotes Setting","errorCode":"CANNOT_INSERT_UPDATE_ACTIVATE_ENTITY","fields":[]} , So i need the solution regarding this if it is possible to do so with this approach


global class TestRecordInsertUsingToolingApi {
    @future (callout = true)
    public static void connectOrg(){
        Http h = new Http();
        Httprequest req = new Httprequest();
        string json ='{"Masterlabel":"Import Note","ImportID__c":"Imp36862577","Notes__c":"Test ToolinApi"}';
        String autho ='Bearer '+ UserInfo.getUserId();
        req.setHeader('Authorization', autho);            
        string endpointRemainingUrl = '/services/data/v56.0/sobjects/ImportNotes_Setting__mdt';
        string endpoint = Url.getSalesforceBaseUrl().toExternalForm() + endpointRemainingUrl;
        req.setEndpoint(endpoint); 
        req.setHeader('Content-Type','application/json;  charset=utf-8');
        req.setBody(json);
        req.setMethod('POST');
        Httpresponse res = h.send(req);
        system.debug(res.getBody()+ res.getStatusCode());
        if(res.getStatusCode() == 400){
            system.debug(res.getBody());
            Map<String, Object> m = (Map<String, Object>)System.JSON.deserializeUntyped(res.getBody());
            system.debug(m);
        }
    }
Prateek Prasoon 25Prateek Prasoon 25
Unfortunately, it is not possible to insert records into a custom metadata type using the Tooling API. The error message you received "entity type cannot be inserted: ImportNotes Setting" confirms this.
Instead, you can insert records into a custom metadata type using the Metadata API. Here is an example of how you can modify your code to use the Metadata API:
global class TestRecordInsertUsingMetadataApi {
    @future(callout=true)
    public static void insertImportNotesSetting() {
        MetadataService.MetadataPort service = new MetadataService.MetadataPort();
        service.SessionHeader = new MetadataService.SessionHeader_element();
        service.SessionHeader.sessionId = UserInfo.getSessionId();
        
        MetadataService.CustomMetadata customMetadata = new MetadataService.CustomMetadata();
        customMetadata.fullName = 'ImportNote.ImportNoteSetting'; // Developer Name of the custom metadata type and record name
        customMetadata.label = 'Import Note'; // Master Label of the custom metadata type and record name
        customMetadata.fields = new List<MetadataService.CustomMetadataValue>();
        
        MetadataService.CustomMetadataValue importIdValue = new MetadataService.CustomMetadataValue();
        importIdValue.field = 'ImportID__c';
        importIdValue.value = 'Imp36862577';
        customMetadata.fields.add(importIdValue);
        
        MetadataService.CustomMetadataValue notesValue = new MetadataService.CustomMetadataValue();
        notesValue.field = 'Notes__c';
        notesValue.value = 'Test Metadata API';
        customMetadata.fields.add(notesValue);
        
        List<MetadataService.SaveResult> results = service.createMetadata(new MetadataService.Metadata[] { customMetadata });
        
        if (results[0].success) {
            System.debug('Record inserted successfully');
        } else {
            System.debug('Error inserting record: ' + results[0].errors[0].message);
        }
    }
}

Note that you will also need to add the MetadataService class from the Metadata API to your org. You can download it from the Metadata API Developer Guide.
If you find this answer helpful, Please mark it as the best answer.