Skip to main content

Request to OpenAI

Creating a request in the Node-RED environment.

In the Node-RED environment, we create an endpoint that makes a request to the OpenAI API and returns a link to an image.

You will need the following nodes:

  1. "http in" node (with the POST method).
  2. "function" node. In the function node, specify all the necessary data to make a request to OpenAI. First, you need to register on the OpenAI website. After that, go to your account and create your own API key.

Please note that for security reasons, it is recommended to keep your API key confidential and avoid sharing it publicly. Make sure to read the documentation!

image.png


image.png


Instead of YOUR_API_KEY in the function, insert your own key. The rest of the settings remain unchanged.

msg.token = `Bearer YOUR_API_KEY`
msg.oldpayload=msg.payload;
msg.url=`https://api.openai.com/v1/images/generations`;
msg.method="POST";

msg.headers={ 
"Content-Type": "application/json",
  "Authorization": "Bearer  YOUR_API_KEY"
  }

msg.payload={
    "prompt": msg.oldpayload.content,
    "n": msg.oldpayload.count,
    "size":"512x512"
  }

return msg;
  • http request.
    Method -set by msg.method-. URL - we'll set in other place. Specify that the desired return is a parsed JSON object.


    image.png

  • function

    In the function node, we will check the status code received. If it is 200, we will save the time when the data was received (date) and record the expiration time for the link (expireTime). We will add the following to each object: the text based on which we obtained the image data (msg.oldpayload.content), the creation date, and the expiration time for the link. If the status code is different, we will return an error.


  • if (msg.statusCode==200){ var date = new Date(); var expireTime = new Date(Date.now() + (1 * 60 * 60 * 1000)); msg.payload=msg.payload.data.map((el)=>{return{ img: el.url, text: msg.oldpayload.content, date: date, expireTime: expireTime, }}) } else{ msg.payload = msg.payload.error.message; } return msg;
  • http response


    Here is how the entire endpoint should look like:


    image.png

Creating an API request on the UI side.

Creating an API that invokes the endpoint we have created.

image.png

image.png

The path to the flow contains a link to the Node-RED and the URL of the API: `${Node-RED link}/{URL from http in}`

  • link to the Node-RED

    image.png

  • The URL specified in the HTTP In node.


    image.png

    image.png


In the body, we pass the values from the input and sliderwidgets.

image.png

image.png

The API is called when the button is clicked.

The data returned by the API should be displayed in the carousel widget. Please use your discretion to determine the value of the visibleSlides property for the widget (for example, 4).

image.png

Important: The carousel widget should display the images that are stored under the key "img".

Expected result:

image.png