How do I assign a topic via the API

@tobiaseigen this works for me using node js

var https = require(‘https’);

// Configuration
var CONFIG = {
apiUrl: ‘YOURDISCOURSEDOMAIN’,
apiKey: ‘YOURAPIKEY’,
apiUsername: ‘YOURAPIUSER’,
assignToUsername: ‘USERNAMETOASSIGNTO’  // Username to assign topics to
};

// Topic IDs to assign
var topicIds = [634]; //change with the topic id

function assignTopic(topicId, callback) {
var postData = JSON.stringify({
target_id: topicId,
target_type: ‘Topic’,
username: CONFIG.assignToUsername
});

var options = {
hostname: CONFIG.apiUrl,
port: 443,
path: ‘/assign/assign.json’,
method: ‘PUT’,
rejectUnauthorized: false,
headers: {
‘Api-Key’: CONFIG.apiKey,
‘Api-Username’: CONFIG.apiUsername,
‘Content-Type’: ‘application/json’,
‘Content-Length’: postData.length
}
};

var req = https.request(options, function(res) {
var data = ‘’;

res.on('data', function(chunk) {
  data += chunk;
});

res.on('end', function() {
  console.log('Status:', res.statusCode);
  console.log('Raw response:', data);
  try {
    var response = JSON.parse(data);
    if (res.statusCode === 200) {
      console.log('Topic ' + topicId + ' successfully assigned');
    } else {
      console.log('Topic ' + topicId + ' error:', response.errors || response.error_type || response);
    }
  } catch (e) {
    console.log('Parse error:', e.message);
  }
  if (callback) callback();
});

});

req.on(‘error’, function(e) {
console.error('Request error for topic ’ + topicId + ‘:’, e);
if (callback) callback();
});

req.write(postData);
req.end();
}

// Run sequentially
var index = 0;
function next() {
if (index < topicIds.length) {
assignTopic(topicIds[index], function() {
index++;
setTimeout(next, 500);
});
}
}

console.log(‘Assigning topics:’, topicIds.join(‘, ‘));
console.log(‘Assign to:’, CONFIG.assignToUsername);
console.log(’’);
next();
2 Likes