Can't update a topic's body by API

I did follow the docs and, however, it only update the topic’s title, without updating the body.

My code (Javascript):

async function updateDiscourseTopic(topic_id) {
  const Discourse_API_Key = "Discourse_API_Key";
  const url = `https://discourse.mysite.com/t/-/${topic_id}.json`;

  const payload = {
    title: 'session_1',
    raw: "new body(doesn't apply)"
  }

  const response = await fetch(url, {
    method: 'PUT',
    headers: {
      "Api-Key": Discourse_API_Key,
      "Api-Username": "system",
      "Content-Type": "application/json",
    },
    body: JSON.stringify(payload)
  });

}

just a guess from looking at the code, but perhaps it may be because you are using topic_id instead of post_id? because first post is the topic in Discourse, more or less?

3 Likes

@Lilly’s right.

A topic is defined by attributes like title, category, tags, etc.

But the content belongs to a post.

If you want to update the title and the content, you need 2 requests.

  1. PUT on the topic

  2. PUT on the first post. You can find the post’s ID in the HTML code of the page. Look for the data-post-id attribute in <article>.
    Example:

    <article id="post_2" aria-label="post #2 by @Lillinator" role="region" data-post-id="1288311" data- 
    topic-id="264640" data-user-id="127856" class="boxed onscreen-post">
    
3 Likes

Wow,you are right, it works :sparkling_heart:

And I figured out how to retrieve the ID of the first post in a topic using the Discourse API:

async function getFirstPostIdFromOnetopic(topic_id) {
  const Discourse_API_Key = "Discourse_API_Key";
  const url = `https://discourse.mysite.com/t/${topic_id}/posts.json`;

  const response = await fetch(url, {
    method: 'GET',
    headers: {
      "Api-Key": Discourse_API_Key,
      "Api-Username": "system",
      "Content-Type": "application/json",
    }
  });
  const data = await response.json();
  const firstPostId = data.post_stream.posts[0].id;
  
  return firstPostId;
}

Thank you and @Lilly :innocent:

3 Likes

This topic was automatically closed 30 days after the last reply. New replies are no longer allowed.