# How to build an API with Functions and ChatGPT

Learn about the required process to create an API with [Functions](/en/documentation/products/build/applications/functions/) and [ChatGPT](/en/documentation/products/applications/functions/runtime-api/ai-integration/) and have the response shown on the [Azion Preview Deployment](/en/documentation/products/applications/functions/runtime-api/preview-deployment/).

To do so, you need to:

- Be [registered on OpenAI](https://chat.openai.com/).
- Have [your OpenAI API key](https://platform.openai.com/account/api-keys).
- Have [your OpenAI organization ID](https://platform.openai.com/account/org-settings).

To start creating your API, proceed as follows:

1. Access [Azion Console](/en/documentation/products/guides/how-to-access-azion-console/) > **Functions**.
2. Click on **+ Function**.
3. Choose a name for your function.
4. In the **Code** tab, delete the placeholder function that is inside the code editor. 
5. Add your OpenAI API key and organization ID to the code as a comment:

```js
    /*
    ChatGPTKey=sk-xxxxxxx
    ChatGPTOrg=org-xxxxxx
    */
```

:::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.
:::

6. Copy and paste the following `const`:

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

7. Write the following prompt inside the function, right below the OpenAI credentials that were pasted on step 5:

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

8. 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:

```js
    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'}]
    };
```

9. Add the `handleRequest` function, containing a `switch case`, with a `GET` and a `POST` method:

```js
async function handleRequest(request) {
  switch (request.method) {
    case 'POST':
      return new Response(JSON.stringify(myObject), { // Returning the object generated by ChatGPT
        headers: {
          "content-type": "application/json",// Altering the content-type to application/json
        }
      })
    case 'GET':
      return new Response(html, {
        headers: {
          "content-type": "text/html:charset=UTF-8",
        }
      })
  }
}
```

- The `POST` method returns a `JSON` object, that was generated by the `ChatGPT: Generate` option.
- The `GET` method returns the HTML `const` that was declared on step 6.

10. Copy and paste the `PreviewProvider` function, responsible for simulating requests:

```js
    function PreviewProvider(args) {
      var request = {
        body: {},
        headers: {},
        method: "GET", 
        redirect: "",
      }
      return handleRequest(request)
    }
```

11. Add the `addEventListener` function, which triggers the whole processing of the function:

```js
    addEventListener("fetch", event => {
            return event.respondWith(handleRequest(event.request))
          })
```

12. Click with the right button anywhere inside the code editor and select **Format Document**.

At this point, your function should look like this:

```js

    /*
    ChatGPTKey=sk-xxxxxxx
    ChatGPTOrg=org-xxxxxx
    */
    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 'POST':
          return new Response(JSON.stringify(myObject), { // Returning the object generated by ChatGPT
            headers: {
              "content-type": "application/json",// Altering the content-type to application/json
            }
          })
        case 'GET':
          return new Response(html, {
            headers: {
              "content-type": "text/html:charset=UTF-8",
            }
          })
      }
    }

     function PreviewProvider(args) { 
      var request = {
        body: {},
        headers: {},
        method: "GET", //or POST
        redirect: "",
      }
      return handleRequest(request)
    }

      addEventListener("fetch", event => {
        return event.respondWith(handleRequest(event.request))
      })
```

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](/en/documentation/products/applications/functions/runtime-api/preview-deployment/).

13. Click the **Save** button.

Now, the function is ready to be instantiated in an application. Check how to [instantiate and execute the functions in your application](/en/documentation/products/build/applications/functions-instances/) and try it out.