How to build an API with Edge Functions and ChatGPT
Learn about the required process to create an API with Edge Functions and ChatGPT and have the response shown on the Azion Preview Deployment.
To do so, you need to:
To start creating your API, proceed as follows:
- On Real-Time Manager (RTM), on the upper-left corner, select Edge Functions in the Edge Libraries section.
- Click on Add a Function.
- Choose a name for your function.
- Delete the placeholder function that is inside the code editor.
- Add your OpenAI API key and organization ID to the code as a comment:
Note: the preview will present a warning mentioning the necessity of the
PreviewProvider function. Don’t worry, this situation will be covered by the upcoming steps.
- Copy and paste the following
- Write the following prompt inside the function, right below the OpenAI credentials that were pasted on step 5:
- Select the prompt > click on it with the right button > choose ChatGPT: Generate. Wait a few seconds for it to complete the request.
The expected output should be similar to:
- Add the
handleRequest function, containing a
switch case, with a
GET and a
POST method returns a
JSON object, that was generated by the
ChatGPT: Generate option.
GET method returns the HTML
const that was declared on step 6.
- Copy and paste the
PreviewProvider function, responsible for simulating requests:
- Add the
addEventListener function, which triggers the whole processing of the edge function:
- Click with the right button anywhere inside the code editor and select Format Document.
At this point, your edge function should look like this:
If you want, you can switch the method inside the
PreviewProvider function and get a live preview of the responses on the Azion Preview Deployment.
- Click the Save button.
Now, the function is ready to be instantiated in an edge application. Check how to instantiate and execute the functions in your edge application and try it out.