# Share your use cases of using Discourse REST API 🧑‍💻

**URL:** <https://meta.discourse.org/t/share-your-use-cases-of-using-discourse-rest-api/272139>\
**Category:** Development\
**Tags:** rest-api\
**Created:** [July 19, 2023, 3:17pm UTC](https://meta.discourse.org/t/share-your-use-cases-of-using-discourse-rest-api/272139 "2023-07-19T15:17:05Z")\
**Posts on this page:** 1\
**Showing post:** 3

<div class="post-metadata">

**Author:** ![maiki](https://sea3.discourse-cdn.com/meta/user_avatar/meta.discourse.org/maiki/32/233950_2.png) [@maiki](https://meta.discourse.org/u/maiki)\
**Post date:** [August 8, 2023, 6:58pm UTC](https://meta.discourse.org/t/share-your-use-cases-of-using-discourse-rest-api/272139/3 "2023-08-08T18:58:57Z")

</div>

I did a lot of experimenting recently with various platforms that provide chaining together steps, and I’ll share one that got me excited: Optical Character Recognition to detect text in an image, and appending it to the Discourse post!

My sandbox topic shows how it works: [https://notes.maiki.interi.org/t/testing-ocr-calls/403](https://notes.maiki.interi.org/t/testing-ocr-calls/403)

I did the first one on Pipedream, and I will explain how I did it by following along the steps. There is a beta feature for sharing workflows on that service, and the following is shared at [https://pipedream.com/new?h=tch\_3Z6fa9](https://pipedream.com/new?h=tch_3Z6fa9).

> ℹ While this would make for an in-depth guide to using Pipedream with Discourse, I’m going to stay light on details, as I’ve already moved on from that platform, and will be sharing more about that later. 🙂

### Steps

The rough outline is: send image URL to Google Cloud Vision API, run the results through ChatGPT, then append the results to the post in Discourse.

#### Trigger

![Screenshot 2023-08-08 at 11-23-21 OCR Test - Pipedream](https://global.discourse-cdn.com/meta/original/4X/a/4/a/a4a6415b5ea9f3f902af982409222bfe288c8ae6.png)

This provides a webhook to send data to. In Discourse I created a webhook with two specific settings:

![Screenshot 2023-08-08 at 11-24-41 Admin - notes](https://global.discourse-cdn.com/meta/original/4X/8/0/3/80357ec2e66e8a36ce049f5ec2ae5566e7c868df.png)

Only firing on Post Events means my initial topic won’t trigger the process; this is useful to me so I can plan to use topics as holders for applying external functions (I call them “[functional notes](https://notes.maiki.interi.org/t/functional-notes/398)”).

 ![Screenshot 2023-08-08 at 11-24-52 Admin - notes](https://global.discourse-cdn.com/meta/original/4X/c/b/6/cb6e9f5b5dfe1f6cff178c9f357a1aeaafee9cfd.png)

Only firing on that tag means I can use tags to control which webhooks are produced per topics; generally I’d only have one “functions” tag, to keep the process logic simple.

The webhook sends a payload with lots of info, and we’ll use the topic and post IDs later in the process.

#### End based on condition

 ![Screenshot 2023-08-08 at 11-32-29 OCR Test - Pipedream](https://global.discourse-cdn.com/meta/original/4X/4/2/f/42ffeaeb3c437b4374447e02242a94ca2eae8570.png)

This is a step to check if an edit reason is included. If so, it stops the workflow.

In the last step I update the post and include an Edit Reason, and this check [ensures that I don’t keep updating the post](https://notes.maiki.interi.org/t/testing-ocr-calls/403/6)… 😅

> ℹ One of reasons I stopped using Pipedream was because my webhook checks were eating up credits on the service. I don’t think I should have to pay to conditionally process a webhook, hence moving on…

#### Extract the image URL

 ![Screenshot 2023-08-08 at 11-37-22 OCR Test - Pipedream](https://global.discourse-cdn.com/meta/original/4X/c/7/c/c7c45d8d5856261654b52f818775bbd6c31790b6.png)

I decided for this test each post would have a single image uploaded to it. This step checks the “cooked” value and uses the following regular expression to grab the URL:

```plaintext
/https?:\/\/[^\s"]+/

```

#### Google Cloud Vision API call

This is a custom code step on Pipedream. The pre-made components didn’t do want I wanted, and the service also has a code assistant that can write code from a prompt; as these API calls are straightforward, it was easy to produce with this method.

It takes the value of the former step (`{{steps.extract_by_regular_expression.$return_value[0].match}}`), and this is the code:

```js
import { axios } from "@pipedream/platform";

export default defineComponent({
  props: {
    imageUrl: {
      type: "string",
      label: "Image URL",
      description: "URL of the image to be processed by Google Vision API",
    },
    apiKey: {
      type: "string",
      label: "API Key",
      description: "Your Google Cloud API Key",
      secret: true,
    },
  },
  async run() {
    const url = `https://vision.googleapis.com/v1/images:annotate?key=${this.apiKey}`;
    const body = {
      requests: [
        {
          image: {
            source: {
              imageUri: this.imageUrl,
            },
          },
          features: [
            {
              type: "TEXT_DETECTION",
            },
          ],
        },
      ],
    };

    const config = {
      method: "POST",
      url,
      data: body,
    };

    const response = await axios(this, config);
    return response;
  },
});

```

#### ChatGPT for editing

 ![Screenshot 2023-08-08 at 11-43-11 OCR Test - Pipedream](https://global.discourse-cdn.com/meta/original/4X/8/6/c/86c6e9850ee89425fdbc6af86fd354db778d6d6c.png)

Takes output from the former step (`{{steps.google_cloud.$return_value.responses[0].fullTextAnnotation.text}}`) and passes it as the User message. For the system message I have:

> You are reading the output from a vision api that detected text in an image. Review the message and copyedit it for clarity. Return only the edited text without commentary.

#### Append to the post in Discourse

 ![Screenshot 2023-08-08 at 11-48-01 OCR Test - Pipedream](https://global.discourse-cdn.com/meta/original/4X/e/2/f/e2f5850c75293edbb2842153f669a67b5759e60a.png)

Another custom code section, as the pre-made [Discourse actions in Pipedream](https://pipedream.com/apps/discourse) only cover a couple of scenarios (create a topic or a post), and I want to _append_ the text to the post.

First, here’s the code:

```js
import { axios } from "@pipedream/platform";

export default defineComponent({
  props: {
    discourse: {
      type: "app",
      app: "discourse",
    },
    postId: {
      type: "string",
      label: "Post ID",
      description: "The ID of the post to append text to",
    },
    text: {
      type: "string",
      label: "Text",
      description: "The text to append to the post",
    },
    editReason: {
      type: "string",
      label: "Edit Reason",
      description: "The reason for editing the post",
      optional: true,
    },
  },
  async run({ steps, $ }) {
    const url = `https://${this.discourse.$auth.domain}/posts/${this.postId}.json`;
    const response = await axios($, {
      method: "GET",
      url: url,
      headers: {
        "Api-Username": `${this.discourse.$auth.api_username}`,
        "Api-Key": `${this.discourse.$auth.api_key}`,
      },
    });

    const updatedText = `${response.raw} ${this.text}`;

    return await axios($, {
      method: "PUT",
      url: url,
      headers: {
        "Api-Username": `${this.discourse.$auth.api_username}`,
        "Api-Key": `${this.discourse.$auth.api_key}`,
      },
      data: {
        post: {
          raw: updatedText,
          edit_reason: this.editReason,
        },
      },
    });
  },
});

```

Those properties for step are filled in like so:

##### Post ID

Grabs the post ID from the original payload: `{{steps.trigger.event.body.post.id}}`

This is used to edit that post directly.

##### Text

```plaintext
---

<blockquote>
 {{steps.chat.$return_value.generated_message.content}}
</blockquote>

[details="Detected text"]
{{steps.google_cloud.$return_value.responses[0].textAnnotations[0].description}}
[/details]

```

Basically, I want to add a horizontal rule beneath each image, with a blockquote of edited text, and the details to check the raw output.

Since each post will have one image in it, this works very easily. I wonder how to do it with multiple images at once? 🤔

##### Edit Reason

> OCR Text Detection

This is added as the edit reason for the post update, which will prevent a post update loop due to the step at the beginning. ☝ ♻ 🆖

> ℹ I find it super helpful to always include an edit reason, especially when dealing with external services.

* * *

And that’s it! As you can see from my sandbox, it works fairly well!

I have a trip coming up, and I plan on fine-tuning the OpenAI editing to also translate to English if needed, that is one option I would have added to the system prompt for this workflow.

---

_[View the full topic](https://meta.discourse.org/t/share-your-use-cases-of-using-discourse-rest-api/272139)._
