# API

The API block allows you to send restful HTTP requests to 3rd party servers to append, delete or retrieve information from the server side. APIs are super handy when you need to communicate with an outside service that is not natively integrated with BotWiz. Sending HTTP requests with BotWiz is super simple. Below is a general outline on how to use this block and send successful requests. Given APIs can be complex, this guide will be elongated to cover as much as possible to make it as easy as possible to understand.

## What is an API?

Before sending requests to servers, it is relatively important to understand how a HTTP request works. For those who know what a HTTP request is and how it works, [click here ](#sending-http-requests)to skip this section.

The Hypertext Transfer Protocol (HTTP) is designed to enable communications between clients and servers. HTTP works as a request-response protocol between a client and server.

> **Example:** A client (browser) sends an HTTP request to the server; then the server returns a response to the client. The response contains status information about the request and may also contain the requested content.

## Request Methods

Simple enough right? Well, each HTTP request must be sent with a designated 'method'. Each method does different things and means different things. Annoying right? Yes, we know. A list of each request type/method can be found below.&#x20;

### Common Request Methods

{% tabs %}
{% tab title="GET" %}
GET is used to request data from a specified resource. This method cannot accept any bodies on the request. As such all query parameters must be sent in the URL. Like the example below:\
\ <mark style="color:red;">`/test/demo_form?name1=value1&name2=value2`</mark>

**Some notes on GET requests:**

* **GET** requests can be cached
* **GET** requests have length restrictions
* **GET** requests are only used to request data (not modify)
* **GET** requests cannot pass any data via the request body
  {% endtab %}

{% tab title="POST" %}

POST is used to send data to a server to create/update a resource. Most commonly used to 'post/send' data to a server, rather than update.

The data sent to the server with POST is stored in the request body of the HTTP request:

<figure><img src="/files/VJtASIcPzIiMAERobnxR" alt=""><figcaption><p>Request Body for a POST request in BotWiz</p></figcaption></figure>

As you can tell from the start, the request body works by sending key/value pairs in the request. Think of this as JSON keys and entries. As that is exactly what it is, BotWiz just removes the need to use {} or "" in the request. Taking something from this:

> ```json
> {
>    "key": "value"
> }
> ```

And turning it into:

> Key: key \
> Value: value

**Some notes on POST requests:**

* **POST** requests are never cached
* **POST** requests have no restrictions on data length
* **POST** requests transmit data via the request body object.
* POST requests can still send values via query params (In the URL)
  {% endtab %}

{% tab title="PUT" %}
PUT is used to send data to a server to create/update a resource.

The difference between POST and PUT is that PUT requests are idempotent. That is, calling the same PUT request multiple times will always produce the same result. In contrast, calling a POST request repeatedly have side effects of creating the same resource multiple times.
{% endtab %}

{% tab title="DELETE" %}
The DELETE method deletes the specified resource. This wont be as commonly used in BotWiz as typically it is only used if you control the data server for the resource you are sending the request to.
{% endtab %}

{% tab title="PATCH" %}
The PATCH method is used to apply partial modifications to a resource. This is commonly used in Discord endpoints in which you update a resource. Such as message, channel or guild, etc.
{% endtab %}
{% endtabs %}

### Not So Common Request Methods *(Not used in BotWiz)*

{% tabs %}
{% tab title="HEAD" %}
HEAD is almost identical to GET, but without the response body.

In other words, if GET /users returns a list of users, then HEAD /users will make the same request but will not return the list of users.

A HEAD request is useful for checking what a GET request will return before actually making a GET request - a HEAD request can read the Content-Length header to check the size of the file, without actually downloading the file.
{% endtab %}

{% tab title="OPTIONS" %}
The OPTIONS method describes the communication options for the target resource.
{% endtab %}

{% tab title="CONNECT" %}
The CONNECT method is used to start a two-way communications (almost like a tunnel) with the requested resource. This is different from a websocket.
{% endtab %}

{% tab title="TRACE" %}
The TRACE method is used to perform a message loop-back test that tests the path for the target resource (useful for debugging purposes).
{% endtab %}
{% endtabs %}

Now you know all the types, you can start to use HTTP requests more confidently. You can get started using the API block in BotWiz to send requests to servers.&#x20;

<figure><img src="/files/OZZayB9Ar2JJNN39lE01" alt=""><figcaption><p>API block in BotWiz</p></figcaption></figure>

## Sending HTTP Requests

To get started sending HTTP requests with BotWiz, you first need to add the API block to your command/event tree, the block is pictured above for reference. Once you have added the API block to your command/event tree, you can configure the request by clicking on the block itself to open the configuration menu.

<figure><img src="/files/4jTpBdX4sbMH2sny2zik" alt=""><figcaption><p>API block configuration menu</p></figcaption></figure>

### Setup Tab

Once open, you will be greeted by a couple different options, if this is your first time using HTTP requests, this may seem confusing at first glance. However, it is super simple to setup and use. On the first page 'Setup' which is open by default you will be greeted by 3 input boxes.&#x20;

* **Name**\
  The name of the API block, used to reference the response with {api\_**api\_name\_here**\[response]}
* URL\
  The URL/Address for the resource you are sending a request to
* Method\
  The [method/type](#request-methods) of request it will be

When picking a name for your API block, it is best to keep it simple, and note that it MUST be unique, you cannot have 2 or more API blocks in the same command/event with the same name, or this will confuse the responses and may lead to issues down the line.

### URL Parameters

The second page/tab you will see is the URL Parameters tab. This is used to add query params to your URL, used mainly for GET requests, but widely used across all methods which accept URL params.

<figure><img src="/files/ujds9vPn4MWvCYBuBASB" alt=""><figcaption><p>URL Parameters Tab</p></figcaption></figure>

The URL parameters are accepted in Key/Value form to keep it simple. To shorten it all down and keep it as simple as possible, essentially this will append the key and value to the end of the URL when sending the request. It could end up looking something like this:

<mark style="color:red;">`/test/demo_form?name1=value1&name2=value2`</mark>

### HTTP Headers

HTTP Headers are used to pass important data to the servers you are sending a request to, data such as: Authentication tokens, request data type, and other bits of information the server may need to respond and process your request correctly.&#x20;

This is most commonly used for stating the data type, and authenticating the request when using endpoints which require keys or tokens.&#x20;

{% hint style="danger" %}
**Never share any authentication key with anyone. Make sure to keep this secret at all times! BotWiz allows you to use {bot\_token} to send your bots token in an API request without the need to copy and paste it. Only use this variable in Discord APIs, other APIs do not need it.**
{% endhint %}

<figure><img src="/files/dIrEeSDKNmSc6OUslvVb" alt=""><figcaption><p>HTTP Headers Tab</p></figcaption></figure>

As you can see, this also works in a Key/Value pair. Exactly the same as the URL Parameters. This is also the same for Request Body, which is the next section we will cover.

### Request Body

The request body is usable on all request methods besides HEAD, and GET. The request body allows you to send data to the server, This data is sent as JSON and parsed on the receiving end. If you need to send data with your request, it will most likely be a POST or PUT request that uses the request body to send such data.

<figure><img src="/files/VvOCinS6PgpezHtfqErx" alt=""><figcaption><p>Request Body</p></figcaption></figure>

### Test Request

The test request tab is used to send a request to the server from the builder so you can see the response of the request. This is useful for testing the request, or viewing the data it will return so you can correctly reference it in your event or command.

Test requests send like a normal request, the only difference is it is sent by the builder and not the bot.

{% hint style="info" %}
**The use of any variables aside from&#x20;**<mark style="color:red;">**`{bot_token}`**</mark>**&#x20;will not work in a test request.**
{% endhint %}

## Retrieving Response Data

Once you have sent a successful request, you can use it's response in your commands or events. Note the requested data is specific to that interaction, meaning once the command or event finishes its trigger, the request data is deleted to make room for the next run.&#x20;

Request data cannot be transferred from one command, to another. Or one event, to another, unless you save the response from the HTTP call to a custom variable, however unless needed, it is advised you do not do this as storing data will mean it does not get updated without you specifically making it.

To display the data from the request you can use the API response variable, this looks like:

<mark style="color:red;">`{api_`</mark><mark style="color:red;">**`your_api_name`**</mark><mark style="color:red;">`[response]}`</mark>

Remember to replace 'your\_api\_name' with the name you have chosen for the API block when setting it up. After response you will use dot '.' notations to add another argument to the variable lick such:

<mark style="color:red;">`{api_`</mark><mark style="color:red;">**`your_api_name`**</mark><mark style="color:red;">`[response.example]}`</mark>

The above is an example of me retrieving the value stored in the 'example' key of the JSON response the server sends back. Everything that comes after response should match with what is returned in the response from the server the request was sent to. For example, I have sent a request and received this response:

```json
{
  "userId": 1,
  "id": 1,
  "title": "delectus aut autem",
  "completed": false
}
```

I want to access the title of this response, to do this i would write out the variable as such:

<mark style="color:red;">`{api_`</mark><mark style="color:red;">**`your api name`**</mark><mark style="color:red;">`[response.title]}`</mark>

This will retrieve the data from title and return "delectus aut autem".  When working with responses that return an array of objects, it is slightly different. Here is an example:

{% code title="Normal Object Response" %}

```json
{
  "userId": 1,
  "id": 1,
  "title": "delectus aut autem",
  "completed": false
}
```

{% endcode %}

{% code title="Response Object With Arrays" %}

```json
{
    "data": {
      "users": [
        {
          "firstName": "Bryan",
          "countryCode": "PW",
          "country": {
            "name": "Palau"
          },
          "company": {
            "name": "Mastercard"
          }
        },
        {
          "firstName": "Bryan",
          "countryCode": "CG",
          "country": {
            "name": "Congo (the)"
          },
          "company": {
            "name": "China Construction Bank"
          }
        },
        {
          "firstName": "Bryan",
          "countryCode": "BV",
          "country": {
            "name": "Bouvet Island"
          },
          "company": {
            "name": "Chevron"
          }
        }
      ],
      "countries": [
        {
          "iso3": "RUS"
        }
      ]
    }
  }
```

{% endcode %}

As you can see, there are some responses that have been returned as an array with objects inside them (Objects use <mark style="color:red;">`{}`</mark> and arrays use <mark style="color:red;">`[]`</mark>}. This is all in JSON format. Learn more about it [here](https://developer.mozilla.org/en-US/docs/Learn/JavaScript/Objects/JSON).

To access a value in an array, we must specify the arrays name, and the position of the object/data value in which we want. It is important to explain now that arrays ALWAYS start at 0. Now that we know this, lets say I want to access the second user in the users array (Bryan) and then retrieve the name of his country. This is how I would do it.

<mark style="color:red;">`{api_`</mark><mark style="color:red;">**`your api name`**</mark><mark style="color:red;">`[response.data.users.1.country.name]}`</mark>

As you can see, I have defined the index/position number for the user object I want to access. This is important when working with arrays, or the bot will not know which one to return, and instead will return null, the variable or even \[Object object].

Lets say I want to get the only object in the countries array. This is how I would do it:

<mark style="color:red;">`{api_`</mark><mark style="color:red;">**`your api name`**</mark><mark style="color:red;">`[response.data.countries.0.iso3]}`</mark>

This will return 'RUS' as the value.


---

# Agent Instructions: Querying This Documentation

If you need additional information that is not directly available in this page, you can query the documentation dynamically by asking a question.

Perform an HTTP GET request on the current page URL with the `ask` query parameter:

```
GET https://docs.botwiz.dev/docs/blocks/actions/action-blocks/api.md?ask=<question>
```

The question should be specific, self-contained, and written in natural language.
The response will contain a direct answer to the question and relevant excerpts and sources from the documentation.

Use this mechanism when the answer is not explicitly present in the current page, you need clarification or additional context, or you want to retrieve related documentation sections.
