Unable to add new post using API

Hi I am unable to add new post on topic in my discourse forum using API, my code:

function postComment(topicId, comment) {
  const url = `${DISCOURSE_API_URL}/t/${topicId}/posts.json`; // Ensure this URL is correct
  Logger.log(`Posting to URL: ${url}`);
  const headers = {
    "Api-Key": DISCOURSE_API_KEY,
    "Api-Username": DISCOURSE_API_USERNAME
  };

  const payload = {
    post: {
      topic_id: topicId,
      raw: comment
    },
  };

  const options = {
    method: "post",
    contentType: "application/json",
    headers: headers,
    payload: JSON.stringify(payload),
    muteHttpExceptions: true, // To capture the full error response
  };

  try {
    const response = UrlFetchApp.fetch(url, options);
    const jsonResponse = JSON.parse(response.getContentText());

    // Log the response for debugging
    Logger.log(`Response Code: ${response.getResponseCode()}`);
    Logger.log(`Response Body: ${JSON.stringify(jsonResponse, null, 2)}`);

    // Check if the posting was successful
    if (response.getResponseCode() === 200) {
      Logger.log(`Posted comment successfully: ${JSON.stringify(jsonResponse, null, 2)}`);
    } else {
      Logger.log(`Failed to post comment: ${JSON.stringify(jsonResponse, null, 2)}`);
    }

    return jsonResponse; // Return the API response
  } catch (error) {
    Logger.log(`Error posting comment: ${error}`);
    return null; // Return null on error
  }
}

getting this response:

Info
Response Code: 404
3:35:29 PM
Info
Response Body: {
  "errors": [
    "The requested URL or resource could not be found."
  ],
  "error_type": "not_found"
}

even though forum topic exists and I can post on it directly on forum website.

Please help.

404 not likely means that your api key is bad or not getting passed correctly.

Unless it means that you’re actually using the wrong path. If you Reverse engineer the Discourse API for a post, is that the path that’s used?

I am using this path: ${DISCOURSE_API_URL}/t/${topicId}/posts.json
where DISCOURSE_API_URL = "https://community.xxxxxxxxxxx.com"

I think the URL for replying to a topic via the API is /posts.json. When creating a reply, as opposed to when you’re creating a new topic, the topic_id is a required param.

Details are here: Discourse API Docs, but you can also just create a reply to a topic through your site’s UI and check the RequestURL that’s set in the “network” section of your browser’s web inspector.

2 Likes