---
name: azion-build-an-api-function-with-chatgpt
description: >-
  Generate the JSON payload of a function with the ChatGPT integration of the Azion Console editor, then read the response with Preview deployment.
---

# Build an API function with ChatGPT

You build a function that answers a `GET` request with HTML and a `POST` request with JSON. The [ChatGPT integration](/en/documentation/platform/functions/ai-integration/) of the Azion Console [code editor](/en/documentation/platform/functions/code-editor/) writes the JSON payload from a comment.

Two neighboring pages own the parts this one leaves out:

- For the handler patterns of a function and its log output, refer to [Write and test a function](/en/documentation/guides/application-development/functions-and-runtime/first-steps/).
- For an API backed by a database, refer to [Build a RESTful API with Functions and SQL Database](/en/documentation/guides/application-development/functions-and-runtime/restful-tasks-api-functions/).

---

## Prerequisites

- An Azion account. To create one, refer to [How to create an account on Azion](/en/documentation/fundamentals/creating-account/).
- The **Edit Functions** permission on the account. It also requires the permission **View Functions**. Refer to [Teams Permissions](/en/documentation/fundamentals/teams-permissions/).
- An account on [OpenAI](https://chat.openai.com/), with an [API key](https://platform.openai.com/account/api-keys) and an [organization ID](https://platform.openai.com/account/org-settings).

---

## Declare the OpenAI credentials

The integration runs on the credentials of your own OpenAI account. It reads them from a comment in the source code of the function, so the credentials come first.

To put the credentials in the source code of a new function:

1. **Open the Functions page**

   Access [Azion Console](https://console.azion.com/) > **Products Menu** > **Libraries** > **Functions**.

2. **Select + Function**

3. **Name the function**

   Enter a name for the function. For example: `chatgpt-api`.

4. **Replace the placeholder code in the Code tab**

   In the **Code** tab, replace the placeholder code with the two values of your OpenAI account:

   ```javascript
   /*
   ChatGPTKey=[TOKEN VALUE]
   ChatGPTOrg=<your-organization-id>
   */
   ```

The editor commands of the integration now authenticate with your OpenAI account.

> **Note**
>
> Azion Console renders no preview while the source code carries no `PreviewProvider` function. The preview shows a warning that names the missing function. A later section adds that function.

---

## Generate the response data with ChatGPT

Code generation turns a comment into JavaScript. The **ChatGPT: Generate** command reads the selected comment as the prompt and writes the code it returns.

To generate the object the API returns:

1. **Enter the prompt as a comment**

   Below the credentials, enter the comment that describes the object:

   ```javascript
   // generate an object with 5 properties being 2 of them array of objects
   ```

2. **Select the comment**

3. **Open the context menu of the editor and select ChatGPT: Generate**

   The request takes a few seconds.

4. **Read the generated code**

   The integration writes the object in the editor. The output is similar to:

   ```javascript
   let myObject = {
       property_1: 'value_1',
       property_2: 10,
       property_3: true,
       property_4: [{object_1: 'value_1'}, {object_2: 'value_2'}],
       property_5: [{object_3: 'value_3'}, {object_4: 'value_4'}]
   };
   ```

The source code now carries the object the API returns for a `POST` request.

---

## Assemble the handler

The generated object is data. The handler decides what the function returns for each request method. A `fetch` handler branches on `request.method`: the markup for a `GET`, the object for a `POST`.

Complete the source code with the HTML constant, the handler, and the default export:

```javascript
const html = `<!DOCTYPE html>
<body>
  <h1>Hello World</h1>
  <p>This markup was generated by Azion Functions.</p>
</body>`;

let myObject = {
    property_1: 'value_1',
    property_2: 10,
    property_3: true,
    property_4: [{object_1: 'value_1'}, {object_2: 'value_2'}],
    property_5: [{object_3: 'value_3'}, {object_4: 'value_4'}]
};

async function handleRequest(request) {
  switch (request.method) {
    case 'GET':
      return new Response(html, {
        headers: {
          'content-type': 'text/html;charset=UTF-8',
        },
      });
    case 'POST':
      return new Response(JSON.stringify(myObject), {
        headers: {
          'content-type': 'application/json',
        },
      });
  }
}

export default {
  async fetch(request, env, ctx) {
    return handleRequest(request);
  },
};
```

Each branch declares the format it returns in the `content-type` header:

- The `GET` case returns the `html` constant as `text/html;charset=UTF-8`.
- The `POST` case returns the generated object as `application/json`.

The switch covers `GET` and `POST`. Add a case for every other method the API answers.

The default export is the ES Modules pattern, the recommended way to structure a function. To move existing code off the legacy Service Worker pattern, refer to [Migrate handler patterns in Functions](/en/documentation/guides/application-development/functions-and-runtime/migrate-handler-patterns/).

The source code now holds the complete handler of the API.

---

## Preview the response

[Preview deployment](/en/documentation/platform/functions/preview-deployment/) runs the function in Azion Console and shows the response the code returns. It calls `PreviewProvider`, an auxiliary function in the source code that builds a simulated request for the handler.

To read both responses before the function serves traffic:

1. **Add a PreviewProvider function to the source code**

   `PreviewProvider` builds the request the preview sends and returns the response the preview renders. Add it below the default export, with `GET` as the method:

   ```javascript
   function PreviewProvider(args) {
     var request = new Request("https://www.azion.com/example", {
       method: "GET",
       headers: {
         "Content-Type": "application/json",
       },
       redirect: "follow",
     });
     return handleRequest(request);
   }
   ```

   For every value the simulated request carries, refer to [PreviewProvider function](/en/documentation/platform/functions/preview-deployment/#previewprovider-function).

2. **Open the context menu of the editor and select Format Document**

3. **Read the output in the code editor**

   The preview renders the `text/html` response as the page. Select **Open** to read the same output in a separate browser tab.

4. **Change the method inside PreviewProvider to POST**

5. **Read the output again**

   The preview renders the `application/json` response as the JSON body of the generated object.

Both responses of the function appear in Azion Console, with no deployment.

---

## Save the function

The complete source code carries the credentials, the generated object, the handler, and the preview function:

```javascript
/*
ChatGPTKey=[TOKEN VALUE]
ChatGPTOrg=<your-organization-id>
*/

const html = `<!DOCTYPE html>
<body>
  <h1>Hello World</h1>
  <p>This markup was generated by Azion Functions.</p>
</body>`;

let myObject = {
    property_1: 'value_1',
    property_2: 10,
    property_3: true,
    property_4: [{object_1: 'value_1'}, {object_2: 'value_2'}],
    property_5: [{object_3: 'value_3'}, {object_4: 'value_4'}]
};

async function handleRequest(request) {
  switch (request.method) {
    case 'GET':
      return new Response(html, {
        headers: {
          'content-type': 'text/html;charset=UTF-8',
        },
      });
    case 'POST':
      return new Response(JSON.stringify(myObject), {
        headers: {
          'content-type': 'application/json',
        },
      });
  }
}

export default {
  async fetch(request, env, ctx) {
    return handleRequest(request);
  },
};

function PreviewProvider(args) {
  var request = new Request("https://www.azion.com/example", {
    method: "GET",
    headers: {
      "Content-Type": "application/json",
    },
    redirect: "follow",
  });
  return handleRequest(request);
}
```

To store the code, select **Save**.

Azion Console stores the function and makes it available to instantiate on an application. The function serves no traffic until an instance binds it and a Rules Engine rule selects that instance.

---

## Next steps

- [Run a function on an application](/en/documentation/guides/application-development/functions-and-runtime/serverless-functions.md): Add the Rules Engine rule that runs the instance, from Azion Console or the Azion API.
- [ChatGPT integration](/en/documentation/platform/functions/ai-integration.md): The credentials, the editor commands, and code refactor.
- [Preview deployment](/en/documentation/platform/functions/preview-deployment.md): Every value the simulated request carries, and how the preview renders each format.
- [Write and test a function](/en/documentation/guides/application-development/functions-and-runtime/first-steps.md): The handler patterns of a function, and where to read its log output.
- [Function instances](/en/documentation/platform/applications/functions-instances.md): Pass Args to an instance in JSON.
- [Build a RESTful API with Functions and SQL Database](/en/documentation/guides/application-development/functions-and-runtime/restful-tasks-api-functions.md): An API backed by a database, with create, read, update, and delete operations.
