Assign a Default Community to a User Profile Programmatically

Salesforce stores default community to a User Profile in NetworkAffinity object. Using apex we cannot insert the default community to a User Profile. We can make a REST API call to add default community to a User Profile.

Sample Code:

//Get Endpoint URL
String endpointURL = URL.getSalesforceBaseUrl().toExternalForm()+'/services/data/v48.0/sobjects/NetworkAffinity';
HttpRequest req = new HttpRequest();  
req.setHeader('Authorization', 'Bearer ' + UserInfo.getSessionId()); 
req.setHeader('Content-Type', 'application/json;charset=UTF-8');
//Add Community Id as NetworkId and Profile/Permission Id
Http http = new Http();
HttpResponse response = http.send(req);
System.debug('response-' + response);

Note: Add your salesforce base URL as remote site settings and then execute above code in developer console anonymous window.