# Introduction

## A CFML HTTP Builder

### Inspiration

Hyper was built after coding several API SDK's for various platforms — [S3SDK](https://github.com/coldbox-modules/s3sdk), [cbstripe](https://github.com/coldbox-modules/cbox-stripe), and [cbgithub](https://github.com/elpete/cbgithub), to name a few. We noticed that we spent a lot of time setting up the plumbing for the requests and a wrapper around `cfhttp`. Each implementation was mostly the same but slightly different. It was additionally frustrating because we really only needed to tweak a few values, usually just the `Authorization` header. It would be nice to create an HTTP client pre-configured for each of these SDK's. It seemed the perfect fit for a module.

### The problem it solves

Hyper exists to provide a fluent builder experience for HTTP requests and responses. It also provides a powerful way to create clients, i.e. Builder objects with pre-configured defaults like a base URL or certain headers.


# What's New?

## 6.1.0

Add [`head`](/6.1.0-1/making-requests/hyperrequest#head) and [`options`](/6.1.0-1/making-requests/hyperrequest#options) shortcut methods.

## 6.0.0

* Add `xml` support and an `asXML` method to set the body format and `Content-Type` header.
* Add `adobe@2023` to testing matrix.

### Breaking Changes

* Remove default `Content-Type` header. You must set this [manually](/6.1.0-1/making-requests/hyperrequest#setcontenttype) or use a format helper, such as [`asJson`](/6.1.0-1/making-requests/hyperrequest#asjson).
* Dropped `adobe@2016` support.

## 5.0.1

Correctly handle cases when the `body` is a string and format is `JSON`.

## 5.0.0

Add a `debug` method to see what the HTTP client generates.

### Breaking Changes

`HyperHttpClientInterface` now requires a `debug` method.

```cfscript
/**
 * Return a struct of information showing how the client will execute the HyperRequest.
 * This will be used by a developer to debug any differences between the generated
 * request values and the expected request values.
 *
 * @req     The HyperRequest to debug.
 *
 * @returns A struct of information detailing how the client would execute the HyperRequest.
 */
public struct function debug( required HyperRequest req );
```

## 4.0.3

* Do not prepend the base url when a full url is passed.
* Add `resolveUrls` and `encodeUrl` properties to the [memento](/6.1.0-1/making-requests/hyperrequest#getmemento).
* Correctly set the `encodeUrl` property when cloning a request.

## 4.0.2

Update README for builder `initWith` headers losing `Content-Type`.

## 4.0.1

Fix `HyperBuilder` example in the docs.

## 4.0.0

Allow adding multiple query params with the same key.

### Breaking Changes

Previously, query params were stored as a struct.  Some APIs expect multiple values for the same query param name to be passed as separate arguments.  Hyper now stores the query params as an array and provides new methods for interacting with query params:

* [`getQueryParamByName`](/6.1.0-1/making-requests/hyperrequest#getqueryparambyname)
* [`getAllQueryParamsByName`](/6.1.0-1/making-requests/hyperrequest#getallqueryparamsbyname)
* [`withQueryParams`](/6.1.0-1/making-requests/hyperrequest#withqueryparams)
* [`appendQueryParam`](/6.1.0-1/making-requests/hyperrequest#appendqueryparam)
* [`appendQueryParams`](/6.1.0-1/making-requests/hyperrequest#appendqueryparams)
* [`hasQueryParam`](/6.1.0-1/making-requests/hyperrequest#hasqueryparam)

The following methods still exist, but now interact with arrays of query param structs instead of a simple struct.

* [`getQueryParams`](/6.1.0-1/making-requests/hyperrequest#getqueryparams)
* [`setQueryParams`](/6.1.0-1/making-requests/hyperrequest#setqueryparams)

The following methods have been deprecated:

| Deprecated Method                                                      | Replacement Method                                                                 |
| ---------------------------------------------------------------------- | ---------------------------------------------------------------------------------- |
| [`getQueryParam`](/6.1.0-1/making-requests/hyperrequest#getqueryparam) | [`getQueryParamByName`](/6.1.0-1/making-requests/hyperrequest#getqueryparambyname) |

## 3.6.2

Convert array values correctly when sending form fields

## 3.6.1

Add a workaround for CommandBox not having the `box:asyncManager` injection DSL.

## 3.6.0

Add async requests using ColdBox's [AsyncManager](https://coldbox.ortusbooks.com/digging-deeper/promises-async-programming).

## 3.5.0

* Provide more useful error than cfhttp when [`throwOnErrors`](/6.1.0-1/making-requests/hyperrequest#throwerrors) is enabled.
* Provide mementos for [HyperRequest](/6.1.0-1/making-requests/hyperrequest#getmemento) and [HyperResponse](/6.1.0-1/making-requests/hyperresponse#getmemento) instances.
* Capture [statusText](/6.1.0-1/making-requests/hyperresponse#getstatustext) and provide a [status](/6.1.0-1/making-requests/hyperresponse#getstatus) convenience string.

## 3.4.2

Add MIT License file

## 3.4.1

Use `processState` over `announce` until CommandBox can update its `interceptorService`.

## 3.4.0

### HyperRequest

* Add [`forwardHeaders`](/6.1.0-1/making-requests/hyperrequest#forwardheaders) shortcut method.

### HyperResponse

* Allow for default values in [`getHeader`](/6.1.0-1/making-requests/hyperresponse#getheader).
* Add helper methods for checking for specific status codes:
  * [`isOk`](/6.1.0-1/making-requests/hyperresponse#isok)
  * [`isUnauthorized`](/6.1.0-1/making-requests/hyperresponse#isunauthorized)
  * [`isForbidden`](/6.1.0-1/making-requests/hyperresponse#isforbidden)
  * [`isNotFound`](/6.1.0-1/making-requests/hyperresponse#isnotfound)

## 3.3.0

Allowing [attaching](/6.1.0-1/making-requests/hyperrequest#attach) file uploads.

## 3.2.1

Support WireBox outside of ColdBox.

## 3.2.0

Include response data as detail in `DeserializeJsonException`.

## 3.1.0

* Add [`clone`](/6.1.0-1/making-requests/hyperrequest#clone) to quickly copy `HyperRequest` instances.
* Add interceptors and [local](/6.1.0-1/making-requests/hyperrequest#withrequestcallback) [callbacks](/6.1.0-1/making-requests/hyperrequest#withresponsecallback) for lifecycle events.

## 3.0.0

Add execution time to `HyperResponse` instances.

### Breaking Changes

Dropped support for ColdBox 5.

## 2.3.11

* Add support for [NTLM authentication](/6.1.0-1/making-requests/hyperrequest#withntlmauth).
* Include [`getFullURL`](/6.1.0-1/making-requests/hyperrequest#getfullurl) method in docs.

## 2.3.10

Fixed typo of `Bulider` to `Builder`.

## 2.3.9

Add [`withoutEncodingUrl`](/6.1.0-1/making-requests/hyperrequest#withoutencodingurl) flag.

## 2.3.8

Do not fail fast on cron job actions on CI.

## 2.3.7

Update fetch-depth for tests and release actions on CI.

## 2.3.6

Attempt to skip committing back changes on CI.

## 2.3.5

Add matrix and cron testing on CI.

## 2.3.4

Use better GitHub token on CI

## 2.3.1

Add workaround for `boolean` values in query strings.

## 2.3.0

Add [certificate](/6.1.0-1/making-requests/hyperrequest#withcertificateauth) auth.

## 2.2.1

Use the previous host for redirect if redirect does not include a full URL.

## 2.2.0

Add [`resolveUrls`](/6.1.0-1/making-requests/hyperrequest#setresolveurl) flag.

## 2.1.1

* Use OpenJDK instead of OracleJDK on CI.
* Store module in [ForgeBox Storage](https://commandbox.ortusbooks.com/5.6.0/developing-for-commandbox/commands).

## 2.1.0

Allow for pluggable [HTTP Clients](/6.1.0-1/customizing-hyper/custom-http-clients) that follow the `HyperHttpClientInterface`. (Clients do not need to use the `implements` keyword.)

## 2.0.2

Avoid double encoding using [`cfhttpparam`](https://cfdocs.org/cfhttpparam).

## 2.0.1

Remove Lucee 4.5 support from docs. (Support was dropped in [v2.0.0](#2.0.0))

## 2.0.0

* Do not include [`username`](/6.1.0-1/making-requests/hyperrequest#setusername) and [`password`](/6.1.0-1/making-requests/hyperrequest#setpassword) unless they have values.
* Add `adobe@2018` support to CI builds.

### Breaking Changes

Dropped support for `lucee@4.5`.

## 1.15.0

Add [`throwOnError`](/6.1.0-1/making-requests/hyperrequest#throwerrors) flag.

## 1.14.5

Use `504 Gateway Timeout` for incomplete responses.

## 1.14.4

Include equal signs in query param values.

## 1.14.0 – 1.0.0

### New Features

* Add [`when`](/6.1.0-1/making-requests/hyperrequest#when) helper to execute conditions without breaking chaining.
* Add [`clear`](/6.1.0-1/making-requests/hyperrequest#clear) method to reset HyperRequest instances.
* Add configurable [`timeout`](/6.1.0-1/making-requests/hyperrequest#settimeout).

### Bug Fixes

* Fix for Lucee 4 compatibility on `LinkedHashMaps` and `keyArray`.
* Preserve case in header names.
* Preserve case for query parameters.
* Serialize both params from the url and set on the `HyperRequest` instance.
* Default to `UTF-8` charset if none is present in the response.
* Fix withHeaders and withQueryParams for Lucee compatibility.
* Only map HyperBuilder as a singleton in WireBox

### Other

* Migrate to [coldbox-modules](https://github.com/coldbox-modules) organization on GitHub.
* Update `box.json` description.
* Enable [CommandBox Semantic Release](https://forgebox.io/view/commandbox-semantic-release) on CI.


# Upgrade Guide

## Upgrading from v5 to v6

* The default `Content-Type` header has been removed. You must set this [manually](/6.1.0-1/making-requests/hyperrequest#setcontenttype) or use a format helper, such as [`asJson`](/6.1.0-1/making-requests/hyperrequest#asjson).
* Dropped support for Adobe 2016.

## Upgrading from v4 to v5

`HyperHttpClientInterface` now requires a `debug` method.

```cfscript
/**
 * Return a struct of information showing how the client will execute the HyperRequest.
 * This will be used by a developer to debug any differences between the generated
 * request values and the expected request values.
 *
 * @req     The HyperRequest to debug.
 *
 * @returns A struct of information detailing how the client would execute the HyperRequest.
 */
public struct function debug( required HyperRequest req );
```

## Upgrading from v3 to v4

Previously, query params were stored as a struct.  Some APIs expect multiple values for the same query param name to be passed as separate arguments.  Hyper now stores the query params as an array and provides new methods for interacting with query params:

* [`getQueryParamByName`](/6.1.0-1/making-requests/hyperrequest#getqueryparambyname)
* [`getAllQueryParamsByName`](/6.1.0-1/making-requests/hyperrequest#getallqueryparamsbyname)
* [`withQueryParams`](/6.1.0-1/making-requests/hyperrequest#withqueryparams)
* [`appendQueryParam`](/6.1.0-1/making-requests/hyperrequest#appendqueryparam)
* [`appendQueryParams`](/6.1.0-1/making-requests/hyperrequest#appendqueryparams)
* [`hasQueryParam`](/6.1.0-1/making-requests/hyperrequest#hasqueryparam)

The following methods still exist, but now interact with arrays of query param structs instead of a simple struct.

* [`getQueryParams`](/6.1.0-1/making-requests/hyperrequest#getqueryparams)
* [`setQueryParams`](/6.1.0-1/making-requests/hyperrequest#setqueryparams)

The following methods have been deprecated:

| Deprecated Method                                                      | Replacement Method                                                                 |
| ---------------------------------------------------------------------- | ---------------------------------------------------------------------------------- |
| [`getQueryParam`](/6.1.0-1/making-requests/hyperrequest#getqueryparam) | [`getQueryParamByName`](/6.1.0-1/making-requests/hyperrequest#getqueryparambyname) |

## Upgrading from v2 to v3

Dropped support for ColdBox 5.

## Upgrading from v1 to v2

Dropped support for Lucee 4.5.


# Requirements

Hyper runs on Adobe ColdFusion 2018+ and Lucee 5+.

ColdBox is not required, but mappings are provided for ColdBox users automatically.


# Installation

Hyper is most easily installed via ForgeBox and CommandBox.

```sh
box install hyper
```

If you install Hyper in a non-ColdBox application, make sure to create a mapping in your `Application.cfc`

```cfscript
this.mappings[ "/hyper" ] = expandPath( "/modules/hyper" );
```


# HyperBuilder

A `HyperBuilder` is a singleton factory component that will give you a new [`HyperRequest`](/6.1.0-1/making-requests/hyperrequest) any time you call the `new` method.  It will also create a new [`HyperRequest`](/6.1.0-1/making-requests/hyperrequest) any time you call a method on `HyperBuilder` that exists on [`HyperRequest`](/6.1.0-1/making-requests/hyperrequest).

`HyperBuilder` is the component you want to inject into your singleton components, like handlers or services.  It will ensure you get a fresh [`HyperRequest`](/6.1.0-1/making-requests/hyperrequest) instance on each invocation.  This is important since reusing the same [`HyperRequest`](/6.1.0-1/making-requests/hyperrequest) instance will likely produce unintended results.

You can inject a `HyperBuilder` into your application using the `HyperBuilder@hyper` id.

```cfscript
component {
    
    property name="hyper" inject="HyperBuilder@hyper";

    function index( event, rc, prc ) {
        var reqA = hyper.new();
        // reqA is a new HyperRequest instance.
        
        var reqB = hyper.setUrl( "https://swapi.dev/api/people" );
        // reqB is a new HyperRequest instance with the url set.
    }

}
```

If you are not using ColdBox, you can create a `HyperBuilder` manually:

```cfscript
component {

    function init() {
        variables.hyper = new hyper.models.HyperBuilder();
    }

}
```


# HyperRequest

Though the [`HyperBuilder`](/6.1.0-1/making-requests/hyperbuilder) is the component you will most likely inject, `HyperRequest` is the component will you interact with the most. `HyperRequest` provides a fluent interface to configure your HTTP call.

```cfscript
hyper.get( "https//api.github.com/users" );

hyper.setMethod( "PUT" )
    .withHeaders( { "Authorization" = "Bearer #token#" } )
    .setUrl( "https://jsonplaceholder.typicode.com/posts/1" )
    .setBody( {
        title: "New Title"
    } )
    .send();
```

## Defaults

The following are default properties for a `HyperRequest`:

```json
{
    "method": "GET"
    "resolveUrls": false,
    "encodeUrl": true,
    "timeout": 10, // in seconds
    "maximumRedirects": "*", // follow redirects indefinitely
    "bodyFormat": "json",
    "throwOnError": false
}
```

## Executing Requests

### `get`

Execute a `GET` request and return a [`HyperResponse`](/6.1.0-1/making-requests/hyperresponse).

| Name        | Type   | Required | Default | Description                                                    |
| ----------- | ------ | -------- | ------- | -------------------------------------------------------------- |
| url         | string | false    | null    | An optional URL to set for the request.                        |
| queryParams | struct | false    | null    | An optional struct of query parameters to set for the request. |

**Return**: [`HyperResponse`](/6.1.0-1/making-requests/hyperresponse)

### `getAsync`

Execute a `GET` request asynchronously. Returns a [ColdBox Future](https://coldbox.ortusbooks.com/digging-deeper/promises-async-programming) that returns a [`HyperResponse`](/6.1.0-1/making-requests/hyperresponse).

| Name        | Type   | Required | Default | Description                                                    |
| ----------- | ------ | -------- | ------- | -------------------------------------------------------------- |
| url         | string | false    | null    | An optional URL to set for the request.                        |
| queryParams | struct | false    | null    | An optional struct of query parameters to set for the request. |

**Return**: [`Future`](https://coldbox.ortusbooks.com/digging-deeper/promises-async-programming)`<`[`HyperResponse`](/6.1.0-1/making-requests/hyperresponse)`>`

### `post`

Execute a `POST` request and return a [`HyperResponse`](/6.1.0-1/making-requests/hyperresponse).

| Name | Type   | Required | Default | Description                              |
| ---- | ------ | -------- | ------- | ---------------------------------------- |
| url  | string | false    | null    | An optional URL to set for the request.  |
| body | struct | false    | null    | An optional body to set for the request. |

**Return**: [`HyperResponse`](/6.1.0-1/making-requests/hyperresponse)

### `postAsync`

Execute a `POST` request asynchronously. Returns a [ColdBox Future](https://coldbox.ortusbooks.com/digging-deeper/promises-async-programming) that returns a [`HyperResponse`](/6.1.0-1/making-requests/hyperresponse).

| Name | Type   | Required | Default | Description                              |
| ---- | ------ | -------- | ------- | ---------------------------------------- |
| url  | string | false    | null    | An optional URL to set for the request.  |
| body | struct | false    | null    | An optional body to set for the request. |

**Return**: [`Future`](https://coldbox.ortusbooks.com/digging-deeper/promises-async-programming)`<`[`HyperResponse`](/6.1.0-1/making-requests/hyperresponse)`>`

### `put`

Execute a `PUT` request and return a [`HyperResponse`](/6.1.0-1/making-requests/hyperresponse).

| Name | Type   | Required | Default | Description                              |
| ---- | ------ | -------- | ------- | ---------------------------------------- |
| url  | string | false    | null    | An optional URL to set for the request.  |
| body | struct | false    | null    | An optional body to set for the request. |

**Return**: [`HyperResponse`](/6.1.0-1/making-requests/hyperresponse)

### `putAsync`

Execute a `PUT` request asynchronously. Returns a [ColdBox Future](https://coldbox.ortusbooks.com/digging-deeper/promises-async-programming) that returns a [`HyperResponse`](/6.1.0-1/making-requests/hyperresponse).

| Name | Type   | Required | Default | Description                              |
| ---- | ------ | -------- | ------- | ---------------------------------------- |
| url  | string | false    | null    | An optional URL to set for the request.  |
| body | struct | false    | null    | An optional body to set for the request. |

**Return**: [`Future`](https://coldbox.ortusbooks.com/digging-deeper/promises-async-programming)`<`[`HyperResponse`](/6.1.0-1/making-requests/hyperresponse)`>`

### `patch`

Execute a `PATCH` request and return a [`HyperResponse`](/6.1.0-1/making-requests/hyperresponse).

| Name | Type   | Required | Default | Description                              |
| ---- | ------ | -------- | ------- | ---------------------------------------- |
| url  | string | false    | null    | An optional URL to set for the request.  |
| body | struct | false    | null    | An optional body to set for the request. |

**Return**: [`HyperResponse`](/6.1.0-1/making-requests/hyperresponse)

### `patchAsync`

Execute a `PATCH` request asynchronously. Returns a [ColdBox Future](https://coldbox.ortusbooks.com/digging-deeper/promises-async-programming) that returns a [`HyperResponse`](/6.1.0-1/making-requests/hyperresponse).

| Name | Type   | Required | Default | Description                              |
| ---- | ------ | -------- | ------- | ---------------------------------------- |
| url  | string | false    | null    | An optional URL to set for the request.  |
| body | struct | false    | null    | An optional body to set for the request. |

**Return**: [`Future`](https://coldbox.ortusbooks.com/digging-deeper/promises-async-programming)`<`[`HyperResponse`](/6.1.0-1/making-requests/hyperresponse)`>`

### `delete`

Execute a `DELETE` request and return a [`HyperResponse`](/6.1.0-1/making-requests/hyperresponse).

| Name | Type   | Required | Default | Description                              |
| ---- | ------ | -------- | ------- | ---------------------------------------- |
| url  | string | false    | null    | An optional URL to set for the request.  |
| body | struct | false    | null    | An optional body to set for the request. |

**Return**: [`HyperResponse`](/6.1.0-1/making-requests/hyperresponse)

### `deleteAsync`

Execute a `DELETE` request asynchronously. Returns a [ColdBox Future](https://coldbox.ortusbooks.com/digging-deeper/promises-async-programming) that returns a [`HyperResponse`](/6.1.0-1/making-requests/hyperresponse).

| Name | Type   | Required | Default | Description                              |
| ---- | ------ | -------- | ------- | ---------------------------------------- |
| url  | string | false    | null    | An optional URL to set for the request.  |
| body | struct | false    | null    | An optional body to set for the request. |

**Return**: [`Future`](https://coldbox.ortusbooks.com/digging-deeper/promises-async-programming)`<`[`HyperResponse`](/6.1.0-1/making-requests/hyperresponse)`>`

### `head`

Execute a `HEAD` request and return a [`HyperResponse`](/6.1.0-1/making-requests/hyperresponse).

| Name        | Type   | Required | Default | Description                                                    |
| ----------- | ------ | -------- | ------- | -------------------------------------------------------------- |
| url         | string | false    | null    | An optional URL to set for the request.                        |
| queryParams | struct | false    | null    | An optional struct of query parameters to set for the request. |

**Return**: [`HyperResponse`](/6.1.0-1/making-requests/hyperresponse)

### `headAsync`

Execute a `HEAD` request asynchronously. Returns a [ColdBox Future](https://coldbox.ortusbooks.com/digging-deeper/promises-async-programming) that returns a [`HyperResponse`](/6.1.0-1/making-requests/hyperresponse).

| Name        | Type   | Required | Default | Description                                                    |
| ----------- | ------ | -------- | ------- | -------------------------------------------------------------- |
| url         | string | false    | null    | An optional URL to set for the request.                        |
| queryParams | struct | false    | null    | An optional struct of query parameters to set for the request. |

**Return**: [`Future`](https://coldbox.ortusbooks.com/digging-deeper/promises-async-programming)`<`[`HyperResponse`](/6.1.0-1/making-requests/hyperresponse)`>`

### `options`

Execute an `OPTIONS` request and return a [`HyperResponse`](/6.1.0-1/making-requests/hyperresponse).

| Name        | Type   | Required | Default | Description                                                    |
| ----------- | ------ | -------- | ------- | -------------------------------------------------------------- |
| url         | string | false    | null    | An optional URL to set for the request.                        |
| queryParams | struct | false    | null    | An optional struct of query parameters to set for the request. |

**Return**: [`HyperResponse`](/6.1.0-1/making-requests/hyperresponse)

### `optionsAsync`

Execute an `OPTIONS` request asynchronously. Returns a [ColdBox Future](https://coldbox.ortusbooks.com/digging-deeper/promises-async-programming) that returns a [`HyperResponse`](/6.1.0-1/making-requests/hyperresponse).

| Name        | Type   | Required | Default | Description                                                    |
| ----------- | ------ | -------- | ------- | -------------------------------------------------------------- |
| url         | string | false    | null    | An optional URL to set for the request.                        |
| queryParams | struct | false    | null    | An optional struct of query parameters to set for the request. |

**Return**: [`Future`](https://coldbox.ortusbooks.com/digging-deeper/promises-async-programming)`<`[`HyperResponse`](/6.1.0-1/making-requests/hyperresponse)`>`

### `send`

Send the HTTP request and return a [`HyperResponse`](/6.1.0-1/making-requests/hyperresponse).

| Name         | Type | Required | Default | Description |
| ------------ | ---- | -------- | ------- | ----------- |
| No arguments |      |          |         |             |

**Return**: [`HyperResponse`](/6.1.0-1/making-requests/hyperresponse)

### `sendAsync`

Send the HTTP request asynchronously and return a [ColdBox Future](https://coldbox.ortusbooks.com/digging-deeper/promises-async-programming) that will resolve to a [`HyperResponse`](/6.1.0-1/making-requests/hyperresponse).

| Name         | Type | Required | Default | Description |
| ------------ | ---- | -------- | ------- | ----------- |
| No arguments |      |          |         |             |

**Return**: [`Future`](https://coldbox.ortusbooks.com/digging-deeper/promises-async-programming)`<`[`HyperResponse`](/6.1.0-1/making-requests/hyperresponse)`>`

## Building Requests

### `getRequestId`

Gets the unique request ID representing this request.

| Name         | Type | Required | Default | Description |
| ------------ | ---- | -------- | ------- | ----------- |
| No arguments |      |          |         |             |

**Return**: `String`

### `getFullURL`

Gets the full URL for the request.

| Name            | Type    | Required | Default | Description                                            |
| --------------- | ------- | -------- | ------- | ------------------------------------------------------ |
| withQueryString | boolean | false    | false   | Includes the configured query string with the full URL |

**Return**: `String`

### `getBaseURL`

Gets the base URL for the request. The base URL is combined with the URL when making the request.

| Name         | Type | Required | Default | Description |
| ------------ | ---- | -------- | ------- | ----------- |
| No arguments |      |          |         |             |

**Return**: `String`

### `setBaseURL`

Sets the base URL for the request. The base URL is combined with the URL when making the request.

| Name  | Type   | Required | Default | Description                                                   |
| ----- | ------ | -------- | ------- | ------------------------------------------------------------- |
| value | string | true     |         | The base URL for the request, e.g. `https://api.github.com/`. |

**Return**: `HyperRequest`

### `getURL`

Gets the URL for the request.

| Name         | Type | Required | Default | Description |
| ------------ | ---- | -------- | ------- | ----------- |
| No arguments |      |          |         |             |

**Return**: `String`

### `setURL`

Sets the URL for the request.

| Name  | Type   | Required | Default | Description                                                                                                     |
| ----- | ------ | -------- | ------- | --------------------------------------------------------------------------------------------------------------- |
| value | string | true     |         | The URL for the request. It can either be a full url or a URI resource for use with the baseURL. e.g. `/repos`. |

**Return**: `HyperRequest`

### `setResolveURL`

Sets the resolveURL parameter for the request.

| Name  | Type    | Required | Default | Description                                                                    |
| ----- | ------- | -------- | ------- | ------------------------------------------------------------------------------ |
| value | boolean | false    | false   | Resolves URLs in the response body to absolute URLs, including the port number |

**Return**: `HyperRequest`

### `getMethod`

Gets the HTTP method for the request.

| Name         | Type | Required | Default | Description |
| ------------ | ---- | -------- | ------- | ----------- |
| No arguments |      |          |         |             |

**Return**: `String`

### `setMethod`

Sets the HTTP method for the request.

| Name  | Type   | Required | Default | Description                      |
| ----- | ------ | -------- | ------- | -------------------------------- |
| value | string | true     |         | The HTTP method for the request. |

**Return**: `HyperRequest`

### `withBasicAuth`

Sets the username and password for HTTP Basic Auth.

| Name     | Type   | Required | Default | Description                      |
| -------- | ------ | -------- | ------- | -------------------------------- |
| username | string | true     |         | The username for the basic auth. |
| password | string | true     |         | The password for the basic auth. |

**Return**: `HyperRequest`

### `withCertificateAuth`

Sets the username and password for HTTP Basic Auth.

| Name            | Type   | Required | Default | Description                                              |
| --------------- | ------ | -------- | ------- | -------------------------------------------------------- |
| certificatePath | string | true     |         | The mapped path to the certificate used to authenticate. |
| password        | string | false    |         | The optional password used to decrypt the certificate.   |

**Return**: `HyperRequest`

### `withNTLMAuth`

Sets the username, password, domain and workstation for NTLM Auth.

| Name        | Type   | Required | Default | Description                        |
| ----------- | ------ | -------- | ------- | ---------------------------------- |
| username    | string | true     |         | The username for the NTLM auth.    |
| password    | string | true     |         | The password for the NTLM auth.    |
| domain      | string | true     |         | The domain for the NTLM auth.      |
| workstation | string | true     |         | The workstation for the NTLM auth. |

Workstation can be obtained with `createObject('java','java.net.InetAddress').getLocalHost().getHostName()`

**Return**: `HyperRequest`

### `withRequestCallback`

Schedules a callback to be ran when executing the request.

| Name     | Type     | Required | Default | Description                                     |
| -------- | -------- | -------- | ------- | ----------------------------------------------- |
| callback | function | true     |         | The callback to run when executing the request. |

**Return**: `HyperRequest`

### `withResponseCallback`

Schedules a callback to be ran when receiving the response.

| Name     | Type     | Required | Default | Description                                      |
| -------- | -------- | -------- | ------- | ------------------------------------------------ |
| callback | function | true     |         | The callback to run when receiving the response. |

**Return**: `HyperRequest`

### `getUsername`

Gets the username for the request.

| Name         | Type | Required | Default | Description |
| ------------ | ---- | -------- | ------- | ----------- |
| No arguments |      |          |         |             |

**Return**: `String`

### `setUsername`

Sets the username for the request.

| Name  | Type   | Required | Default | Description                   |
| ----- | ------ | -------- | ------- | ----------------------------- |
| value | string | true     |         | The username for the request. |

**Return**: `HyperRequest`

### `getPassword`

Gets the password for the request.

| Name         | Type | Required | Default | Description |
| ------------ | ---- | -------- | ------- | ----------- |
| No arguments |      |          |         |             |

**Return**: `String`

### `setPassword`

Sets the password for the request.

| Name  | Type   | Required | Default | Description                   |
| ----- | ------ | -------- | ------- | ----------------------------- |
| value | string | true     |         | The password for the request. |

**Return**: `HyperRequest`

### `getTimeout`

Gets the timeout for the request, in seconds.

| Name         | Type | Required | Default | Description |
| ------------ | ---- | -------- | ------- | ----------- |
| No arguments |      |          |         |             |

**Return**: `numeric`

### `setTimeout`

Sets the timeout for the request, in seconds.

| Name  | Type   | Required | Default | Description                              |
| ----- | ------ | -------- | ------- | ---------------------------------------- |
| value | string | true     |         | The timeout for the request, in seconds. |

**Return**: `HyperRequest`

### `withoutRedirecting`

A convenience method to not follow any redirects.

| Name         | Type | Required | Default | Description |
| ------------ | ---- | -------- | ------- | ----------- |
| No arguments |      |          |         |             |

**Return**: `HyperRequest`

### `withoutEncodingUrl`

A convenience method to not encode the url.

{% hint style="warning" %}
**WARNING**: Not supported on Adobe engines.
{% endhint %}

| Name         | Type | Required | Default | Description |
| ------------ | ---- | -------- | ------- | ----------- |
| No arguments |      |          |         |             |

**Return**: `HyperRequest`

### `getMaximumRedirects`

Gets the maximum number of redirects to follow.

| Name         | Type | Required | Default | Description |
| ------------ | ---- | -------- | ------- | ----------- |
| No arguments |      |          |         |             |

**Return**: `numeric | String`

### `setMaximumRedirects`

Sets the maximum number of redirects to follow. A value of `*` will follow redirects infinitely.

| Name  | Type | Required | Default | Description                                |
| ----- | ---- | -------- | ------- | ------------------------------------------ |
| value | any  | true     |         | The maximum number of redirects to follow. |

**Return**: `HyperRequest`

### `getBody`

Gets the body for the request.

| Name         | Type | Required | Default | Description |
| ------------ | ---- | -------- | ------- | ----------- |
| No arguments |      |          |         |             |

**Return**: `any`

### `setBody`

Sets the body for the request. Complex values will be serialized before sending the request.

| Name  | Type | Required | Default | Description               |
| ----- | ---- | -------- | ------- | ------------------------- |
| value | any  | true     |         | The body for the request. |

**Return**: `HyperRequest`

### `hasBody`

Checks if the request has a body.

| Name         | Type | Required | Default | Description |
| ------------ | ---- | -------- | ------- | ----------- |
| No arguments |      |          |         |             |

**Return**: `boolean`

### `getBodyFormat`

Gets the body format for the request.

| Name         | Type | Required | Default | Description |
| ------------ | ---- | -------- | ------- | ----------- |
| No arguments |      |          |         |             |

**Return**: `String`

### `setBodyFormat`

Sets the body format for the request. Recognized values are `formFields`, `json`, or `xml`. It is highly recommended to use `asFormFields`, `asJson`, or `asXML` instead.  If you set this value to a non-recognized value, the body will be passed along as-is to the body of the HTTP request.

| Name  | Type | Required | Default | Description                      |
| ----- | ---- | -------- | ------- | -------------------------------- |
| value | any  | true     |         | The body format for the request. |

**Return**: `HyperRequest`

### `asJson`

A convenience method to set the body format and Content-Type to `json`.

| Name         | Type | Required | Default | Description |
| ------------ | ---- | -------- | ------- | ----------- |
| No arguments |      |          |         |             |

**Return**: `HyperRequest`

### `asFormFields`

A convenience method to set the body format and Content-Type to form fields.

| Name         | Type | Required | Default | Description |
| ------------ | ---- | -------- | ------- | ----------- |
| No arguments |      |          |         |             |

**Return**: `HyperRequest`

### `asXML`

A convenience method to set the body format and Content-Type to `xml`.

| Name         | Type | Required | Default | Description |
| ------------ | ---- | -------- | ------- | ----------- |
| No arguments |      |          |         |             |

**Return**: `HyperRequest`

### `getReferrer`

Gets the referrer for the request, if any.

| Name         | Type | Required | Default | Description |
| ------------ | ---- | -------- | ------- | ----------- |
| No arguments |      |          |         |             |

**Return**: `String`

### `getHeaders`

Gets the headers for the request.

| Name         | Type | Required | Default | Description |
| ------------ | ---- | -------- | ------- | ----------- |
| No arguments |      |          |         |             |

**Return**: `java.util.LinkedHashMap`

### `setHeaders`

Sets the headers for the request.

| Name  | Type   | Required | Default | Description                  |
| ----- | ------ | -------- | ------- | ---------------------------- |
| value | struct | true     |         | The headers for the request. |

**Return**: `HyperRequest`

### `setHeader`

Set a header for the request.

| Name  | Type   | Required | Default | Description              |
| ----- | ------ | -------- | ------- | ------------------------ |
| name  | string | true     |         | The name of the header.  |
| value | string | true     |         | The value of the header. |

**Return**: `HyperRequest`

### `withHeaders`

Add additional headers to the request.

| Name    | Type   | Required | Default | Description                                |
| ------- | ------ | -------- | ------- | ------------------------------------------ |
| headers | struct | true     |         | A struct of headers to add to the request. |

**Return**: `HyperRequest`

### `forwardHeaders`

Adds specified headers to the request if they exist. Usually used in conjunction with the current CFML request headers.

| Name    | Type   | Required | Default                               | Description                                                                           |
| ------- | ------ | -------- | ------------------------------------- | ------------------------------------------------------------------------------------- |
| names   | array  | true     |                                       | An array of header names to add to the request if they exist in the `headers` struct. |
| headers | struct | false    | `getHTTPRequestData( false ).headers` | A struct of headers to inspect.                                                       |

**Return**: `HyperRequest`

### `hasHeader`

Check if the request has a header with the given name.

| Name | Type   | Required | Default | Description                      |
| ---- | ------ | -------- | ------- | -------------------------------- |
| name | string | true     |         | The name of the header to check. |

**Return**: `boolean`

### `setContentType`

A convenience method to set the [`Content-Type` header](https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Content-Type).

| Name | Type   | Required | Default | Description                            |
| ---- | ------ | -------- | ------- | -------------------------------------- |
| type | string | true     |         | The Content-Type value for the request |

**Return**: `HyperRequest`

### `setAccept`

A convenience method to set the [`Accept` header](https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Accept).

| Name | Type   | Required | Default | Description                      |
| ---- | ------ | -------- | ------- | -------------------------------- |
| type | string | true     |         | The Accept value for the request |

**Return**: `HyperRequest`

### `getQueryParams`

Gets the query parameters for the request.

{% hint style="warning" %}
This method returns an array of param structs that is used under the hood by Hyper. You probably want to use [`getQueryParamByName`](#getqueryparambyname) or [`getAllQueryParamsByName`](#getallqueryparamsbyname) instead.
{% endhint %}

| Name         | Type | Required | Default | Description |
| ------------ | ---- | -------- | ------- | ----------- |
| No arguments |      |          |         |             |

**Return**: `array<struct<string, any>>`

### `setQueryParams`

Sets the query parameters for the request.

{% hint style="warning" %}
This method accepts an array of param structs that is used under the hood by Hyper. You probably want to use [`withQueryParams`](#withqueryparams) or [`appendQueryParams`](#appendqueryparams) instead.
{% endhint %}

If needed, param structs have two keys, `name` and `value`.

| Name  | Type  | Required | Default | Description                                                |
| ----- | ----- | -------- | ------- | ---------------------------------------------------------- |
| value | array | true     |         | The query parameters for the as an array of param structs. |

**Return**: `HyperRequest`

### `getQueryParam`

{% hint style="danger" %}
**DEPRECATED:** Use [`getQueryParamByName`](#getqueryparambyname)
{% endhint %}

Gets the first value for a certain query parameter. Returns an empty string if the query parameter does not exist.

| Name | Type   | Required | Default | Description                                                  |
| ---- | ------ | -------- | ------- | ------------------------------------------------------------ |
| name | string | true     |         | The name of the query parameter to retrieve the first value. |

**Return**: `any`

### `getQueryParamByName`

Gets the first value for a certian query parameter. Returns an empty string if the query parameter does not exist.

| Name | Type   | Required | Default | Description                                                  |
| ---- | ------ | -------- | ------- | ------------------------------------------------------------ |
| name | string | true     |         | The name of the query parameter to retrieve the first value. |

**Return**: `any`

### `getAllQueryParamsByName`

Get all the values for a certain query parameter. Returns an empty array if the query parameter does not exist.

| Name | Type   | Required | Default | Description                                                    |
| ---- | ------ | -------- | ------- | -------------------------------------------------------------- |
| name | string | true     |         | The name of the query parameter to retrieve all of its values. |

**Return**: `array<any>`

### `setQueryParam`

Set a query parameter for the request.

{% hint style="info" %}
**Note:** This removes all other query params with the same name.
{% endhint %}

| Name  | Type   | Required | Default | Description                       |
| ----- | ------ | -------- | ------- | --------------------------------- |
| name  | string | true     |         | The name of the query parameter.  |
| value | string | true     |         | The value of the query parameter. |

**Return**: `HyperRequest`

### `appendQueryParam`

Append a query parameter for the request.

| Name  | Type   | Required | Default | Description                       |
| ----- | ------ | -------- | ------- | --------------------------------- |
| name  | string | true     |         | The name of the query parameter.  |
| value | string | true     |         | The value of the query parameter. |

**Return**: `HyperRequest`

### `withQueryParams`

Add additional query parameters to the request.&#x20;

{% hint style="info" %}
**Note:** This will remove any values with duplicate keys prior to adding the new struct of params.
{% endhint %}

| Name        | Type   | Required | Default | Description                                         |
| ----------- | ------ | -------- | ------- | --------------------------------------------------- |
| queryParams | struct | true     |         | A struct of query parameters to add to the request. |

**Return**: `HyperRequest`

### `appendQueryParams`

Appends additional query parameters to the request.

| Name        | Type   | Required | Default | Description                                         |
| ----------- | ------ | -------- | ------- | --------------------------------------------------- |
| queryParams | struct | true     |         | A struct of query parameters to add to the request. |

**Return**: `HyperRequest`

### `hasQueryParam`

Check if the request has a query parameter with the given name.

| Name | Type   | Required | Default | Description                               |
| ---- | ------ | -------- | ------- | ----------------------------------------- |
| name | string | true     |         | The name of the query parameter to check. |

**Return**: `boolean`

### `attach`

Attaches a file to the Hyper request. Also sets the Content-Type as `multipart/form-data`. Multiple files can be attached by calling `attach` multiple times before calling a send method.

| Name     | Type   | Required | Default | Description                                       |
| -------- | ------ | -------- | ------- | ------------------------------------------------- |
| name     | string | true     |         | The name of the file being uploaded.              |
| path     | string | true     |         | The absolute path to the file to be uploaded.     |
| mimeType | string | false    |         | An optional mime type to associate with the file. |

**Return**: `HyperRequest`

### `setThrowOnError`

Sets the throw on error property for the request. If true, statuses in the 4xx and 5xx range will be turned in to exceptions.

| Name  | Type    | Required | Default | Description                           |
| ----- | ------- | -------- | ------- | ------------------------------------- |
| value | boolean | true     |         | The value of the throw on error flag. |

**Return**: `HyperRequest`

### `throwErrors`

A convenience method to throw on errors.

| Name         | Type | Required | Default | Description |
| ------------ | ---- | -------- | ------- | ----------- |
| No arguments |      |          |         |             |

**Return**: `HyperRequest`

### `allowErrors`

A convenience method to not throw on errors.

| Name         | Type | Required | Default | Description |
| ------------ | ---- | -------- | ------- | ----------- |
| No arguments |      |          |         |             |

**Return**: `HyperRequest`

### `clone`

Clones the current request into a new HyperRequest.

| Name         | Type | Required | Default | Description |
| ------------ | ---- | -------- | ------- | ----------- |
| No arguments |      |          |         |             |

**Return**: A new `HyperRequest` instance cloned from this one.

### `clear`

Clears the request of any set values, including defaults passed by the builder.

| Name         | Type | Required | Default | Description |
| ------------ | ---- | -------- | ------- | ----------- |
| No arguments |      |          |         |             |

**Return**: `HyperRequest`

### `when`

Helper to conditionally execute a callback for the `HyperRequest`. This method lets you use conditionals without breaking chaining.

| Name            | Type       | Required | Default | Description                                                                                            |
| --------------- | ---------- | -------- | ------- | ------------------------------------------------------------------------------------------------------ |
| condition       | `boolean`  | `true`   |         | The condition to check.                                                                                |
| successCallback | `function` | `true`   |         | The callback to execute if the condition is true. The callback is passed the `HyperRequest` instance.  |
| failureCallback | `function` | `false`  | `null`  | The callback to execute if the condition is false. The callback is passed the `HyperRequest` instance. |

**Return**: `HyperRequest`

### `setProperties`

Quickly set many request properties using a struct. The key should be the name of one of the properties on the request, e.g. `url`, `headers`, `method`, `body`.

| Name       | Type   | Required | Default | Description                                                                                                                                   |
| ---------- | ------ | -------- | ------- | --------------------------------------------------------------------------------------------------------------------------------------------- |
| properties | struct | true     |         | A struct of properties to set. Each property name will be set on the request. Properties that don't exist on the request will throw an error. |

**Return**: `HyperRequest`

### `setHttpClient`

Sets the [HTTP Client](/6.1.0-1/customizing-hyper/custom-http-clients) to use for the request. The client should conform to the `HyperHttpClientInterface` (though it does not need to use the `implements` keyword).

| Name       | Type                       | Required | Default | Description                            |
| ---------- | -------------------------- | -------- | ------- | -------------------------------------- |
| httpClient | `HyperHttpClientInterface` | `true`   |         | The httpClient to use for the request. |

**Return**: `HyperRequest`

### `setInterceptorService`

Sets the [ColdBox Interceptor Service](https://coldbox.ortusbooks.com/the-basics/interceptors) to announce request and response interception points. A noop option is provided in the `init` for non-ColdBox usage.

| Name               | Type | Required | Default | Description                                     |
| ------------------ | ---- | -------- | ------- | ----------------------------------------------- |
| interceptorService | any  | `true`   |         | The interceptor service to use for the request. |

**Return**: `HyperRequest`

### `setAsyncManager`

Sets the [ColdBox AsyncManager](https://coldbox.ortusbooks.com/digging-deeper/promises-async-programming) to send requests asynchronously. A noop option is provided in the `init` for non-ColdBox usage.

| Name         | Type | Required | Default | Description                              |
| ------------ | ---- | -------- | ------- | ---------------------------------------- |
| asyncManager | any  | `true`   |         | The asyncManager to use for the request. |

**Return**: `HyperRequest`

### `getMemento`

Returns a struct representing this `HyperRequest`.

| Name         | Type | Required | Default | Description |
| ------------ | ---- | -------- | ------- | ----------- |
| No arguments |      |          |         |             |

**Return**:

```json
{
    "requestID"          : getRequestID(),
    "baseUrl"            : getBaseUrl(),
    "url"                : getUrl(),
    "fullUrl"            : getFullUrl(),
    "method"             : getMethod(),
    "queryParams"        : getQueryParams(),
    "headers"            : getHeaders(),
    "files"              : getFiles(),
    "bodyFormat"         : getBodyFormat(),
    "body"               : getBody(),
    "referrer"           : isNull( variables.referrer ) ? "" : variables.referrer,
    "throwOnError"       : getThrowOnError(),
    "timeout"            : getTimeout(),
    "maximumRedirects"   : getMaximumRedirects(),
    "authType"           : getAuthType(),
    "username"           : getUsername(),
    "password"           : getPassword(),
    "clientCert"         : isNull( variables.clientCert ) ? "" : variables.clientCert,
    "clientCertPassword" : isNull( variables.clientCertPassword ) ? "" : variables.clientCertPassword,
    "domain"             : getDomain(),
    "workstation"        : getWorkstation(),
    "resolveUrls"        : getResolveUrls(),
    "encodeUrl"          : getEncodeUrl()
};
```

### `debug`

Creates a debug representation of the HTTP request for the current HTTP client.

{% hint style="danger" %}
**Throws**: `NoUrlException` when no URL is set.
{% endhint %}

| Name         | Type | Required | Default | Description |
| ------------ | ---- | -------- | ------- | ----------- |
| No arguments |      |          |         |             |

**Return**: Dependent on the configured HTTP Client.  See specific HTTP Client documentation for details.


# HyperResponse

The `HyperResponse` component is a read-only wrapper to easily grab different information about the response.

### `getResponseId`

Gets the unique response ID representing this response.

| Name         | Type | Required | Default | Description |
| ------------ | ---- | -------- | ------- | ----------- |
| No arguments |      |          |         |             |

**Return**: `String`

### `getStatusCode`

Gets the status code for the response.

| Name         | Type | Required | Default | Description |
| ------------ | ---- | -------- | ------- | ----------- |
| No arguments |      |          |         |             |

**Return**: `numeric`

### `getStatusText`

Gets the status text for the response.

| Name         | Type | Required | Default | Description |
| ------------ | ---- | -------- | ------- | ----------- |
| No arguments |      |          |         |             |

**Return**: `String`

### `getStatus`

Returns the status code and status text as a single string.

| Name         | Type | Required | Default | Description |
| ------------ | ---- | -------- | ------- | ----------- |
| No arguments |      |          |         |             |

**Return**: `String`

### `getData`

Gets the data for the response.

| Name         | Type | Required | Default | Description |
| ------------ | ---- | -------- | ------- | ----------- |
| No arguments |      |          |         |             |

**Return**: `String`

### `getRequestID`

Returns the id of the request to which this response is related.

| Name         | Type | Required | Default | Description |
| ------------ | ---- | -------- | ------- | ----------- |
| No arguments |      |          |         |             |

**Return**: `String`

### `getRequest`

Gets the [HyperRequest](/6.1.0-1/making-requests/hyperrequest) instance associated with this response.

| Name         | Type | Required | Default | Description |
| ------------ | ---- | -------- | ------- | ----------- |
| No arguments |      |          |         |             |

**Return**: [`HyperRequest`](/6.1.0-1/making-requests/hyperrequest)

### `getCharset`

Gets the charset value for the response.

| Name         | Type | Required | Default | Description |
| ------------ | ---- | -------- | ------- | ----------- |
| No arguments |      |          |         |             |

**Return**: `String`

### `getTimestamp`

Gets the timestamp for when this response was received.

| Name         | Type | Required | Default | Description |
| ------------ | ---- | -------- | ------- | ----------- |
| No arguments |      |          |         |             |

**Return**: `DateTime`

### `getExecutionTime`

Gets the execution time of the request, in milliseconds.

| Name         | Type | Required | Default | Description |
| ------------ | ---- | -------- | ------- | ----------- |
| No arguments |      |          |         |             |

**Return**: `numeric`

### `json`

Returns the data of the request as deserialized `JSON`.

{% hint style="danger" %}
**Throws**: `DeserializeJsonException` if the response is not `JSON`.
{% endhint %}

| Name         | Type | Required | Default | Description |
| ------------ | ---- | -------- | ------- | ----------- |
| No arguments |      |          |         |             |

**Return**: `any`

### `isSuccess`

Returns true if the request status code is considered successful.

| Name         | Type | Required | Default | Description |
| ------------ | ---- | -------- | ------- | ----------- |
| No arguments |      |          |         |             |

**Return**: `boolean`

### `isOK`

Returns true if the request status code is `200 OK`.

| Name         | Type | Required | Default | Description |
| ------------ | ---- | -------- | ------- | ----------- |
| No arguments |      |          |         |             |

**Return**: `boolean`

### `isCreated`

Returns true if the request status code is `201 Created`.

| Name         | Type | Required | Default | Description |
| ------------ | ---- | -------- | ------- | ----------- |
| No arguments |      |          |         |             |

**Return**: `boolean`

### `isRedirect`

Returns true if the request status code is considered a redirect.

| Name         | Type | Required | Default | Description |
| ------------ | ---- | -------- | ------- | ----------- |
| No arguments |      |          |         |             |

**Return**: `boolean`

### `isError`

Returns true if the request status code is considered either a client error (4xx status code) or a server error (5xx status code).

| Name         | Type | Required | Default | Description |
| ------------ | ---- | -------- | ------- | ----------- |
| No arguments |      |          |         |             |

**Return**: `boolean`

### `isClientError`

Returns true if the request status code is considered a client error (4xx status code).

| Name         | Type | Required | Default | Description |
| ------------ | ---- | -------- | ------- | ----------- |
| No arguments |      |          |         |             |

**Return**: `boolean`

### `isUnauthorized`

Returns true if the request status code is `401 Unauthorized`.

| Name         | Type | Required | Default | Description |
| ------------ | ---- | -------- | ------- | ----------- |
| No arguments |      |          |         |             |

**Return**: `boolean`

### `isForbidden`

Returns true if the request status code is `403 Forbidden`.

| Name         | Type | Required | Default | Description |
| ------------ | ---- | -------- | ------- | ----------- |
| No arguments |      |          |         |             |

**Return**: `boolean`

### `isNotFound`

Returns true if the request status code is `404 Not Found`.

| Name         | Type | Required | Default | Description |
| ------------ | ---- | -------- | ------- | ----------- |
| No arguments |      |          |         |             |

**Return**: `boolean`

### `isServerError`

Returns true if the request status code is considered a server error (5xx status code).

| Name         | Type | Required | Default | Description |
| ------------ | ---- | -------- | ------- | ----------- |
| No arguments |      |          |         |             |

**Return**: `boolean`

### `hasHeader`

Checks if a header exists in the response.

| Name | Type     | Required | Default | Description                      |
| ---- | -------- | -------- | ------- | -------------------------------- |
| name | `String` | `true`   |         | The name of the header to check. |

**Return**: `boolean`

### `getHeader`

Gets the value of a header from the response.

| Name         | Type     | Required | Default | Description                                       |
| ------------ | -------- | -------- | ------- | ------------------------------------------------- |
| name         | `String` | `true`   |         | The name of the header to retrieve.               |
| defaultValue | `any`    | `false`  | `""`    | The value to return if the header does not exist. |

**Return**: `any`

### `getMemento`

Gets a serializable representation of the response.

| Name         | Type | Required | Default | Description |
| ------------ | ---- | -------- | ------- | ----------- |
| No arguments |      |          |         |             |

**Return**:

```json
{
    "responseID"    : getResponseID(),
    "requestID"     : getRequestID(),
    "statusCode"    : getStatusCode(),
    "statusText"    : getStatusText(),
    "status"        : getStatus(),
    "data"          : getData(),
    "charset"       : getCharset(),
    "headers"       : getHeaders(),
    "timestamp"     : getTimestamp(),
    "executionTime" : getExecutionTime()
}
```


# Hyper Clients

Hyper allows you to configure defaults for your requests as custom Hyper Clients. This is particularly useful for reducing boilerplate in your application.

Defaults are set on the `HyperBuilder` instance. The easiest way to do this is to configure it in WireBox:

```js
// config/WireBox.cfc
component {

    function configure() {
        map( "StarWarsClient" )
            .to( "hyper.models.HyperBuilder" )
            .asSingleton()
            .initWith(
                baseUrl = "https://swapi.dev/api"
            );
    }

}
```

Now, you can inject this pre-configured builder wherever you need in your application:

```js
component {

    property name="StarWarsClient" inject="StarWarsClient";

    function findUser( id ) {
        return variables.StarWarsClient.get( "/people/#id#" );
    }

}
```

You can even create multiple clients using this approach:

```js
// config/WireBox.cfc
component {

    function configure() {
        map( "SWAPIClient" )
            .to( "hyper.models.HyperBuilder" )
            .asSingleton()
            .initWith(
                baseUrl = "https://swapi.dev/api"
            );

        map( "GitHubClient" )
            .to( "hyper.models.HyperBuilder" )
            .asSingleton()
            .initWith(
                baseUrl = "https://api.github.com",
                headers = {
                    "Authorization" = getColdBox().getUtil().getSystemSetting( "GITHUB_TOKEN" )
                }
            );
    }

}
```

You can also set or change the defaults by either passing the key / value pairs in to the `init` method or by calling the appropriate `HyperRequest` method on the `HyperBuilder.defaults` property.

```js
var hyper = new Hyper.models.HyperBuilder(
    baseUrl = "https://api.github.com"
);
hyper.defaults.withHeaders( { "Authorization" = token } );
```

The defaults set here need to match the property names on the `HyperRequest`. These are:

```cfscript
/**
* The httpClient to use for the request
*/
property name="httpClient";

/**
* The baseURL for the request.
* e.g. https://api.github.com/
*/
property name="baseUrl" default="";

/**
* The URL for the request.
* It can either be a full url
* or a URI resource for use with the baseURL.
* e.g. /repos
*/
property name="url" default="";

/**
* Setting this to true will change all relative urls in the document to absolute.
*/
property name="resolveUrls" default="false";

/**
* Setting this to false will not automatically encode the url passed.
* WARNING: Setting this to false is not supported on Adobe engines.
*/
property name="encodeUrl" default="true";

/**
* The HTTP method for the request.
*/
property name="method" default="GET";

/**
* The username for the request for basic auth.
*/
property name="username" default="";

/**
* The password for the request for basic auth.
*/
property name="password" default="";

/**
* Timeout, in seconds, for the request.
*/
property name="timeout" default="10";

/**
* The maximum number of redirects to follow.
* A value of `*` will follow redirects infinitely.
*/
property name="maximumRedirects" default="*";

/**
* The body to send with the request.
* How the body is serialized is
* determined by the bodyFormat.
*/
property name="body" default="";

/**
* The format to serialize the body.
* e.g. `json` or `formFields`
*/
property name="bodyFormat" default="json";

/**
* The referring response in the case of redirects.
*/
property name="referrer";

/**
* A struct of headers for the request.
*/
property name="headers";

/**
* A struct of query parameters for the request.
*/
property name="queryParams";

/**
* Flag to throw on a cfhttp error.
*/
property name="throwOnError" default="false";

/**
* The full path to a PKCS12 format file that contains the client certificate for the request.
*/
property name="clientCert";

/**
* 	Password used to decrypt the client certificate.
*/
property name="clientCertPassword";

/**
* The domain for the request for NTLM auth.
*/
property name="domain" default="";

/**
* The workstation for the request for NTLM auth.
*/
property name="workstation" default="";

/**
* The authType for the request
*/
property name="authType" default="BASIC";

/**
* An array of callback functions to call
* before firing off a request.
*/
property name="requestCallbacks" type="array";

/**
* An array of callback functions to call
* after receiving a response.
*/
property name="responseCallbacks" type="array";
```

If you need per-request or per-response manipulation of defaults, use the [`requestCallbacks`](/6.1.0-1/making-requests/hyperrequest#withrequestcallback) and [`responseCallbacks`](/6.1.0-1/making-requests/hyperrequest#withresponsecallback) hooks.

```cfscript
map( "ApiClient" )
    .to( "hyper.models.HyperBuilder" )
    .asSingleton()
    .initWith(
        baseUrl = getColdBox().getUtil().getSystemSetting( "API_URL" ),
        requestCallbacks = [
            // provide the current user's token for the request
            function( req ) {
                var auth = getWireBox().getInstance( "AuthenticationService@cbauth" );
                req.withHeaders( "Authorization", auth.user().getApiToken() );
            }
        ],
        responseCallbacks = [
            // map custom `error` property to an exception
            function ( res ) {
                if ( !res.isError() ) {
                    return;
                }
                
                var body = res.json();
                throw(
                    type = "ApiError",
                    message = body.error.message,
                    detail = body.error.code
                );
            }
        ]
    );
```


# Custom HTTP Clients

By default, Hyper makes HTTP requests using `cfhttp` under the hood.  This can be swapped out by any compatible HTTP client that follows the `HyperHttpClientInterface`.

```cfscript
/**
 * Responsible for executing the HyperRequest and mapping it to a HyperResponse
 */
interface displayname="HyperHttpClientInterface" {

	/**
	 * Execute the HyperRequest and map it to a HyperResponse.
	 *
	 * @req     The HyperRequest to execute.
	 *
	 * @returns A HyperResponse of the executed request.
	 */
	public HyperResponse function send( required HyperRequest req );

	/**
	 * Return a struct of information showing how the client will execute the HyperRequest.
	 * This will be used by a developer to debug any differences between the generated
	 * request values and the expected request values.
	 *
	 * @req     The HyperRequest to debug.
	 *
	 * @returns A struct of information detailing how the client would execute the HyperRequest.
	 */
	public struct function debug( required HyperRequest req );

}
```


# CfhttpHttpClient

### `debug`

Return a struct of information showing how the client will execute the [`HyperRequest`](/6.1.0-1/making-requests/hyperrequest). This will be used by a developer to debug any differences between the generated request values and the expected request values.

| Name | Type                                                    | Required | Default | Description                                                           |
| ---- | ------------------------------------------------------- | -------- | ------- | --------------------------------------------------------------------- |
| req  | [`HyperRequest`](/6.1.0-1/making-requests/hyperrequest) | `true`   |         | The [`HyperRequest`](/6.1.0-1/making-requests/hyperrequest) to debug. |

**Return**:

```json
{
    "attributes" : attrCollection,
    "body"       : {
        "headers" : cfhttpHeaders,
        "params"  : cfhttpParams,
        "files"   : cfhttpFiles,
        "body"    : cfhttpBody
    }
}
```


# Introduction

## A CFML HTTP Builder

### Inspiration

Hyper was built after coding several API SDK's for various platforms — [S3SDK](https://github.com/coldbox-modules/s3sdk), [cbstripe](https://github.com/coldbox-modules/cbox-stripe), and [cbgithub](https://github.com/elpete/cbgithub), to name a few. We noticed that we spent a lot of time setting up the plumbing for the requests and a wrapper around `cfhttp`. Each implementation was mostly the same but slightly different. It was additionally frustrating because we really only needed to tweak a few values, usually just the `Authorization` header. It would be nice to create an HTTP client pre-configured for each of these SDK's. It seemed the perfect fit for a module.

### The problem it solves

Hyper exists to provide a fluent builder experience for HTTP requests and responses. It also provides a powerful way to create clients, i.e. Builder objects with pre-configured defaults like a base URL or certain headers.


# What's New?

## 7.0.0

### CFHttp HTTP Client

This client now returns more accurate status codes for `502 Bad Gateway` and `408 Request Timeout` responses.

Previously, these responses were returned as `504 Gateway Timeout` responses. Hyper now normalizes the responses from the different CFML engines into a consistent response. `502 Bad Gateway` is returned instead of `504 Gateway Timeout` for invalid hosts. `408 Request Timeout` is returned if the request takes longer than the configured [`timeout`](/7.0.0-2/making-requests/hyperrequest#settimeout) value.

### Breaking Changes

If you were previously checking specifically for `504` status codes for bad hosts, you need to now either check for `502` status codes or use a more general method, like [`isServerError`](/7.0.0-2/making-requests/hyperresponse#isservererror) or [`isError`](/7.0.0-2/making-requests/hyperresponse#iserror).

If you were previously checking specifically for `504` status codes or [`isServerError`](/7.0.0-2/making-requests/hyperresponse#isservererror) for timed out requests, you need to now either check for `408` status codes, [`isClientError`](/7.0.0-2/making-requests/hyperresponse#isclienterror), or the more general [`isError`](/7.0.0-2/making-requests/hyperresponse#iserror).

## 6.1.0

Add [`head`](/7.0.0-2/making-requests/hyperrequest#head) and [`options`](/7.0.0-2/making-requests/hyperrequest#options) shortcut methods.

## 6.0.0

* Add `xml` support and an `asXML` method to set the body format and `Content-Type` header.
* Add `adobe@2023` to testing matrix.

### Breaking Changes

* Remove default `Content-Type` header. You must set this [manually](/7.0.0-2/making-requests/hyperrequest#setcontenttype) or use a format helper, such as [`asJson`](/7.0.0-2/making-requests/hyperrequest#asjson).
* Dropped `adobe@2016` support.

## 5.0.1

Correctly handle cases when the `body` is a string and format is `JSON`.

## 5.0.0

Add a `debug` method to see what the HTTP client generates.

### Breaking Changes

`HyperHttpClientInterface` now requires a `debug` method.

```cfscript
/**
 * Return a struct of information showing how the client will execute the HyperRequest.
 * This will be used by a developer to debug any differences between the generated
 * request values and the expected request values.
 *
 * @req     The HyperRequest to debug.
 *
 * @returns A struct of information detailing how the client would execute the HyperRequest.
 */
public struct function debug( required HyperRequest req );
```

## 4.0.3

* Do not prepend the base url when a full url is passed.
* Add `resolveUrls` and `encodeUrl` properties to the [memento](/7.0.0-2/making-requests/hyperrequest#getmemento).
* Correctly set the `encodeUrl` property when cloning a request.

## 4.0.2

Update README for builder `initWith` headers losing `Content-Type`.

## 4.0.1

Fix `HyperBuilder` example in the docs.

## 4.0.0

Allow adding multiple query params with the same key.

### Breaking Changes

Previously, query params were stored as a struct.  Some APIs expect multiple values for the same query param name to be passed as separate arguments.  Hyper now stores the query params as an array and provides new methods for interacting with query params:

* [`getQueryParamByName`](/7.0.0-2/making-requests/hyperrequest#getqueryparambyname)
* [`getAllQueryParamsByName`](/7.0.0-2/making-requests/hyperrequest#getallqueryparamsbyname)
* [`withQueryParams`](/7.0.0-2/making-requests/hyperrequest#withqueryparams)
* [`appendQueryParam`](/7.0.0-2/making-requests/hyperrequest#appendqueryparam)
* [`appendQueryParams`](/7.0.0-2/making-requests/hyperrequest#appendqueryparams)
* [`hasQueryParam`](/7.0.0-2/making-requests/hyperrequest#hasqueryparam)

The following methods still exist, but now interact with arrays of query param structs instead of a simple struct.

* [`getQueryParams`](/7.0.0-2/making-requests/hyperrequest#getqueryparams)
* [`setQueryParams`](/7.0.0-2/making-requests/hyperrequest#setqueryparams)

The following methods have been deprecated:

| Deprecated Method                                                      | Replacement Method                                                                 |
| ---------------------------------------------------------------------- | ---------------------------------------------------------------------------------- |
| [`getQueryParam`](/7.0.0-2/making-requests/hyperrequest#getqueryparam) | [`getQueryParamByName`](/7.0.0-2/making-requests/hyperrequest#getqueryparambyname) |

## 3.6.2

Convert array values correctly when sending form fields

## 3.6.1

Add a workaround for CommandBox not having the `box:asyncManager` injection DSL.

## 3.6.0

Add async requests using ColdBox's [AsyncManager](https://coldbox.ortusbooks.com/digging-deeper/promises-async-programming).

## 3.5.0

* Provide more useful error than cfhttp when [`throwOnErrors`](/7.0.0-2/making-requests/hyperrequest#throwerrors) is enabled.
* Provide mementos for [HyperRequest](/7.0.0-2/making-requests/hyperrequest#getmemento) and [HyperResponse](/7.0.0-2/making-requests/hyperresponse#getmemento) instances.
* Capture [statusText](/7.0.0-2/making-requests/hyperresponse#getstatustext) and provide a [status](/7.0.0-2/making-requests/hyperresponse#getstatus) convenience string.

## 3.4.2

Add MIT License file

## 3.4.1

Use `processState` over `announce` until CommandBox can update its `interceptorService`.

## 3.4.0

### HyperRequest

* Add [`forwardHeaders`](/7.0.0-2/making-requests/hyperrequest#forwardheaders) shortcut method.

### HyperResponse

* Allow for default values in [`getHeader`](/7.0.0-2/making-requests/hyperresponse#getheader).
* Add helper methods for checking for specific status codes:
  * [`isOk`](/7.0.0-2/making-requests/hyperresponse#isok)
  * [`isUnauthorized`](/7.0.0-2/making-requests/hyperresponse#isunauthorized)
  * [`isForbidden`](/7.0.0-2/making-requests/hyperresponse#isforbidden)
  * [`isNotFound`](/7.0.0-2/making-requests/hyperresponse#isnotfound)

## 3.3.0

Allowing [attaching](/7.0.0-2/making-requests/hyperrequest#attach) file uploads.

## 3.2.1

Support WireBox outside of ColdBox.

## 3.2.0

Include response data as detail in `DeserializeJsonException`.

## 3.1.0

* Add [`clone`](/7.0.0-2/making-requests/hyperrequest#clone) to quickly copy `HyperRequest` instances.
* Add interceptors and [local](/7.0.0-2/making-requests/hyperrequest#withrequestcallback) [callbacks](/7.0.0-2/making-requests/hyperrequest#withresponsecallback) for lifecycle events.

## 3.0.0

Add execution time to `HyperResponse` instances.

### Breaking Changes

Dropped support for ColdBox 5.

## 2.3.11

* Add support for [NTLM authentication](/7.0.0-2/making-requests/hyperrequest#withntlmauth).
* Include [`getFullURL`](/7.0.0-2/making-requests/hyperrequest#getfullurl) method in docs.

## 2.3.10

Fixed typo of `Bulider` to `Builder`.

## 2.3.9

Add [`withoutEncodingUrl`](/7.0.0-2/making-requests/hyperrequest#withoutencodingurl) flag.

## 2.3.8

Do not fail fast on cron job actions on CI.

## 2.3.7

Update fetch-depth for tests and release actions on CI.

## 2.3.6

Attempt to skip committing back changes on CI.

## 2.3.5

Add matrix and cron testing on CI.

## 2.3.4

Use better GitHub token on CI

## 2.3.1

Add workaround for `boolean` values in query strings.

## 2.3.0

Add [certificate](/7.0.0-2/making-requests/hyperrequest#withcertificateauth) auth.

## 2.2.1

Use the previous host for redirect if redirect does not include a full URL.

## 2.2.0

Add [`resolveUrls`](/7.0.0-2/making-requests/hyperrequest#setresolveurl) flag.

## 2.1.1

* Use OpenJDK instead of OracleJDK on CI.
* Store module in [ForgeBox Storage](https://commandbox.ortusbooks.com/5.6.0/developing-for-commandbox/commands).

## 2.1.0

Allow for pluggable [HTTP Clients](/7.0.0-2/customizing-hyper/custom-http-clients) that follow the `HyperHttpClientInterface`. (Clients do not need to use the `implements` keyword.)

## 2.0.2

Avoid double encoding using [`cfhttpparam`](https://cfdocs.org/cfhttpparam).

## 2.0.1

Remove Lucee 4.5 support from docs. (Support was dropped in [v2.0.0](#2.0.0))

## 2.0.0

* Do not include [`username`](/7.0.0-2/making-requests/hyperrequest#setusername) and [`password`](/7.0.0-2/making-requests/hyperrequest#setpassword) unless they have values.
* Add `adobe@2018` support to CI builds.

### Breaking Changes

Dropped support for `lucee@4.5`.

## 1.15.0

Add [`throwOnError`](/7.0.0-2/making-requests/hyperrequest#throwerrors) flag.

## 1.14.5

Use `504 Gateway Timeout` for incomplete responses.

## 1.14.4

Include equal signs in query param values.

## 1.14.0 – 1.0.0

### New Features

* Add [`when`](/7.0.0-2/making-requests/hyperrequest#when) helper to execute conditions without breaking chaining.
* Add [`clear`](/7.0.0-2/making-requests/hyperrequest#clear) method to reset HyperRequest instances.
* Add configurable [`timeout`](/7.0.0-2/making-requests/hyperrequest#settimeout).

### Bug Fixes

* Fix for Lucee 4 compatibility on `LinkedHashMaps` and `keyArray`.
* Preserve case in header names.
* Preserve case for query parameters.
* Serialize both params from the url and set on the `HyperRequest` instance.
* Default to `UTF-8` charset if none is present in the response.
* Fix withHeaders and withQueryParams for Lucee compatibility.
* Only map HyperBuilder as a singleton in WireBox

### Other

* Migrate to [coldbox-modules](https://github.com/coldbox-modules) organization on GitHub.
* Update `box.json` description.
* Enable [CommandBox Semantic Release](https://forgebox.io/view/commandbox-semantic-release) on CI.


# Upgrade Guide

## Upgrading from v6 to v7

### CFHttp HTTP Client

This client now returns more accurate status codes for `502 Bad Gateway` and `408 Request Timeout` responses.

If you were previously checking specifically for `504` status codes for bad hosts, you need to now either check for `502` status codes or use a more general method, like [`isServerError`](/7.0.0-2/making-requests/hyperresponse#isservererror) or [`isError`](/7.0.0-2/making-requests/hyperresponse#iserror).

If you were previously checking specifically for `504` status codes or [`isServerError`](/7.0.0-2/making-requests/hyperresponse#isservererror) for timed out requests, you need to now either check for `408` status codes, [`isClientError`](/7.0.0-2/making-requests/hyperresponse#isclienterror), or the more general [`isError`](/7.0.0-2/making-requests/hyperresponse#iserror).

## Upgrading from v5 to v6

* The default `Content-Type` header has been removed. You must set this [manually](/7.0.0-2/making-requests/hyperrequest#setcontenttype) or use a format helper, such as [`asJson`](/7.0.0-2/making-requests/hyperrequest#asjson).
* Dropped support for Adobe 2016.

## Upgrading from v4 to v5

`HyperHttpClientInterface` now requires a `debug` method.

```cfscript
/**
 * Return a struct of information showing how the client will execute the HyperRequest.
 * This will be used by a developer to debug any differences between the generated
 * request values and the expected request values.
 *
 * @req     The HyperRequest to debug.
 *
 * @returns A struct of information detailing how the client would execute the HyperRequest.
 */
public struct function debug( required HyperRequest req );
```

## Upgrading from v3 to v4

Previously, query params were stored as a struct.  Some APIs expect multiple values for the same query param name to be passed as separate arguments.  Hyper now stores the query params as an array and provides new methods for interacting with query params:

* [`getQueryParamByName`](/7.0.0-2/making-requests/hyperrequest#getqueryparambyname)
* [`getAllQueryParamsByName`](/7.0.0-2/making-requests/hyperrequest#getallqueryparamsbyname)
* [`withQueryParams`](/7.0.0-2/making-requests/hyperrequest#withqueryparams)
* [`appendQueryParam`](/7.0.0-2/making-requests/hyperrequest#appendqueryparam)
* [`appendQueryParams`](/7.0.0-2/making-requests/hyperrequest#appendqueryparams)
* [`hasQueryParam`](/7.0.0-2/making-requests/hyperrequest#hasqueryparam)

The following methods still exist, but now interact with arrays of query param structs instead of a simple struct.

* [`getQueryParams`](/7.0.0-2/making-requests/hyperrequest#getqueryparams)
* [`setQueryParams`](/7.0.0-2/making-requests/hyperrequest#setqueryparams)

The following methods have been deprecated:

| Deprecated Method                                                      | Replacement Method                                                                 |
| ---------------------------------------------------------------------- | ---------------------------------------------------------------------------------- |
| [`getQueryParam`](/7.0.0-2/making-requests/hyperrequest#getqueryparam) | [`getQueryParamByName`](/7.0.0-2/making-requests/hyperrequest#getqueryparambyname) |

## Upgrading from v2 to v3

Dropped support for ColdBox 5.

## Upgrading from v1 to v2

Dropped support for Lucee 4.5.


# Requirements

Hyper runs on Adobe ColdFusion 2018+ and Lucee 5+.

ColdBox is not required, but mappings are provided for ColdBox users automatically.


# Installation

Hyper is most easily installed via ForgeBox and CommandBox.

```sh
box install hyper
```

If you install Hyper in a non-ColdBox application, make sure to create a mapping in your `Application.cfc`

```cfscript
this.mappings[ "/hyper" ] = expandPath( "/modules/hyper" );
```


# HyperBuilder

A `HyperBuilder` is a singleton factory component that will give you a new [`HyperRequest`](/7.0.0-2/making-requests/hyperrequest) any time you call the `new` method.  It will also create a new [`HyperRequest`](/7.0.0-2/making-requests/hyperrequest) any time you call a method on `HyperBuilder` that exists on [`HyperRequest`](/7.0.0-2/making-requests/hyperrequest).

`HyperBuilder` is the component you want to inject into your singleton components, like handlers or services.  It will ensure you get a fresh [`HyperRequest`](/7.0.0-2/making-requests/hyperrequest) instance on each invocation.  This is important since reusing the same [`HyperRequest`](/7.0.0-2/making-requests/hyperrequest) instance will likely produce unintended results.

You can inject a `HyperBuilder` into your application using the `HyperBuilder@hyper` id.

```cfscript
component {
    
    property name="hyper" inject="HyperBuilder@hyper";

    function index( event, rc, prc ) {
        var reqA = hyper.new();
        // reqA is a new HyperRequest instance.
        
        var reqB = hyper.setUrl( "https://swapi.dev/api/people" );
        // reqB is a new HyperRequest instance with the url set.
    }

}
```

If you are not using ColdBox, you can create a `HyperBuilder` manually:

```cfscript
component {

    function init() {
        variables.hyper = new hyper.models.HyperBuilder();
    }

}
```


# HyperRequest

Though the [`HyperBuilder`](/7.0.0-2/making-requests/hyperbuilder) is the component you will most likely inject, `HyperRequest` is the component will you interact with the most. `HyperRequest` provides a fluent interface to configure your HTTP call.

```cfscript
hyper.get( "https//api.github.com/users" );

hyper.setMethod( "PUT" )
    .withHeaders( { "Authorization" = "Bearer #token#" } )
    .setUrl( "https://jsonplaceholder.typicode.com/posts/1" )
    .setBody( {
        title: "New Title"
    } )
    .send();
```

## Defaults

The following are default properties for a `HyperRequest`:

```json
{
    "method": "GET"
    "resolveUrls": false,
    "encodeUrl": true,
    "timeout": 10, // in seconds
    "maximumRedirects": "*", // follow redirects indefinitely
    "bodyFormat": "json",
    "throwOnError": false
}
```

## Executing Requests

### `get`

Execute a `GET` request and return a [`HyperResponse`](/7.0.0-2/making-requests/hyperresponse).

| Name        | Type   | Required | Default | Description                                                    |
| ----------- | ------ | -------- | ------- | -------------------------------------------------------------- |
| url         | string | false    | null    | An optional URL to set for the request.                        |
| queryParams | struct | false    | null    | An optional struct of query parameters to set for the request. |

**Return**: [`HyperResponse`](/7.0.0-2/making-requests/hyperresponse)

### `getAsync`

Execute a `GET` request asynchronously. Returns a [ColdBox Future](https://coldbox.ortusbooks.com/digging-deeper/promises-async-programming) that returns a [`HyperResponse`](/7.0.0-2/making-requests/hyperresponse).

| Name        | Type   | Required | Default | Description                                                    |
| ----------- | ------ | -------- | ------- | -------------------------------------------------------------- |
| url         | string | false    | null    | An optional URL to set for the request.                        |
| queryParams | struct | false    | null    | An optional struct of query parameters to set for the request. |

**Return**: [`Future`](https://coldbox.ortusbooks.com/digging-deeper/promises-async-programming)`<`[`HyperResponse`](/7.0.0-2/making-requests/hyperresponse)`>`

### `post`

Execute a `POST` request and return a [`HyperResponse`](/7.0.0-2/making-requests/hyperresponse).

| Name | Type   | Required | Default | Description                              |
| ---- | ------ | -------- | ------- | ---------------------------------------- |
| url  | string | false    | null    | An optional URL to set for the request.  |
| body | struct | false    | null    | An optional body to set for the request. |

**Return**: [`HyperResponse`](/7.0.0-2/making-requests/hyperresponse)

### `postAsync`

Execute a `POST` request asynchronously. Returns a [ColdBox Future](https://coldbox.ortusbooks.com/digging-deeper/promises-async-programming) that returns a [`HyperResponse`](/7.0.0-2/making-requests/hyperresponse).

| Name | Type   | Required | Default | Description                              |
| ---- | ------ | -------- | ------- | ---------------------------------------- |
| url  | string | false    | null    | An optional URL to set for the request.  |
| body | struct | false    | null    | An optional body to set for the request. |

**Return**: [`Future`](https://coldbox.ortusbooks.com/digging-deeper/promises-async-programming)`<`[`HyperResponse`](/7.0.0-2/making-requests/hyperresponse)`>`

### `put`

Execute a `PUT` request and return a [`HyperResponse`](/7.0.0-2/making-requests/hyperresponse).

| Name | Type   | Required | Default | Description                              |
| ---- | ------ | -------- | ------- | ---------------------------------------- |
| url  | string | false    | null    | An optional URL to set for the request.  |
| body | struct | false    | null    | An optional body to set for the request. |

**Return**: [`HyperResponse`](/7.0.0-2/making-requests/hyperresponse)

### `putAsync`

Execute a `PUT` request asynchronously. Returns a [ColdBox Future](https://coldbox.ortusbooks.com/digging-deeper/promises-async-programming) that returns a [`HyperResponse`](/7.0.0-2/making-requests/hyperresponse).

| Name | Type   | Required | Default | Description                              |
| ---- | ------ | -------- | ------- | ---------------------------------------- |
| url  | string | false    | null    | An optional URL to set for the request.  |
| body | struct | false    | null    | An optional body to set for the request. |

**Return**: [`Future`](https://coldbox.ortusbooks.com/digging-deeper/promises-async-programming)`<`[`HyperResponse`](/7.0.0-2/making-requests/hyperresponse)`>`

### `patch`

Execute a `PATCH` request and return a [`HyperResponse`](/7.0.0-2/making-requests/hyperresponse).

| Name | Type   | Required | Default | Description                              |
| ---- | ------ | -------- | ------- | ---------------------------------------- |
| url  | string | false    | null    | An optional URL to set for the request.  |
| body | struct | false    | null    | An optional body to set for the request. |

**Return**: [`HyperResponse`](/7.0.0-2/making-requests/hyperresponse)

### `patchAsync`

Execute a `PATCH` request asynchronously. Returns a [ColdBox Future](https://coldbox.ortusbooks.com/digging-deeper/promises-async-programming) that returns a [`HyperResponse`](/7.0.0-2/making-requests/hyperresponse).

| Name | Type   | Required | Default | Description                              |
| ---- | ------ | -------- | ------- | ---------------------------------------- |
| url  | string | false    | null    | An optional URL to set for the request.  |
| body | struct | false    | null    | An optional body to set for the request. |

**Return**: [`Future`](https://coldbox.ortusbooks.com/digging-deeper/promises-async-programming)`<`[`HyperResponse`](/7.0.0-2/making-requests/hyperresponse)`>`

### `delete`

Execute a `DELETE` request and return a [`HyperResponse`](/7.0.0-2/making-requests/hyperresponse).

| Name | Type   | Required | Default | Description                              |
| ---- | ------ | -------- | ------- | ---------------------------------------- |
| url  | string | false    | null    | An optional URL to set for the request.  |
| body | struct | false    | null    | An optional body to set for the request. |

**Return**: [`HyperResponse`](/7.0.0-2/making-requests/hyperresponse)

### `deleteAsync`

Execute a `DELETE` request asynchronously. Returns a [ColdBox Future](https://coldbox.ortusbooks.com/digging-deeper/promises-async-programming) that returns a [`HyperResponse`](/7.0.0-2/making-requests/hyperresponse).

| Name | Type   | Required | Default | Description                              |
| ---- | ------ | -------- | ------- | ---------------------------------------- |
| url  | string | false    | null    | An optional URL to set for the request.  |
| body | struct | false    | null    | An optional body to set for the request. |

**Return**: [`Future`](https://coldbox.ortusbooks.com/digging-deeper/promises-async-programming)`<`[`HyperResponse`](/7.0.0-2/making-requests/hyperresponse)`>`

### `head`

Execute a `HEAD` request and return a [`HyperResponse`](/7.0.0-2/making-requests/hyperresponse).

| Name        | Type   | Required | Default | Description                                                    |
| ----------- | ------ | -------- | ------- | -------------------------------------------------------------- |
| url         | string | false    | null    | An optional URL to set for the request.                        |
| queryParams | struct | false    | null    | An optional struct of query parameters to set for the request. |

**Return**: [`HyperResponse`](/7.0.0-2/making-requests/hyperresponse)

### `headAsync`

Execute a `HEAD` request asynchronously. Returns a [ColdBox Future](https://coldbox.ortusbooks.com/digging-deeper/promises-async-programming) that returns a [`HyperResponse`](/7.0.0-2/making-requests/hyperresponse).

| Name        | Type   | Required | Default | Description                                                    |
| ----------- | ------ | -------- | ------- | -------------------------------------------------------------- |
| url         | string | false    | null    | An optional URL to set for the request.                        |
| queryParams | struct | false    | null    | An optional struct of query parameters to set for the request. |

**Return**: [`Future`](https://coldbox.ortusbooks.com/digging-deeper/promises-async-programming)`<`[`HyperResponse`](/7.0.0-2/making-requests/hyperresponse)`>`

### `options`

Execute an `OPTIONS` request and return a [`HyperResponse`](/7.0.0-2/making-requests/hyperresponse).

| Name        | Type   | Required | Default | Description                                                    |
| ----------- | ------ | -------- | ------- | -------------------------------------------------------------- |
| url         | string | false    | null    | An optional URL to set for the request.                        |
| queryParams | struct | false    | null    | An optional struct of query parameters to set for the request. |

**Return**: [`HyperResponse`](/7.0.0-2/making-requests/hyperresponse)

### `optionsAsync`

Execute an `OPTIONS` request asynchronously. Returns a [ColdBox Future](https://coldbox.ortusbooks.com/digging-deeper/promises-async-programming) that returns a [`HyperResponse`](/7.0.0-2/making-requests/hyperresponse).

| Name        | Type   | Required | Default | Description                                                    |
| ----------- | ------ | -------- | ------- | -------------------------------------------------------------- |
| url         | string | false    | null    | An optional URL to set for the request.                        |
| queryParams | struct | false    | null    | An optional struct of query parameters to set for the request. |

**Return**: [`Future`](https://coldbox.ortusbooks.com/digging-deeper/promises-async-programming)`<`[`HyperResponse`](/7.0.0-2/making-requests/hyperresponse)`>`

### `send`

Send the HTTP request and return a [`HyperResponse`](/7.0.0-2/making-requests/hyperresponse).

| Name         | Type | Required | Default | Description |
| ------------ | ---- | -------- | ------- | ----------- |
| No arguments |      |          |         |             |

**Return**: [`HyperResponse`](/7.0.0-2/making-requests/hyperresponse)

### `sendAsync`

Send the HTTP request asynchronously and return a [ColdBox Future](https://coldbox.ortusbooks.com/digging-deeper/promises-async-programming) that will resolve to a [`HyperResponse`](/7.0.0-2/making-requests/hyperresponse).

| Name         | Type | Required | Default | Description |
| ------------ | ---- | -------- | ------- | ----------- |
| No arguments |      |          |         |             |

**Return**: [`Future`](https://coldbox.ortusbooks.com/digging-deeper/promises-async-programming)`<`[`HyperResponse`](/7.0.0-2/making-requests/hyperresponse)`>`

## Building Requests

### `getRequestId`

Gets the unique request ID representing this request.

| Name         | Type | Required | Default | Description |
| ------------ | ---- | -------- | ------- | ----------- |
| No arguments |      |          |         |             |

**Return**: `String`

### `getFullURL`

Gets the full URL for the request.

| Name            | Type    | Required | Default | Description                                            |
| --------------- | ------- | -------- | ------- | ------------------------------------------------------ |
| withQueryString | boolean | false    | false   | Includes the configured query string with the full URL |

**Return**: `String`

### `getBaseURL`

Gets the base URL for the request. The base URL is combined with the URL when making the request.

| Name         | Type | Required | Default | Description |
| ------------ | ---- | -------- | ------- | ----------- |
| No arguments |      |          |         |             |

**Return**: `String`

### `setBaseURL`

Sets the base URL for the request. The base URL is combined with the URL when making the request.

| Name  | Type   | Required | Default | Description                                                   |
| ----- | ------ | -------- | ------- | ------------------------------------------------------------- |
| value | string | true     |         | The base URL for the request, e.g. `https://api.github.com/`. |

**Return**: `HyperRequest`

### `getURL`

Gets the URL for the request.

| Name         | Type | Required | Default | Description |
| ------------ | ---- | -------- | ------- | ----------- |
| No arguments |      |          |         |             |

**Return**: `String`

### `setURL`

Sets the URL for the request.

| Name  | Type   | Required | Default | Description                                                                                                     |
| ----- | ------ | -------- | ------- | --------------------------------------------------------------------------------------------------------------- |
| value | string | true     |         | The URL for the request. It can either be a full url or a URI resource for use with the baseURL. e.g. `/repos`. |

**Return**: `HyperRequest`

### `setResolveURL`

Sets the resolveURL parameter for the request.

| Name  | Type    | Required | Default | Description                                                                    |
| ----- | ------- | -------- | ------- | ------------------------------------------------------------------------------ |
| value | boolean | false    | false   | Resolves URLs in the response body to absolute URLs, including the port number |

**Return**: `HyperRequest`

### `getMethod`

Gets the HTTP method for the request.

| Name         | Type | Required | Default | Description |
| ------------ | ---- | -------- | ------- | ----------- |
| No arguments |      |          |         |             |

**Return**: `String`

### `setMethod`

Sets the HTTP method for the request.

| Name  | Type   | Required | Default | Description                      |
| ----- | ------ | -------- | ------- | -------------------------------- |
| value | string | true     |         | The HTTP method for the request. |

**Return**: `HyperRequest`

### `withBasicAuth`

Sets the username and password for HTTP Basic Auth.

| Name     | Type   | Required | Default | Description                      |
| -------- | ------ | -------- | ------- | -------------------------------- |
| username | string | true     |         | The username for the basic auth. |
| password | string | true     |         | The password for the basic auth. |

**Return**: `HyperRequest`

### `withCertificateAuth`

Sets the username and password for HTTP Basic Auth.

| Name            | Type   | Required | Default | Description                                              |
| --------------- | ------ | -------- | ------- | -------------------------------------------------------- |
| certificatePath | string | true     |         | The mapped path to the certificate used to authenticate. |
| password        | string | false    |         | The optional password used to decrypt the certificate.   |

**Return**: `HyperRequest`

### `withNTLMAuth`

Sets the username, password, domain and workstation for NTLM Auth.

| Name        | Type   | Required | Default | Description                        |
| ----------- | ------ | -------- | ------- | ---------------------------------- |
| username    | string | true     |         | The username for the NTLM auth.    |
| password    | string | true     |         | The password for the NTLM auth.    |
| domain      | string | true     |         | The domain for the NTLM auth.      |
| workstation | string | true     |         | The workstation for the NTLM auth. |

Workstation can be obtained with `createObject('java','java.net.InetAddress').getLocalHost().getHostName()`

**Return**: `HyperRequest`

### `withRequestCallback`

Schedules a callback to be ran when executing the request.

| Name     | Type     | Required | Default | Description                                     |
| -------- | -------- | -------- | ------- | ----------------------------------------------- |
| callback | function | true     |         | The callback to run when executing the request. |

**Return**: `HyperRequest`

### `withResponseCallback`

Schedules a callback to be ran when receiving the response.

| Name     | Type     | Required | Default | Description                                      |
| -------- | -------- | -------- | ------- | ------------------------------------------------ |
| callback | function | true     |         | The callback to run when receiving the response. |

**Return**: `HyperRequest`

### `getUsername`

Gets the username for the request.

| Name         | Type | Required | Default | Description |
| ------------ | ---- | -------- | ------- | ----------- |
| No arguments |      |          |         |             |

**Return**: `String`

### `setUsername`

Sets the username for the request.

| Name  | Type   | Required | Default | Description                   |
| ----- | ------ | -------- | ------- | ----------------------------- |
| value | string | true     |         | The username for the request. |

**Return**: `HyperRequest`

### `getPassword`

Gets the password for the request.

| Name         | Type | Required | Default | Description |
| ------------ | ---- | -------- | ------- | ----------- |
| No arguments |      |          |         |             |

**Return**: `String`

### `setPassword`

Sets the password for the request.

| Name  | Type   | Required | Default | Description                   |
| ----- | ------ | -------- | ------- | ----------------------------- |
| value | string | true     |         | The password for the request. |

**Return**: `HyperRequest`

### `getTimeout`

Gets the timeout for the request, in seconds.

| Name         | Type | Required | Default | Description |
| ------------ | ---- | -------- | ------- | ----------- |
| No arguments |      |          |         |             |

**Return**: `numeric`

### `setTimeout`

Sets the timeout for the request, in seconds.

| Name  | Type   | Required | Default | Description                              |
| ----- | ------ | -------- | ------- | ---------------------------------------- |
| value | string | true     |         | The timeout for the request, in seconds. |

**Return**: `HyperRequest`

### `withoutRedirecting`

A convenience method to not follow any redirects.

| Name         | Type | Required | Default | Description |
| ------------ | ---- | -------- | ------- | ----------- |
| No arguments |      |          |         |             |

**Return**: `HyperRequest`

### `withoutEncodingUrl`

A convenience method to not encode the url.

{% hint style="warning" %}
**WARNING**: Not supported on Adobe engines.
{% endhint %}

| Name         | Type | Required | Default | Description |
| ------------ | ---- | -------- | ------- | ----------- |
| No arguments |      |          |         |             |

**Return**: `HyperRequest`

### `getMaximumRedirects`

Gets the maximum number of redirects to follow.

| Name         | Type | Required | Default | Description |
| ------------ | ---- | -------- | ------- | ----------- |
| No arguments |      |          |         |             |

**Return**: `numeric | String`

### `setMaximumRedirects`

Sets the maximum number of redirects to follow. A value of `*` will follow redirects infinitely.

| Name  | Type | Required | Default | Description                                |
| ----- | ---- | -------- | ------- | ------------------------------------------ |
| value | any  | true     |         | The maximum number of redirects to follow. |

**Return**: `HyperRequest`

### `getBody`

Gets the body for the request.

| Name         | Type | Required | Default | Description |
| ------------ | ---- | -------- | ------- | ----------- |
| No arguments |      |          |         |             |

**Return**: `any`

### `setBody`

Sets the body for the request. Complex values will be serialized before sending the request.

| Name  | Type | Required | Default | Description               |
| ----- | ---- | -------- | ------- | ------------------------- |
| value | any  | true     |         | The body for the request. |

**Return**: `HyperRequest`

### `hasBody`

Checks if the request has a body.

| Name         | Type | Required | Default | Description |
| ------------ | ---- | -------- | ------- | ----------- |
| No arguments |      |          |         |             |

**Return**: `boolean`

### `getBodyFormat`

Gets the body format for the request.

| Name         | Type | Required | Default | Description |
| ------------ | ---- | -------- | ------- | ----------- |
| No arguments |      |          |         |             |

**Return**: `String`

### `setBodyFormat`

Sets the body format for the request. Recognized values are `formFields`, `json`, or `xml`. It is highly recommended to use `asFormFields`, `asJson`, or `asXML` instead.  If you set this value to a non-recognized value, the body will be passed along as-is to the body of the HTTP request.

| Name  | Type | Required | Default | Description                      |
| ----- | ---- | -------- | ------- | -------------------------------- |
| value | any  | true     |         | The body format for the request. |

**Return**: `HyperRequest`

### `asJson`

A convenience method to set the body format and Content-Type to `json`.

| Name         | Type | Required | Default | Description |
| ------------ | ---- | -------- | ------- | ----------- |
| No arguments |      |          |         |             |

**Return**: `HyperRequest`

### `asFormFields`

A convenience method to set the body format and Content-Type to form fields.

| Name         | Type | Required | Default | Description |
| ------------ | ---- | -------- | ------- | ----------- |
| No arguments |      |          |         |             |

**Return**: `HyperRequest`

### `asXML`

A convenience method to set the body format and Content-Type to `xml`.

| Name         | Type | Required | Default | Description |
| ------------ | ---- | -------- | ------- | ----------- |
| No arguments |      |          |         |             |

**Return**: `HyperRequest`

### `getReferrer`

Gets the referrer for the request, if any.

| Name         | Type | Required | Default | Description |
| ------------ | ---- | -------- | ------- | ----------- |
| No arguments |      |          |         |             |

**Return**: `String`

### `getHeaders`

Gets the headers for the request.

| Name         | Type | Required | Default | Description |
| ------------ | ---- | -------- | ------- | ----------- |
| No arguments |      |          |         |             |

**Return**: `java.util.LinkedHashMap`

### `setHeaders`

Sets the headers for the request.

| Name  | Type   | Required | Default | Description                  |
| ----- | ------ | -------- | ------- | ---------------------------- |
| value | struct | true     |         | The headers for the request. |

**Return**: `HyperRequest`

### `setHeader`

Set a header for the request.

| Name  | Type   | Required | Default | Description              |
| ----- | ------ | -------- | ------- | ------------------------ |
| name  | string | true     |         | The name of the header.  |
| value | string | true     |         | The value of the header. |

**Return**: `HyperRequest`

### `withHeaders`

Add additional headers to the request.

| Name    | Type   | Required | Default | Description                                |
| ------- | ------ | -------- | ------- | ------------------------------------------ |
| headers | struct | true     |         | A struct of headers to add to the request. |

**Return**: `HyperRequest`

### `forwardHeaders`

Adds specified headers to the request if they exist. Usually used in conjunction with the current CFML request headers.

| Name    | Type   | Required | Default                               | Description                                                                           |
| ------- | ------ | -------- | ------------------------------------- | ------------------------------------------------------------------------------------- |
| names   | array  | true     |                                       | An array of header names to add to the request if they exist in the `headers` struct. |
| headers | struct | false    | `getHTTPRequestData( false ).headers` | A struct of headers to inspect.                                                       |

**Return**: `HyperRequest`

### `hasHeader`

Check if the request has a header with the given name.

| Name | Type   | Required | Default | Description                      |
| ---- | ------ | -------- | ------- | -------------------------------- |
| name | string | true     |         | The name of the header to check. |

**Return**: `boolean`

### `setContentType`

A convenience method to set the [`Content-Type` header](https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Content-Type).

| Name | Type   | Required | Default | Description                            |
| ---- | ------ | -------- | ------- | -------------------------------------- |
| type | string | true     |         | The Content-Type value for the request |

**Return**: `HyperRequest`

### `setAccept`

A convenience method to set the [`Accept` header](https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Accept).

| Name | Type   | Required | Default | Description                      |
| ---- | ------ | -------- | ------- | -------------------------------- |
| type | string | true     |         | The Accept value for the request |

**Return**: `HyperRequest`

### `getQueryParams`

Gets the query parameters for the request.

{% hint style="warning" %}
This method returns an array of param structs that is used under the hood by Hyper. You probably want to use [`getQueryParamByName`](#getqueryparambyname) or [`getAllQueryParamsByName`](#getallqueryparamsbyname) instead.
{% endhint %}

| Name         | Type | Required | Default | Description |
| ------------ | ---- | -------- | ------- | ----------- |
| No arguments |      |          |         |             |

**Return**: `array<struct<string, any>>`

### `setQueryParams`

Sets the query parameters for the request.

{% hint style="warning" %}
This method accepts an array of param structs that is used under the hood by Hyper. You probably want to use [`withQueryParams`](#withqueryparams) or [`appendQueryParams`](#appendqueryparams) instead.
{% endhint %}

If needed, param structs have two keys, `name` and `value`.

| Name  | Type  | Required | Default | Description                                                |
| ----- | ----- | -------- | ------- | ---------------------------------------------------------- |
| value | array | true     |         | The query parameters for the as an array of param structs. |

**Return**: `HyperRequest`

### `getQueryParam`

{% hint style="danger" %}
**DEPRECATED:** Use [`getQueryParamByName`](#getqueryparambyname)
{% endhint %}

Gets the first value for a certain query parameter. Returns an empty string if the query parameter does not exist.

| Name | Type   | Required | Default | Description                                                  |
| ---- | ------ | -------- | ------- | ------------------------------------------------------------ |
| name | string | true     |         | The name of the query parameter to retrieve the first value. |

**Return**: `any`

### `getQueryParamByName`

Gets the first value for a certian query parameter. Returns an empty string if the query parameter does not exist.

| Name | Type   | Required | Default | Description                                                  |
| ---- | ------ | -------- | ------- | ------------------------------------------------------------ |
| name | string | true     |         | The name of the query parameter to retrieve the first value. |

**Return**: `any`

### `getAllQueryParamsByName`

Get all the values for a certain query parameter. Returns an empty array if the query parameter does not exist.

| Name | Type   | Required | Default | Description                                                    |
| ---- | ------ | -------- | ------- | -------------------------------------------------------------- |
| name | string | true     |         | The name of the query parameter to retrieve all of its values. |

**Return**: `array<any>`

### `setQueryParam`

Set a query parameter for the request.

{% hint style="info" %}
**Note:** This removes all other query params with the same name.
{% endhint %}

| Name  | Type   | Required | Default | Description                       |
| ----- | ------ | -------- | ------- | --------------------------------- |
| name  | string | true     |         | The name of the query parameter.  |
| value | string | true     |         | The value of the query parameter. |

**Return**: `HyperRequest`

### `appendQueryParam`

Append a query parameter for the request.

| Name  | Type   | Required | Default | Description                       |
| ----- | ------ | -------- | ------- | --------------------------------- |
| name  | string | true     |         | The name of the query parameter.  |
| value | string | true     |         | The value of the query parameter. |

**Return**: `HyperRequest`

### `withQueryParams`

Add additional query parameters to the request.&#x20;

{% hint style="info" %}
**Note:** This will remove any values with duplicate keys prior to adding the new struct of params.
{% endhint %}

| Name        | Type   | Required | Default | Description                                         |
| ----------- | ------ | -------- | ------- | --------------------------------------------------- |
| queryParams | struct | true     |         | A struct of query parameters to add to the request. |

**Return**: `HyperRequest`

### `appendQueryParams`

Appends additional query parameters to the request.

| Name        | Type   | Required | Default | Description                                         |
| ----------- | ------ | -------- | ------- | --------------------------------------------------- |
| queryParams | struct | true     |         | A struct of query parameters to add to the request. |

**Return**: `HyperRequest`

### `hasQueryParam`

Check if the request has a query parameter with the given name.

| Name | Type   | Required | Default | Description                               |
| ---- | ------ | -------- | ------- | ----------------------------------------- |
| name | string | true     |         | The name of the query parameter to check. |

**Return**: `boolean`

### `attach`

Attaches a file to the Hyper request. Also sets the Content-Type as `multipart/form-data`. Multiple files can be attached by calling `attach` multiple times before calling a send method.

| Name     | Type   | Required | Default | Description                                       |
| -------- | ------ | -------- | ------- | ------------------------------------------------- |
| name     | string | true     |         | The name of the file being uploaded.              |
| path     | string | true     |         | The absolute path to the file to be uploaded.     |
| mimeType | string | false    |         | An optional mime type to associate with the file. |

**Return**: `HyperRequest`

### `setThrowOnError`

Sets the throw on error property for the request. If true, statuses in the 4xx and 5xx range will be turned in to exceptions.

| Name  | Type    | Required | Default | Description                           |
| ----- | ------- | -------- | ------- | ------------------------------------- |
| value | boolean | true     |         | The value of the throw on error flag. |

**Return**: `HyperRequest`

### `throwErrors`

A convenience method to throw on errors.

| Name         | Type | Required | Default | Description |
| ------------ | ---- | -------- | ------- | ----------- |
| No arguments |      |          |         |             |

**Return**: `HyperRequest`

### `allowErrors`

A convenience method to not throw on errors.

| Name         | Type | Required | Default | Description |
| ------------ | ---- | -------- | ------- | ----------- |
| No arguments |      |          |         |             |

**Return**: `HyperRequest`

### `clone`

Clones the current request into a new HyperRequest.

| Name         | Type | Required | Default | Description |
| ------------ | ---- | -------- | ------- | ----------- |
| No arguments |      |          |         |             |

**Return**: A new `HyperRequest` instance cloned from this one.

### `clear`

Clears the request of any set values, including defaults passed by the builder.

| Name         | Type | Required | Default | Description |
| ------------ | ---- | -------- | ------- | ----------- |
| No arguments |      |          |         |             |

**Return**: `HyperRequest`

### `when`

Helper to conditionally execute a callback for the `HyperRequest`. This method lets you use conditionals without breaking chaining.

| Name            | Type       | Required | Default | Description                                                                                            |
| --------------- | ---------- | -------- | ------- | ------------------------------------------------------------------------------------------------------ |
| condition       | `boolean`  | `true`   |         | The condition to check.                                                                                |
| successCallback | `function` | `true`   |         | The callback to execute if the condition is true. The callback is passed the `HyperRequest` instance.  |
| failureCallback | `function` | `false`  | `null`  | The callback to execute if the condition is false. The callback is passed the `HyperRequest` instance. |

**Return**: `HyperRequest`

### `setProperties`

Quickly set many request properties using a struct. The key should be the name of one of the properties on the request, e.g. `url`, `headers`, `method`, `body`.

| Name       | Type   | Required | Default | Description                                                                                                                                   |
| ---------- | ------ | -------- | ------- | --------------------------------------------------------------------------------------------------------------------------------------------- |
| properties | struct | true     |         | A struct of properties to set. Each property name will be set on the request. Properties that don't exist on the request will throw an error. |

**Return**: `HyperRequest`

### `setHttpClient`

Sets the [HTTP Client](/7.0.0-2/customizing-hyper/custom-http-clients) to use for the request. The client should conform to the `HyperHttpClientInterface` (though it does not need to use the `implements` keyword).

| Name       | Type                       | Required | Default | Description                            |
| ---------- | -------------------------- | -------- | ------- | -------------------------------------- |
| httpClient | `HyperHttpClientInterface` | `true`   |         | The httpClient to use for the request. |

**Return**: `HyperRequest`

### `setInterceptorService`

Sets the [ColdBox Interceptor Service](https://coldbox.ortusbooks.com/the-basics/interceptors) to announce request and response interception points. A noop option is provided in the `init` for non-ColdBox usage.

| Name               | Type | Required | Default | Description                                     |
| ------------------ | ---- | -------- | ------- | ----------------------------------------------- |
| interceptorService | any  | `true`   |         | The interceptor service to use for the request. |

**Return**: `HyperRequest`

### `setAsyncManager`

Sets the [ColdBox AsyncManager](https://coldbox.ortusbooks.com/digging-deeper/promises-async-programming) to send requests asynchronously. A noop option is provided in the `init` for non-ColdBox usage.

| Name         | Type | Required | Default | Description                              |
| ------------ | ---- | -------- | ------- | ---------------------------------------- |
| asyncManager | any  | `true`   |         | The asyncManager to use for the request. |

**Return**: `HyperRequest`

### `getMemento`

Returns a struct representing this `HyperRequest`.

| Name         | Type | Required | Default | Description |
| ------------ | ---- | -------- | ------- | ----------- |
| No arguments |      |          |         |             |

**Return**:

```json
{
    "requestID"          : getRequestID(),
    "baseUrl"            : getBaseUrl(),
    "url"                : getUrl(),
    "fullUrl"            : getFullUrl(),
    "method"             : getMethod(),
    "queryParams"        : getQueryParams(),
    "headers"            : getHeaders(),
    "files"              : getFiles(),
    "bodyFormat"         : getBodyFormat(),
    "body"               : getBody(),
    "referrer"           : isNull( variables.referrer ) ? "" : variables.referrer,
    "throwOnError"       : getThrowOnError(),
    "timeout"            : getTimeout(),
    "maximumRedirects"   : getMaximumRedirects(),
    "authType"           : getAuthType(),
    "username"           : getUsername(),
    "password"           : getPassword(),
    "clientCert"         : isNull( variables.clientCert ) ? "" : variables.clientCert,
    "clientCertPassword" : isNull( variables.clientCertPassword ) ? "" : variables.clientCertPassword,
    "domain"             : getDomain(),
    "workstation"        : getWorkstation(),
    "resolveUrls"        : getResolveUrls(),
    "encodeUrl"          : getEncodeUrl()
};
```

### `debug`

Creates a debug representation of the HTTP request for the current HTTP client.

{% hint style="danger" %}
**Throws**: `NoUrlException` when no URL is set.
{% endhint %}

| Name         | Type | Required | Default | Description |
| ------------ | ---- | -------- | ------- | ----------- |
| No arguments |      |          |         |             |

**Return**: Dependent on the configured HTTP Client.  See specific HTTP Client documentation for details.


# HyperResponse

The `HyperResponse` component is a read-only wrapper to easily grab different information about the response.

### `getResponseId`

Gets the unique response ID representing this response.

| Name         | Type | Required | Default | Description |
| ------------ | ---- | -------- | ------- | ----------- |
| No arguments |      |          |         |             |

**Return**: `String`

### `getStatusCode`

Gets the status code for the response.

| Name         | Type | Required | Default | Description |
| ------------ | ---- | -------- | ------- | ----------- |
| No arguments |      |          |         |             |

**Return**: `numeric`

### `getStatusText`

Gets the status text for the response.

| Name         | Type | Required | Default | Description |
| ------------ | ---- | -------- | ------- | ----------- |
| No arguments |      |          |         |             |

**Return**: `String`

### `getStatus`

Returns the status code and status text as a single string.

| Name         | Type | Required | Default | Description |
| ------------ | ---- | -------- | ------- | ----------- |
| No arguments |      |          |         |             |

**Return**: `String`

### `getData`

Gets the data for the response.

| Name         | Type | Required | Default | Description |
| ------------ | ---- | -------- | ------- | ----------- |
| No arguments |      |          |         |             |

**Return**: `String`

### `getRequestID`

Returns the id of the request to which this response is related.

| Name         | Type | Required | Default | Description |
| ------------ | ---- | -------- | ------- | ----------- |
| No arguments |      |          |         |             |

**Return**: `String`

### `getRequest`

Gets the [HyperRequest](/7.0.0-2/making-requests/hyperrequest) instance associated with this response.

| Name         | Type | Required | Default | Description |
| ------------ | ---- | -------- | ------- | ----------- |
| No arguments |      |          |         |             |

**Return**: [`HyperRequest`](/7.0.0-2/making-requests/hyperrequest)

### `getCharset`

Gets the charset value for the response.

| Name         | Type | Required | Default | Description |
| ------------ | ---- | -------- | ------- | ----------- |
| No arguments |      |          |         |             |

**Return**: `String`

### `getTimestamp`

Gets the timestamp for when this response was received.

| Name         | Type | Required | Default | Description |
| ------------ | ---- | -------- | ------- | ----------- |
| No arguments |      |          |         |             |

**Return**: `DateTime`

### `getExecutionTime`

Gets the execution time of the request, in milliseconds.

| Name         | Type | Required | Default | Description |
| ------------ | ---- | -------- | ------- | ----------- |
| No arguments |      |          |         |             |

**Return**: `numeric`

### `json`

Returns the data of the request as deserialized `JSON`.

{% hint style="danger" %}
**Throws**: `DeserializeJsonException` if the response is not `JSON`.
{% endhint %}

| Name         | Type | Required | Default | Description |
| ------------ | ---- | -------- | ------- | ----------- |
| No arguments |      |          |         |             |

**Return**: `any`

### `isSuccess`

Returns true if the request status code is considered successful.

| Name         | Type | Required | Default | Description |
| ------------ | ---- | -------- | ------- | ----------- |
| No arguments |      |          |         |             |

**Return**: `boolean`

### `isOK`

Returns true if the request status code is `200 OK`.

| Name         | Type | Required | Default | Description |
| ------------ | ---- | -------- | ------- | ----------- |
| No arguments |      |          |         |             |

**Return**: `boolean`

### `isCreated`

Returns true if the request status code is `201 Created`.

| Name         | Type | Required | Default | Description |
| ------------ | ---- | -------- | ------- | ----------- |
| No arguments |      |          |         |             |

**Return**: `boolean`

### `isRedirect`

Returns true if the request status code is considered a redirect.

| Name         | Type | Required | Default | Description |
| ------------ | ---- | -------- | ------- | ----------- |
| No arguments |      |          |         |             |

**Return**: `boolean`

### `isError`

Returns true if the request status code is considered either a client error (4xx status code) or a server error (5xx status code).

| Name         | Type | Required | Default | Description |
| ------------ | ---- | -------- | ------- | ----------- |
| No arguments |      |          |         |             |

**Return**: `boolean`

### `isClientError`

Returns true if the request status code is considered a client error (4xx status code).

| Name         | Type | Required | Default | Description |
| ------------ | ---- | -------- | ------- | ----------- |
| No arguments |      |          |         |             |

**Return**: `boolean`

### `isUnauthorized`

Returns true if the request status code is `401 Unauthorized`.

| Name         | Type | Required | Default | Description |
| ------------ | ---- | -------- | ------- | ----------- |
| No arguments |      |          |         |             |

**Return**: `boolean`

### `isForbidden`

Returns true if the request status code is `403 Forbidden`.

| Name         | Type | Required | Default | Description |
| ------------ | ---- | -------- | ------- | ----------- |
| No arguments |      |          |         |             |

**Return**: `boolean`

### `isNotFound`

Returns true if the request status code is `404 Not Found`.

| Name         | Type | Required | Default | Description |
| ------------ | ---- | -------- | ------- | ----------- |
| No arguments |      |          |         |             |

**Return**: `boolean`

### `isServerError`

Returns true if the request status code is considered a server error (5xx status code).

| Name         | Type | Required | Default | Description |
| ------------ | ---- | -------- | ------- | ----------- |
| No arguments |      |          |         |             |

**Return**: `boolean`

### `hasHeader`

Checks if a header exists in the response.

| Name | Type     | Required | Default | Description                      |
| ---- | -------- | -------- | ------- | -------------------------------- |
| name | `String` | `true`   |         | The name of the header to check. |

**Return**: `boolean`

### `getHeader`

Gets the value of a header from the response.

| Name         | Type     | Required | Default | Description                                       |
| ------------ | -------- | -------- | ------- | ------------------------------------------------- |
| name         | `String` | `true`   |         | The name of the header to retrieve.               |
| defaultValue | `any`    | `false`  | `""`    | The value to return if the header does not exist. |

**Return**: `any`

### `getMemento`

Gets a serializable representation of the response.

| Name         | Type | Required | Default | Description |
| ------------ | ---- | -------- | ------- | ----------- |
| No arguments |      |          |         |             |

**Return**:

```json
{
    "responseID"    : getResponseID(),
    "requestID"     : getRequestID(),
    "statusCode"    : getStatusCode(),
    "statusText"    : getStatusText(),
    "status"        : getStatus(),
    "data"          : getData(),
    "charset"       : getCharset(),
    "headers"       : getHeaders(),
    "timestamp"     : getTimestamp(),
    "executionTime" : getExecutionTime()
}
```


# Hyper Clients

Hyper allows you to configure defaults for your requests as custom Hyper Clients. This is particularly useful for reducing boilerplate in your application.

Defaults are set on the `HyperBuilder` instance. The easiest way to do this is to configure it in WireBox:

```js
// config/WireBox.cfc
component {

    function configure() {
        map( "StarWarsClient" )
            .to( "hyper.models.HyperBuilder" )
            .asSingleton()
            .initWith(
                baseUrl = "https://swapi.dev/api"
            );
    }

}
```

Now, you can inject this pre-configured builder wherever you need in your application:

```js
component {

    property name="StarWarsClient" inject="StarWarsClient";

    function findUser( id ) {
        return variables.StarWarsClient.get( "/people/#id#" );
    }

}
```

You can even create multiple clients using this approach:

```js
// config/WireBox.cfc
component {

    function configure() {
        map( "SWAPIClient" )
            .to( "hyper.models.HyperBuilder" )
            .asSingleton()
            .initWith(
                baseUrl = "https://swapi.dev/api"
            );

        map( "GitHubClient" )
            .to( "hyper.models.HyperBuilder" )
            .asSingleton()
            .initWith(
                baseUrl = "https://api.github.com",
                headers = {
                    "Authorization" = getColdBox().getUtil().getSystemSetting( "GITHUB_TOKEN" )
                }
            );
    }

}
```

You can also set or change the defaults by either passing the key / value pairs in to the `init` method or by calling the appropriate `HyperRequest` method on the `HyperBuilder.defaults` property.

```js
var hyper = new Hyper.models.HyperBuilder(
    baseUrl = "https://api.github.com"
);
hyper.defaults.withHeaders( { "Authorization" = token } );
```

The defaults set here need to match the property names on the `HyperRequest`. These are:

```cfscript
/**
* The httpClient to use for the request
*/
property name="httpClient";

/**
* The baseURL for the request.
* e.g. https://api.github.com/
*/
property name="baseUrl" default="";

/**
* The URL for the request.
* It can either be a full url
* or a URI resource for use with the baseURL.
* e.g. /repos
*/
property name="url" default="";

/**
* Setting this to true will change all relative urls in the document to absolute.
*/
property name="resolveUrls" default="false";

/**
* Setting this to false will not automatically encode the url passed.
* WARNING: Setting this to false is not supported on Adobe engines.
*/
property name="encodeUrl" default="true";

/**
* The HTTP method for the request.
*/
property name="method" default="GET";

/**
* The username for the request for basic auth.
*/
property name="username" default="";

/**
* The password for the request for basic auth.
*/
property name="password" default="";

/**
* Timeout, in seconds, for the request.
*/
property name="timeout" default="10";

/**
* The maximum number of redirects to follow.
* A value of `*` will follow redirects infinitely.
*/
property name="maximumRedirects" default="*";

/**
* The body to send with the request.
* How the body is serialized is
* determined by the bodyFormat.
*/
property name="body" default="";

/**
* The format to serialize the body.
* e.g. `json` or `formFields`
*/
property name="bodyFormat" default="json";

/**
* The referring response in the case of redirects.
*/
property name="referrer";

/**
* A struct of headers for the request.
*/
property name="headers";

/**
* A struct of query parameters for the request.
*/
property name="queryParams";

/**
* Flag to throw on a cfhttp error.
*/
property name="throwOnError" default="false";

/**
* The full path to a PKCS12 format file that contains the client certificate for the request.
*/
property name="clientCert";

/**
* 	Password used to decrypt the client certificate.
*/
property name="clientCertPassword";

/**
* The domain for the request for NTLM auth.
*/
property name="domain" default="";

/**
* The workstation for the request for NTLM auth.
*/
property name="workstation" default="";

/**
* The authType for the request
*/
property name="authType" default="BASIC";

/**
* An array of callback functions to call
* before firing off a request.
*/
property name="requestCallbacks" type="array";

/**
* An array of callback functions to call
* after receiving a response.
*/
property name="responseCallbacks" type="array";
```

If you need per-request or per-response manipulation of defaults, use the [`requestCallbacks`](/7.0.0-2/making-requests/hyperrequest#withrequestcallback) and [`responseCallbacks`](/7.0.0-2/making-requests/hyperrequest#withresponsecallback) hooks.

```cfscript
map( "ApiClient" )
    .to( "hyper.models.HyperBuilder" )
    .asSingleton()
    .initWith(
        baseUrl = getColdBox().getUtil().getSystemSetting( "API_URL" ),
        requestCallbacks = [
            // provide the current user's token for the request
            function( req ) {
                var auth = getWireBox().getInstance( "AuthenticationService@cbauth" );
                req.withHeaders( "Authorization", auth.user().getApiToken() );
            }
        ],
        responseCallbacks = [
            // map custom `error` property to an exception
            function ( res ) {
                if ( !res.isError() ) {
                    return;
                }
                
                var body = res.json();
                throw(
                    type = "ApiError",
                    message = body.error.message,
                    detail = body.error.code
                );
            }
        ]
    );
```


# Custom HTTP Clients

By default, Hyper makes HTTP requests using `cfhttp` under the hood.  This can be swapped out by any compatible HTTP client that follows the `HyperHttpClientInterface`.

```cfscript
/**
 * Responsible for executing the HyperRequest and mapping it to a HyperResponse
 */
interface displayname="HyperHttpClientInterface" {

	/**
	 * Execute the HyperRequest and map it to a HyperResponse.
	 *
	 * @req     The HyperRequest to execute.
	 *
	 * @returns A HyperResponse of the executed request.
	 */
	public HyperResponse function send( required HyperRequest req );

	/**
	 * Return a struct of information showing how the client will execute the HyperRequest.
	 * This will be used by a developer to debug any differences between the generated
	 * request values and the expected request values.
	 *
	 * @req     The HyperRequest to debug.
	 *
	 * @returns A struct of information detailing how the client would execute the HyperRequest.
	 */
	public struct function debug( required HyperRequest req );

}
```


# CfhttpHttpClient

### `debug`

Return a struct of information showing how the client will execute the [`HyperRequest`](/7.0.0-2/making-requests/hyperrequest). This will be used by a developer to debug any differences between the generated request values and the expected request values.

| Name | Type                                                    | Required | Default | Description                                                           |
| ---- | ------------------------------------------------------- | -------- | ------- | --------------------------------------------------------------------- |
| req  | [`HyperRequest`](/7.0.0-2/making-requests/hyperrequest) | `true`   |         | The [`HyperRequest`](/7.0.0-2/making-requests/hyperrequest) to debug. |

**Return**:

```json
{
    "attributes" : attrCollection,
    "body"       : {
        "headers" : cfhttpHeaders,
        "params"  : cfhttpParams,
        "files"   : cfhttpFiles,
        "body"    : cfhttpBody
    }
}
```


# Introduction

## A CFML HTTP Builder

### Inspiration

Hyper was built after coding several API SDK's for various platforms — [S3SDK](https://github.com/coldbox-modules/s3sdk), [cbstripe](https://github.com/coldbox-modules/cbox-stripe), and [cbgithub](https://github.com/elpete/cbgithub), to name a few. We noticed that we spent a lot of time setting up the plumbing for the requests and a wrapper around `cfhttp`. Each implementation was mostly the same but slightly different. It was additionally frustrating because we really only needed to tweak a few values, usually just the `Authorization` header. It would be nice to create an HTTP client pre-configured for each of these SDK's. It seemed the perfect fit for a module.

### The problem it solves

Hyper exists to provide a fluent builder experience for HTTP requests and responses. It also provides a powerful way to create clients, i.e. Builder objects with pre-configured defaults like a base URL or certain headers.


# What's New?

## 7.1.0

### Fake Requests

Hyper now has the ability to fake requests and return fake responses as a result.  This is perfect for testing scenarios where you don't actually want to make an HTTP request.

{% content-ref url="/pages/fDs68ouvcjilusPgzOdw" %}
[Faking Requests](/7.1.0-1/testing/faking-requests)
{% endcontent-ref %}

### Custom Hyper Clients

It is now more straightforward to register a [custom Hyper client](/7.1.0-1/customizing-hyper/custom-http-clients).  Inside your `config/WireBox.cfc` in an `afterAspectsLoad` method, you can get a reference to a `HyperBuilder`, configure it as you would for a request, and then call the `registerAs` method passing in your desired WireBox alias.

```cfscript
// config/WireBox.cfc
component {

   // ...
   
   function afterApsectsLoad() {
       injector.getInstance( "HyperBuilder@hyper" )
           .setBaseUrl( "https://api.github.com" )
           .asJson()
           .withHeaders( {
               "Authorization": coldbox.getUtil().getSystemSetting( "GITHUB_TOKEN" )
           } )
           .registerAs( "GitHubClient" );
   }

}
```

This is a welcome improvement as the `init` arguments do not exactly match the method names.  Also, for defaults like `requestCallbacks`, `responseCallbacks`, or even `queryParams`, passing in arrays of functions or arrays or structs is not as straightforward as calling the related methods.  Now, you can use the Hyper methods you are familiar with when registering your custom Hyper clients.

{% hint style="info" %}
Putting the registration code in `afterAspectsLoad` is required so Hyper can be loaded and available for injection.
{% endhint %}

## 7.0.0

### CFHttp HTTP Client

This client now returns more accurate status codes for `502 Bad Gateway` and `408 Request Timeout` responses.

Previously, these responses were returned as `504 Gateway Timeout` responses. Hyper now normalizes the responses from the different CFML engines into a consistent response. `502 Bad Gateway` is returned instead of `504 Gateway Timeout` for invalid hosts. `408 Request Timeout` is returned if the request takes longer than the configured [`timeout`](/7.1.0-1/making-requests/hyperrequest#settimeout) value.

### Breaking Changes

If you were previously checking specifically for `504` status codes for bad hosts, you need to now either check for `502` status codes or use a more general method, like [`isServerError`](/7.1.0-1/making-requests/hyperresponse#isservererror) or [`isError`](/7.1.0-1/making-requests/hyperresponse#iserror).

If you were previously checking specifically for `504` status codes or [`isServerError`](/7.1.0-1/making-requests/hyperresponse#isservererror) for timed out requests, you need to now either check for `408` status codes, [`isClientError`](/7.1.0-1/making-requests/hyperresponse#isclienterror), or the more general [`isError`](/7.1.0-1/making-requests/hyperresponse#iserror).

## 6.1.0

Add [`head`](/7.1.0-1/making-requests/hyperrequest#head) and [`options`](/7.1.0-1/making-requests/hyperrequest#options) shortcut methods.

## 6.0.0

* Add `xml` support and an `asXML` method to set the body format and `Content-Type` header.
* Add `adobe@2023` to testing matrix.

### Breaking Changes

* Remove default `Content-Type` header. You must set this [manually](/7.1.0-1/making-requests/hyperrequest#setcontenttype) or use a format helper, such as [`asJson`](/7.1.0-1/making-requests/hyperrequest#asjson).
* Dropped `adobe@2016` support.

## 5.0.1

Correctly handle cases when the `body` is a string and format is `JSON`.

## 5.0.0

Add a `debug` method to see what the HTTP client generates.

### Breaking Changes

`HyperHttpClientInterface` now requires a `debug` method.

```cfscript
/**
 * Return a struct of information showing how the client will execute the HyperRequest.
 * This will be used by a developer to debug any differences between the generated
 * request values and the expected request values.
 *
 * @req     The HyperRequest to debug.
 *
 * @returns A struct of information detailing how the client would execute the HyperRequest.
 */
public struct function debug( required HyperRequest req );
```

## 4.0.3

* Do not prepend the base url when a full url is passed.
* Add `resolveUrls` and `encodeUrl` properties to the [memento](/7.1.0-1/making-requests/hyperrequest#getmemento).
* Correctly set the `encodeUrl` property when cloning a request.

## 4.0.2

Update README for builder `initWith` headers losing `Content-Type`.

## 4.0.1

Fix `HyperBuilder` example in the docs.

## 4.0.0

Allow adding multiple query params with the same key.

### Breaking Changes

Previously, query params were stored as a struct.  Some APIs expect multiple values for the same query param name to be passed as separate arguments.  Hyper now stores the query params as an array and provides new methods for interacting with query params:

* [`getQueryParamByName`](/7.1.0-1/making-requests/hyperrequest#getqueryparambyname)
* [`getAllQueryParamsByName`](/7.1.0-1/making-requests/hyperrequest#getallqueryparamsbyname)
* [`withQueryParams`](/7.1.0-1/making-requests/hyperrequest#withqueryparams)
* [`appendQueryParam`](/7.1.0-1/making-requests/hyperrequest#appendqueryparam)
* [`appendQueryParams`](/7.1.0-1/making-requests/hyperrequest#appendqueryparams)
* [`hasQueryParam`](/7.1.0-1/making-requests/hyperrequest#hasqueryparam)

The following methods still exist, but now interact with arrays of query param structs instead of a simple struct.

* [`getQueryParams`](/7.1.0-1/making-requests/hyperrequest#getqueryparams)
* [`setQueryParams`](/7.1.0-1/making-requests/hyperrequest#setqueryparams)

The following methods have been deprecated:

| Deprecated Method                                                      | Replacement Method                                                                 |
| ---------------------------------------------------------------------- | ---------------------------------------------------------------------------------- |
| [`getQueryParam`](/7.1.0-1/making-requests/hyperrequest#getqueryparam) | [`getQueryParamByName`](/7.1.0-1/making-requests/hyperrequest#getqueryparambyname) |

## 3.6.2

Convert array values correctly when sending form fields

## 3.6.1

Add a workaround for CommandBox not having the `box:asyncManager` injection DSL.

## 3.6.0

Add async requests using ColdBox's [AsyncManager](https://coldbox.ortusbooks.com/digging-deeper/promises-async-programming).

## 3.5.0

* Provide more useful error than cfhttp when [`throwOnErrors`](/7.1.0-1/making-requests/hyperrequest#throwerrors) is enabled.
* Provide mementos for [HyperRequest](/7.1.0-1/making-requests/hyperrequest#getmemento) and [HyperResponse](/7.1.0-1/making-requests/hyperresponse#getmemento) instances.
* Capture [statusText](/7.1.0-1/making-requests/hyperresponse#getstatustext) and provide a [status](/7.1.0-1/making-requests/hyperresponse#getstatus) convenience string.

## 3.4.2

Add MIT License file

## 3.4.1

Use `processState` over `announce` until CommandBox can update its `interceptorService`.

## 3.4.0

### HyperRequest

* Add [`forwardHeaders`](/7.1.0-1/making-requests/hyperrequest#forwardheaders) shortcut method.

### HyperResponse

* Allow for default values in [`getHeader`](/7.1.0-1/making-requests/hyperresponse#getheader).
* Add helper methods for checking for specific status codes:
  * [`isOk`](/7.1.0-1/making-requests/hyperresponse#isok)
  * [`isUnauthorized`](/7.1.0-1/making-requests/hyperresponse#isunauthorized)
  * [`isForbidden`](/7.1.0-1/making-requests/hyperresponse#isforbidden)
  * [`isNotFound`](/7.1.0-1/making-requests/hyperresponse#isnotfound)

## 3.3.0

Allowing [attaching](/7.1.0-1/making-requests/hyperrequest#attach) file uploads.

## 3.2.1

Support WireBox outside of ColdBox.

## 3.2.0

Include response data as detail in `DeserializeJsonException`.

## 3.1.0

* Add [`clone`](/7.1.0-1/making-requests/hyperrequest#clone) to quickly copy `HyperRequest` instances.
* Add interceptors and [local](/7.1.0-1/making-requests/hyperrequest#withrequestcallback) [callbacks](/7.1.0-1/making-requests/hyperrequest#withresponsecallback) for lifecycle events.

## 3.0.0

Add execution time to `HyperResponse` instances.

### Breaking Changes

Dropped support for ColdBox 5.

## 2.3.11

* Add support for [NTLM authentication](/7.1.0-1/making-requests/hyperrequest#withntlmauth).
* Include [`getFullURL`](/7.1.0-1/making-requests/hyperrequest#getfullurl) method in docs.

## 2.3.10

Fixed typo of `Bulider` to `Builder`.

## 2.3.9

Add [`withoutEncodingUrl`](/7.1.0-1/making-requests/hyperrequest#withoutencodingurl) flag.

## 2.3.8

Do not fail fast on cron job actions on CI.

## 2.3.7

Update fetch-depth for tests and release actions on CI.

## 2.3.6

Attempt to skip committing back changes on CI.

## 2.3.5

Add matrix and cron testing on CI.

## 2.3.4

Use better GitHub token on CI

## 2.3.1

Add workaround for `boolean` values in query strings.

## 2.3.0

Add [certificate](/7.1.0-1/making-requests/hyperrequest#withcertificateauth) auth.

## 2.2.1

Use the previous host for redirect if redirect does not include a full URL.

## 2.2.0

Add [`resolveUrls`](/7.1.0-1/making-requests/hyperrequest#setresolveurl) flag.

## 2.1.1

* Use OpenJDK instead of OracleJDK on CI.
* Store module in [ForgeBox Storage](https://commandbox.ortusbooks.com/5.6.0/developing-for-commandbox/commands).

## 2.1.0

Allow for pluggable [HTTP Clients](/7.1.0-1/customizing-hyper/custom-http-clients) that follow the `HyperHttpClientInterface`. (Clients do not need to use the `implements` keyword.)

## 2.0.2

Avoid double encoding using [`cfhttpparam`](https://cfdocs.org/cfhttpparam).

## 2.0.1

Remove Lucee 4.5 support from docs. (Support was dropped in [v2.0.0](#2.0.0))

## 2.0.0

* Do not include [`username`](/7.1.0-1/making-requests/hyperrequest#setusername) and [`password`](/7.1.0-1/making-requests/hyperrequest#setpassword) unless they have values.
* Add `adobe@2018` support to CI builds.

### Breaking Changes

Dropped support for `lucee@4.5`.

## 1.15.0

Add [`throwOnError`](/7.1.0-1/making-requests/hyperrequest#throwerrors) flag.

## 1.14.5

Use `504 Gateway Timeout` for incomplete responses.

## 1.14.4

Include equal signs in query param values.

## 1.14.0 – 1.0.0

### New Features

* Add [`when`](/7.1.0-1/making-requests/hyperrequest#when) helper to execute conditions without breaking chaining.
* Add [`clear`](/7.1.0-1/making-requests/hyperrequest#clear) method to reset HyperRequest instances.
* Add configurable [`timeout`](/7.1.0-1/making-requests/hyperrequest#settimeout).

### Bug Fixes

* Fix for Lucee 4 compatibility on `LinkedHashMaps` and `keyArray`.
* Preserve case in header names.
* Preserve case for query parameters.
* Serialize both params from the url and set on the `HyperRequest` instance.
* Default to `UTF-8` charset if none is present in the response.
* Fix withHeaders and withQueryParams for Lucee compatibility.
* Only map HyperBuilder as a singleton in WireBox

### Other

* Migrate to [coldbox-modules](https://github.com/coldbox-modules) organization on GitHub.
* Update `box.json` description.
* Enable [CommandBox Semantic Release](https://forgebox.io/view/commandbox-semantic-release) on CI.


# Upgrade Guide

## Upgrading from v6 to v7

### CFHttp HTTP Client

This client now returns more accurate status codes for `502 Bad Gateway` and `408 Request Timeout` responses.

If you were previously checking specifically for `504` status codes for bad hosts, you need to now either check for `502` status codes or use a more general method, like [`isServerError`](/7.1.0-1/making-requests/hyperresponse#isservererror) or [`isError`](/7.1.0-1/making-requests/hyperresponse#iserror).

If you were previously checking specifically for `504` status codes or [`isServerError`](/7.1.0-1/making-requests/hyperresponse#isservererror) for timed out requests, you need to now either check for `408` status codes, [`isClientError`](/7.1.0-1/making-requests/hyperresponse#isclienterror), or the more general [`isError`](/7.1.0-1/making-requests/hyperresponse#iserror).

## Upgrading from v5 to v6

* The default `Content-Type` header has been removed. You must set this [manually](/7.1.0-1/making-requests/hyperrequest#setcontenttype) or use a format helper, such as [`asJson`](/7.1.0-1/making-requests/hyperrequest#asjson).
* Dropped support for Adobe 2016.

## Upgrading from v4 to v5

`HyperHttpClientInterface` now requires a `debug` method.

```cfscript
/**
 * Return a struct of information showing how the client will execute the HyperRequest.
 * This will be used by a developer to debug any differences between the generated
 * request values and the expected request values.
 *
 * @req     The HyperRequest to debug.
 *
 * @returns A struct of information detailing how the client would execute the HyperRequest.
 */
public struct function debug( required HyperRequest req );
```

## Upgrading from v3 to v4

Previously, query params were stored as a struct.  Some APIs expect multiple values for the same query param name to be passed as separate arguments.  Hyper now stores the query params as an array and provides new methods for interacting with query params:

* [`getQueryParamByName`](/7.1.0-1/making-requests/hyperrequest#getqueryparambyname)
* [`getAllQueryParamsByName`](/7.1.0-1/making-requests/hyperrequest#getallqueryparamsbyname)
* [`withQueryParams`](/7.1.0-1/making-requests/hyperrequest#withqueryparams)
* [`appendQueryParam`](/7.1.0-1/making-requests/hyperrequest#appendqueryparam)
* [`appendQueryParams`](/7.1.0-1/making-requests/hyperrequest#appendqueryparams)
* [`hasQueryParam`](/7.1.0-1/making-requests/hyperrequest#hasqueryparam)

The following methods still exist, but now interact with arrays of query param structs instead of a simple struct.

* [`getQueryParams`](/7.1.0-1/making-requests/hyperrequest#getqueryparams)
* [`setQueryParams`](/7.1.0-1/making-requests/hyperrequest#setqueryparams)

The following methods have been deprecated:

| Deprecated Method                                                      | Replacement Method                                                                 |
| ---------------------------------------------------------------------- | ---------------------------------------------------------------------------------- |
| [`getQueryParam`](/7.1.0-1/making-requests/hyperrequest#getqueryparam) | [`getQueryParamByName`](/7.1.0-1/making-requests/hyperrequest#getqueryparambyname) |

## Upgrading from v2 to v3

Dropped support for ColdBox 5.

## Upgrading from v1 to v2

Dropped support for Lucee 4.5.


# Requirements

Hyper runs on Adobe ColdFusion 2018+ and Lucee 5+.

ColdBox is not required, but mappings are provided for ColdBox users automatically.


# Installation

Hyper is most easily installed via ForgeBox and CommandBox.

```sh
box install hyper
```

If you install Hyper in a non-ColdBox application, make sure to create a mapping in your `Application.cfc`

```cfscript
this.mappings[ "/hyper" ] = expandPath( "/modules/hyper" );
```


# HyperBuilder

A `HyperBuilder` is a singleton factory component that will give you a new [`HyperRequest`](/7.1.0-1/making-requests/hyperrequest) any time you call the `new` method.  It will also create a new [`HyperRequest`](/7.1.0-1/making-requests/hyperrequest) any time you call a method on `HyperBuilder` that exists on [`HyperRequest`](/7.1.0-1/making-requests/hyperrequest).

`HyperBuilder` is the component you want to inject into your singleton components, like handlers or services.  It will ensure you get a fresh [`HyperRequest`](/7.1.0-1/making-requests/hyperrequest) instance on each invocation.  This is important since reusing the same [`HyperRequest`](/7.1.0-1/making-requests/hyperrequest) instance will likely produce unintended results.

You can inject a `HyperBuilder` into your application using the `HyperBuilder@hyper` id.

```cfscript
component {
    
    property name="hyper" inject="HyperBuilder@hyper";

    function index( event, rc, prc ) {
        var reqA = hyper.new();
        // reqA is a new HyperRequest instance.
        
        var reqB = hyper.setUrl( "https://swapi.dev/api/people" );
        // reqB is a new HyperRequest instance with the url set.
    }

}
```

If you are not using ColdBox, you can create a `HyperBuilder` manually:

```cfscript
component {

    function init() {
        variables.hyper = new hyper.models.HyperBuilder();
    }

}
```

Additionally, you can register `HyperBuilder` instances as custom HTTP Clients.

{% content-ref url="/pages/sc1pmftTrug5lkmdOWQS" %}
[Custom HTTP Clients](/7.1.0-1/customizing-hyper/custom-http-clients)
{% endcontent-ref %}

Finally, you can enable faking of requests from any `HyperBuilder` instance.

{% content-ref url="/pages/fDs68ouvcjilusPgzOdw" %}
[Faking Requests](/7.1.0-1/testing/faking-requests)
{% endcontent-ref %}


# HyperRequest

Though the [`HyperBuilder`](/7.1.0-1/making-requests/hyperbuilder) is the component you will most likely inject, `HyperRequest` is the component will you interact with the most. `HyperRequest` provides a fluent interface to configure your HTTP call.

```cfscript
hyper.get( "https//api.github.com/users" );

hyper.setMethod( "PUT" )
    .withHeaders( { "Authorization" = "Bearer #token#" } )
    .setUrl( "https://jsonplaceholder.typicode.com/posts/1" )
    .setBody( {
        title: "New Title"
    } )
    .send();
```

## Defaults

The following are default properties for a `HyperRequest`:

```json
{
    "method": "GET"
    "resolveUrls": false,
    "encodeUrl": true,
    "timeout": 10, // in seconds
    "maximumRedirects": "*", // follow redirects indefinitely
    "bodyFormat": "json",
    "throwOnError": false
}
```

## Executing Requests

### `get`

Execute a `GET` request and return a [`HyperResponse`](/7.1.0-1/making-requests/hyperresponse).

| Name        | Type   | Required | Default | Description                                                    |
| ----------- | ------ | -------- | ------- | -------------------------------------------------------------- |
| url         | string | false    | null    | An optional URL to set for the request.                        |
| queryParams | struct | false    | null    | An optional struct of query parameters to set for the request. |

**Return**: [`HyperResponse`](/7.1.0-1/making-requests/hyperresponse)

### `getAsync`

Execute a `GET` request asynchronously. Returns a [ColdBox Future](https://coldbox.ortusbooks.com/digging-deeper/promises-async-programming) that returns a [`HyperResponse`](/7.1.0-1/making-requests/hyperresponse).

<table><thead><tr><th width="40">Name</th><th>Type</th><th>Required</th><th>Default</th><th>Description</th></tr></thead><tbody><tr><td>url</td><td>string</td><td>false</td><td>null</td><td>An optional URL to set for the request.</td></tr><tr><td>queryParams</td><td>struct</td><td>false</td><td>null</td><td>An optional struct of query parameters to set for the request.</td></tr></tbody></table>

**Return**: [`Future`](https://coldbox.ortusbooks.com/digging-deeper/promises-async-programming)`<`[`HyperResponse`](/7.1.0-1/making-requests/hyperresponse)`>`

### `post`

Execute a `POST` request and return a [`HyperResponse`](/7.1.0-1/making-requests/hyperresponse).

| Name | Type   | Required | Default | Description                              |
| ---- | ------ | -------- | ------- | ---------------------------------------- |
| url  | string | false    | null    | An optional URL to set for the request.  |
| body | struct | false    | null    | An optional body to set for the request. |

**Return**: [`HyperResponse`](/7.1.0-1/making-requests/hyperresponse)

### `postAsync`

Execute a `POST` request asynchronously. Returns a [ColdBox Future](https://coldbox.ortusbooks.com/digging-deeper/promises-async-programming) that returns a [`HyperResponse`](/7.1.0-1/making-requests/hyperresponse).

| Name | Type   | Required | Default | Description                              |
| ---- | ------ | -------- | ------- | ---------------------------------------- |
| url  | string | false    | null    | An optional URL to set for the request.  |
| body | struct | false    | null    | An optional body to set for the request. |

**Return**: [`Future`](https://coldbox.ortusbooks.com/digging-deeper/promises-async-programming)`<`[`HyperResponse`](/7.1.0-1/making-requests/hyperresponse)`>`

### `put`

Execute a `PUT` request and return a [`HyperResponse`](/7.1.0-1/making-requests/hyperresponse).

| Name | Type   | Required | Default | Description                              |
| ---- | ------ | -------- | ------- | ---------------------------------------- |
| url  | string | false    | null    | An optional URL to set for the request.  |
| body | struct | false    | null    | An optional body to set for the request. |

**Return**: [`HyperResponse`](/7.1.0-1/making-requests/hyperresponse)

### `putAsync`

Execute a `PUT` request asynchronously. Returns a [ColdBox Future](https://coldbox.ortusbooks.com/digging-deeper/promises-async-programming) that returns a [`HyperResponse`](/7.1.0-1/making-requests/hyperresponse).

| Name | Type   | Required | Default | Description                              |
| ---- | ------ | -------- | ------- | ---------------------------------------- |
| url  | string | false    | null    | An optional URL to set for the request.  |
| body | struct | false    | null    | An optional body to set for the request. |

**Return**: [`Future`](https://coldbox.ortusbooks.com/digging-deeper/promises-async-programming)`<`[`HyperResponse`](/7.1.0-1/making-requests/hyperresponse)`>`

### `patch`

Execute a `PATCH` request and return a [`HyperResponse`](/7.1.0-1/making-requests/hyperresponse).

| Name | Type   | Required | Default | Description                              |
| ---- | ------ | -------- | ------- | ---------------------------------------- |
| url  | string | false    | null    | An optional URL to set for the request.  |
| body | struct | false    | null    | An optional body to set for the request. |

**Return**: [`HyperResponse`](/7.1.0-1/making-requests/hyperresponse)

### `patchAsync`

Execute a `PATCH` request asynchronously. Returns a [ColdBox Future](https://coldbox.ortusbooks.com/digging-deeper/promises-async-programming) that returns a [`HyperResponse`](/7.1.0-1/making-requests/hyperresponse).

| Name | Type   | Required | Default | Description                              |
| ---- | ------ | -------- | ------- | ---------------------------------------- |
| url  | string | false    | null    | An optional URL to set for the request.  |
| body | struct | false    | null    | An optional body to set for the request. |

**Return**: [`Future`](https://coldbox.ortusbooks.com/digging-deeper/promises-async-programming)`<`[`HyperResponse`](/7.1.0-1/making-requests/hyperresponse)`>`

### `delete`

Execute a `DELETE` request and return a [`HyperResponse`](/7.1.0-1/making-requests/hyperresponse).

| Name | Type   | Required | Default | Description                              |
| ---- | ------ | -------- | ------- | ---------------------------------------- |
| url  | string | false    | null    | An optional URL to set for the request.  |
| body | struct | false    | null    | An optional body to set for the request. |

**Return**: [`HyperResponse`](/7.1.0-1/making-requests/hyperresponse)

### `deleteAsync`

Execute a `DELETE` request asynchronously. Returns a [ColdBox Future](https://coldbox.ortusbooks.com/digging-deeper/promises-async-programming) that returns a [`HyperResponse`](/7.1.0-1/making-requests/hyperresponse).

| Name | Type   | Required | Default | Description                              |
| ---- | ------ | -------- | ------- | ---------------------------------------- |
| url  | string | false    | null    | An optional URL to set for the request.  |
| body | struct | false    | null    | An optional body to set for the request. |

**Return**: [`Future`](https://coldbox.ortusbooks.com/digging-deeper/promises-async-programming)`<`[`HyperResponse`](/7.1.0-1/making-requests/hyperresponse)`>`

### `head`

Execute a `HEAD` request and return a [`HyperResponse`](/7.1.0-1/making-requests/hyperresponse).

| Name        | Type   | Required | Default | Description                                                    |
| ----------- | ------ | -------- | ------- | -------------------------------------------------------------- |
| url         | string | false    | null    | An optional URL to set for the request.                        |
| queryParams | struct | false    | null    | An optional struct of query parameters to set for the request. |

**Return**: [`HyperResponse`](/7.1.0-1/making-requests/hyperresponse)

### `headAsync`

Execute a `HEAD` request asynchronously. Returns a [ColdBox Future](https://coldbox.ortusbooks.com/digging-deeper/promises-async-programming) that returns a [`HyperResponse`](/7.1.0-1/making-requests/hyperresponse).

| Name        | Type   | Required | Default | Description                                                    |
| ----------- | ------ | -------- | ------- | -------------------------------------------------------------- |
| url         | string | false    | null    | An optional URL to set for the request.                        |
| queryParams | struct | false    | null    | An optional struct of query parameters to set for the request. |

**Return**: [`Future`](https://coldbox.ortusbooks.com/digging-deeper/promises-async-programming)`<`[`HyperResponse`](/7.1.0-1/making-requests/hyperresponse)`>`

### `options`

Execute an `OPTIONS` request and return a [`HyperResponse`](/7.1.0-1/making-requests/hyperresponse).

| Name        | Type   | Required | Default | Description                                                    |
| ----------- | ------ | -------- | ------- | -------------------------------------------------------------- |
| url         | string | false    | null    | An optional URL to set for the request.                        |
| queryParams | struct | false    | null    | An optional struct of query parameters to set for the request. |

**Return**: [`HyperResponse`](/7.1.0-1/making-requests/hyperresponse)

### `optionsAsync`

Execute an `OPTIONS` request asynchronously. Returns a [ColdBox Future](https://coldbox.ortusbooks.com/digging-deeper/promises-async-programming) that returns a [`HyperResponse`](/7.1.0-1/making-requests/hyperresponse).

| Name        | Type   | Required | Default | Description                                                    |
| ----------- | ------ | -------- | ------- | -------------------------------------------------------------- |
| url         | string | false    | null    | An optional URL to set for the request.                        |
| queryParams | struct | false    | null    | An optional struct of query parameters to set for the request. |

**Return**: [`Future`](https://coldbox.ortusbooks.com/digging-deeper/promises-async-programming)`<`[`HyperResponse`](/7.1.0-1/making-requests/hyperresponse)`>`

### `send`

Send the HTTP request and return a [`HyperResponse`](/7.1.0-1/making-requests/hyperresponse).

| Name         | Type | Required | Default | Description |
| ------------ | ---- | -------- | ------- | ----------- |
| No arguments |      |          |         |             |

**Return**: [`HyperResponse`](/7.1.0-1/making-requests/hyperresponse)

### `sendAsync`

Send the HTTP request asynchronously and return a [ColdBox Future](https://coldbox.ortusbooks.com/digging-deeper/promises-async-programming) that will resolve to a [`HyperResponse`](/7.1.0-1/making-requests/hyperresponse).

| Name         | Type | Required | Default | Description |
| ------------ | ---- | -------- | ------- | ----------- |
| No arguments |      |          |         |             |

**Return**: [`Future`](https://coldbox.ortusbooks.com/digging-deeper/promises-async-programming)`<`[`HyperResponse`](/7.1.0-1/making-requests/hyperresponse)`>`

## Building Requests

### `getRequestId`

Gets the unique request ID representing this request.

| Name         | Type | Required | Default | Description |
| ------------ | ---- | -------- | ------- | ----------- |
| No arguments |      |          |         |             |

**Return**: `String`

### `getFullURL`

Gets the full URL for the request.

| Name            | Type    | Required | Default | Description                                            |
| --------------- | ------- | -------- | ------- | ------------------------------------------------------ |
| withQueryString | boolean | false    | false   | Includes the configured query string with the full URL |

**Return**: `String`

### `getBaseURL`

Gets the base URL for the request. The base URL is combined with the URL when making the request.

| Name         | Type | Required | Default | Description |
| ------------ | ---- | -------- | ------- | ----------- |
| No arguments |      |          |         |             |

**Return**: `String`

### `setBaseURL`

Sets the base URL for the request. The base URL is combined with the URL when making the request.

| Name  | Type   | Required | Default | Description                                                   |
| ----- | ------ | -------- | ------- | ------------------------------------------------------------- |
| value | string | true     |         | The base URL for the request, e.g. `https://api.github.com/`. |

**Return**: `HyperRequest`

### `getURL`

Gets the URL for the request.

| Name         | Type | Required | Default | Description |
| ------------ | ---- | -------- | ------- | ----------- |
| No arguments |      |          |         |             |

**Return**: `String`

### `setURL`

Sets the URL for the request.

| Name  | Type   | Required | Default | Description                                                                                                     |
| ----- | ------ | -------- | ------- | --------------------------------------------------------------------------------------------------------------- |
| value | string | true     |         | The URL for the request. It can either be a full url or a URI resource for use with the baseURL. e.g. `/repos`. |

**Return**: `HyperRequest`

### `setResolveURL`

Sets the resolveURL parameter for the request.

| Name  | Type    | Required | Default | Description                                                                    |
| ----- | ------- | -------- | ------- | ------------------------------------------------------------------------------ |
| value | boolean | false    | false   | Resolves URLs in the response body to absolute URLs, including the port number |

**Return**: `HyperRequest`

### `getMethod`

Gets the HTTP method for the request.

| Name         | Type | Required | Default | Description |
| ------------ | ---- | -------- | ------- | ----------- |
| No arguments |      |          |         |             |

**Return**: `String`

### `setMethod`

Sets the HTTP method for the request.

| Name  | Type   | Required | Default | Description                      |
| ----- | ------ | -------- | ------- | -------------------------------- |
| value | string | true     |         | The HTTP method for the request. |

**Return**: `HyperRequest`

### `withBasicAuth`

Sets the username and password for HTTP Basic Auth.

| Name     | Type   | Required | Default | Description                      |
| -------- | ------ | -------- | ------- | -------------------------------- |
| username | string | true     |         | The username for the basic auth. |
| password | string | true     |         | The password for the basic auth. |

**Return**: `HyperRequest`

### `withCertificateAuth`

Sets the username and password for HTTP Basic Auth.

| Name            | Type   | Required | Default | Description                                              |
| --------------- | ------ | -------- | ------- | -------------------------------------------------------- |
| certificatePath | string | true     |         | The mapped path to the certificate used to authenticate. |
| password        | string | false    |         | The optional password used to decrypt the certificate.   |

**Return**: `HyperRequest`

### `withNTLMAuth`

Sets the username, password, domain and workstation for NTLM Auth.

| Name        | Type   | Required | Default | Description                        |
| ----------- | ------ | -------- | ------- | ---------------------------------- |
| username    | string | true     |         | The username for the NTLM auth.    |
| password    | string | true     |         | The password for the NTLM auth.    |
| domain      | string | true     |         | The domain for the NTLM auth.      |
| workstation | string | true     |         | The workstation for the NTLM auth. |

Workstation can be obtained with `createObject('java','java.net.InetAddress').getLocalHost().getHostName()`

**Return**: `HyperRequest`

### `withRequestCallback`

Schedules a callback to be ran when executing the request.

| Name     | Type     | Required | Default | Description                                     |
| -------- | -------- | -------- | ------- | ----------------------------------------------- |
| callback | function | true     |         | The callback to run when executing the request. |

**Return**: `HyperRequest`

### `withResponseCallback`

Schedules a callback to be ran when receiving the response.

| Name     | Type     | Required | Default | Description                                      |
| -------- | -------- | -------- | ------- | ------------------------------------------------ |
| callback | function | true     |         | The callback to run when receiving the response. |

**Return**: `HyperRequest`

### `getUsername`

Gets the username for the request.

| Name         | Type | Required | Default | Description |
| ------------ | ---- | -------- | ------- | ----------- |
| No arguments |      |          |         |             |

**Return**: `String`

### `setUsername`

Sets the username for the request.

| Name  | Type   | Required | Default | Description                   |
| ----- | ------ | -------- | ------- | ----------------------------- |
| value | string | true     |         | The username for the request. |

**Return**: `HyperRequest`

### `getPassword`

Gets the password for the request.

| Name         | Type | Required | Default | Description |
| ------------ | ---- | -------- | ------- | ----------- |
| No arguments |      |          |         |             |

**Return**: `String`

### `setPassword`

Sets the password for the request.

| Name  | Type   | Required | Default | Description                   |
| ----- | ------ | -------- | ------- | ----------------------------- |
| value | string | true     |         | The password for the request. |

**Return**: `HyperRequest`

### `getTimeout`

Gets the timeout for the request, in seconds.

| Name         | Type | Required | Default | Description |
| ------------ | ---- | -------- | ------- | ----------- |
| No arguments |      |          |         |             |

**Return**: `numeric`

### `setTimeout`

Sets the timeout for the request, in seconds.

| Name  | Type   | Required | Default | Description                              |
| ----- | ------ | -------- | ------- | ---------------------------------------- |
| value | string | true     |         | The timeout for the request, in seconds. |

**Return**: `HyperRequest`

### `withoutRedirecting`

A convenience method to not follow any redirects.

| Name         | Type | Required | Default | Description |
| ------------ | ---- | -------- | ------- | ----------- |
| No arguments |      |          |         |             |

**Return**: `HyperRequest`

### `withoutEncodingUrl`

A convenience method to not encode the url.

{% hint style="warning" %}
**WARNING**: Not supported on Adobe engines.
{% endhint %}

| Name         | Type | Required | Default | Description |
| ------------ | ---- | -------- | ------- | ----------- |
| No arguments |      |          |         |             |

**Return**: `HyperRequest`

### `getMaximumRedirects`

Gets the maximum number of redirects to follow.

| Name         | Type | Required | Default | Description |
| ------------ | ---- | -------- | ------- | ----------- |
| No arguments |      |          |         |             |

**Return**: `numeric | String`

### `setMaximumRedirects`

Sets the maximum number of redirects to follow. A value of `*` will follow redirects infinitely.

| Name  | Type | Required | Default | Description                                |
| ----- | ---- | -------- | ------- | ------------------------------------------ |
| value | any  | true     |         | The maximum number of redirects to follow. |

**Return**: `HyperRequest`

### `getBody`

Gets the body for the request.

| Name         | Type | Required | Default | Description |
| ------------ | ---- | -------- | ------- | ----------- |
| No arguments |      |          |         |             |

**Return**: `any`

### `setBody`

Sets the body for the request. Complex values will be serialized before sending the request.

| Name  | Type | Required | Default | Description               |
| ----- | ---- | -------- | ------- | ------------------------- |
| value | any  | true     |         | The body for the request. |

**Return**: `HyperRequest`

### `hasBody`

Checks if the request has a body.

| Name         | Type | Required | Default | Description |
| ------------ | ---- | -------- | ------- | ----------- |
| No arguments |      |          |         |             |

**Return**: `boolean`

### `getBodyFormat`

Gets the body format for the request.

| Name         | Type | Required | Default | Description |
| ------------ | ---- | -------- | ------- | ----------- |
| No arguments |      |          |         |             |

**Return**: `String`

### `setBodyFormat`

Sets the body format for the request. Recognized values are `formFields`, `json`, or `xml`. It is highly recommended to use `asFormFields`, `asJson`, or `asXML` instead.  If you set this value to a non-recognized value, the body will be passed along as-is to the body of the HTTP request.

| Name  | Type | Required | Default | Description                      |
| ----- | ---- | -------- | ------- | -------------------------------- |
| value | any  | true     |         | The body format for the request. |

**Return**: `HyperRequest`

### `asJson`

A convenience method to set the body format and Content-Type to `json`.

| Name         | Type | Required | Default | Description |
| ------------ | ---- | -------- | ------- | ----------- |
| No arguments |      |          |         |             |

**Return**: `HyperRequest`

### `asFormFields`

A convenience method to set the body format and Content-Type to form fields.

| Name         | Type | Required | Default | Description |
| ------------ | ---- | -------- | ------- | ----------- |
| No arguments |      |          |         |             |

**Return**: `HyperRequest`

### `asXML`

A convenience method to set the body format and Content-Type to `xml`.

| Name         | Type | Required | Default | Description |
| ------------ | ---- | -------- | ------- | ----------- |
| No arguments |      |          |         |             |

**Return**: `HyperRequest`

### `getReferrer`

Gets the referrer for the request, if any.

| Name         | Type | Required | Default | Description |
| ------------ | ---- | -------- | ------- | ----------- |
| No arguments |      |          |         |             |

**Return**: `String`

### `getHeaders`

Gets the headers for the request.

| Name         | Type | Required | Default | Description |
| ------------ | ---- | -------- | ------- | ----------- |
| No arguments |      |          |         |             |

**Return**: `java.util.LinkedHashMap`

### `setHeaders`

Sets the headers for the request.

| Name  | Type   | Required | Default | Description                  |
| ----- | ------ | -------- | ------- | ---------------------------- |
| value | struct | true     |         | The headers for the request. |

**Return**: `HyperRequest`

### `setHeader`

Set a header for the request.

| Name  | Type   | Required | Default | Description              |
| ----- | ------ | -------- | ------- | ------------------------ |
| name  | string | true     |         | The name of the header.  |
| value | string | true     |         | The value of the header. |

**Return**: `HyperRequest`

### `withHeaders`

Add additional headers to the request.

| Name    | Type   | Required | Default | Description                                |
| ------- | ------ | -------- | ------- | ------------------------------------------ |
| headers | struct | true     |         | A struct of headers to add to the request. |

**Return**: `HyperRequest`

### `forwardHeaders`

Adds specified headers to the request if they exist. Usually used in conjunction with the current CFML request headers.

| Name    | Type   | Required | Default                               | Description                                                                           |
| ------- | ------ | -------- | ------------------------------------- | ------------------------------------------------------------------------------------- |
| names   | array  | true     |                                       | An array of header names to add to the request if they exist in the `headers` struct. |
| headers | struct | false    | `getHTTPRequestData( false ).headers` | A struct of headers to inspect.                                                       |

**Return**: `HyperRequest`

### `hasHeader`

Check if the request has a header with the given name.

| Name | Type   | Required | Default | Description                      |
| ---- | ------ | -------- | ------- | -------------------------------- |
| name | string | true     |         | The name of the header to check. |

**Return**: `boolean`

### `setContentType`

A convenience method to set the [`Content-Type` header](https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Content-Type).

| Name | Type   | Required | Default | Description                            |
| ---- | ------ | -------- | ------- | -------------------------------------- |
| type | string | true     |         | The Content-Type value for the request |

**Return**: `HyperRequest`

### `setAccept`

A convenience method to set the [`Accept` header](https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Accept).

| Name | Type   | Required | Default | Description                      |
| ---- | ------ | -------- | ------- | -------------------------------- |
| type | string | true     |         | The Accept value for the request |

**Return**: `HyperRequest`

### `getQueryParams`

Gets the query parameters for the request.

{% hint style="warning" %}
This method returns an array of param structs that is used under the hood by Hyper. You probably want to use [`getQueryParamByName`](#getqueryparambyname) or [`getAllQueryParamsByName`](#getallqueryparamsbyname) instead.
{% endhint %}

| Name         | Type | Required | Default | Description |
| ------------ | ---- | -------- | ------- | ----------- |
| No arguments |      |          |         |             |

**Return**: `array<struct<string, any>>`

### `setQueryParams`

Sets the query parameters for the request.

{% hint style="warning" %}
This method accepts an array of param structs that is used under the hood by Hyper. You probably want to use [`withQueryParams`](#withqueryparams) or [`appendQueryParams`](#appendqueryparams) instead.
{% endhint %}

If needed, param structs have two keys, `name` and `value`.

| Name  | Type  | Required | Default | Description                                                |
| ----- | ----- | -------- | ------- | ---------------------------------------------------------- |
| value | array | true     |         | The query parameters for the as an array of param structs. |

**Return**: `HyperRequest`

### `getQueryParam`

{% hint style="danger" %}
**DEPRECATED:** Use [`getQueryParamByName`](#getqueryparambyname)
{% endhint %}

Gets the first value for a certain query parameter. Returns an empty string if the query parameter does not exist.

| Name | Type   | Required | Default | Description                                                  |
| ---- | ------ | -------- | ------- | ------------------------------------------------------------ |
| name | string | true     |         | The name of the query parameter to retrieve the first value. |

**Return**: `any`

### `getQueryParamByName`

Gets the first value for a certian query parameter. Returns an empty string if the query parameter does not exist.

| Name | Type   | Required | Default | Description                                                  |
| ---- | ------ | -------- | ------- | ------------------------------------------------------------ |
| name | string | true     |         | The name of the query parameter to retrieve the first value. |

**Return**: `any`

### `getAllQueryParamsByName`

Get all the values for a certain query parameter. Returns an empty array if the query parameter does not exist.

| Name | Type   | Required | Default | Description                                                    |
| ---- | ------ | -------- | ------- | -------------------------------------------------------------- |
| name | string | true     |         | The name of the query parameter to retrieve all of its values. |

**Return**: `array<any>`

### `setQueryParam`

Set a query parameter for the request.

{% hint style="info" %}
**Note:** This removes all other query params with the same name.
{% endhint %}

| Name  | Type   | Required | Default | Description                       |
| ----- | ------ | -------- | ------- | --------------------------------- |
| name  | string | true     |         | The name of the query parameter.  |
| value | string | true     |         | The value of the query parameter. |

**Return**: `HyperRequest`

### `appendQueryParam`

Append a query parameter for the request.

| Name  | Type   | Required | Default | Description                       |
| ----- | ------ | -------- | ------- | --------------------------------- |
| name  | string | true     |         | The name of the query parameter.  |
| value | string | true     |         | The value of the query parameter. |

**Return**: `HyperRequest`

### `withQueryParams`

Add additional query parameters to the request.&#x20;

{% hint style="info" %}
**Note:** This will remove any values with duplicate keys prior to adding the new struct of params.
{% endhint %}

| Name        | Type   | Required | Default | Description                                         |
| ----------- | ------ | -------- | ------- | --------------------------------------------------- |
| queryParams | struct | true     |         | A struct of query parameters to add to the request. |

**Return**: `HyperRequest`

### `appendQueryParams`

Appends additional query parameters to the request.

| Name        | Type   | Required | Default | Description                                         |
| ----------- | ------ | -------- | ------- | --------------------------------------------------- |
| queryParams | struct | true     |         | A struct of query parameters to add to the request. |

**Return**: `HyperRequest`

### `hasQueryParam`

Check if the request has a query parameter with the given name.

| Name | Type   | Required | Default | Description                               |
| ---- | ------ | -------- | ------- | ----------------------------------------- |
| name | string | true     |         | The name of the query parameter to check. |

**Return**: `boolean`

### `attach`

Attaches a file to the Hyper request. Also sets the Content-Type as `multipart/form-data`. Multiple files can be attached by calling `attach` multiple times before calling a send method.

| Name     | Type   | Required | Default | Description                                       |
| -------- | ------ | -------- | ------- | ------------------------------------------------- |
| name     | string | true     |         | The name of the file being uploaded.              |
| path     | string | true     |         | The absolute path to the file to be uploaded.     |
| mimeType | string | false    |         | An optional mime type to associate with the file. |

**Return**: `HyperRequest`

### `setThrowOnError`

Sets the throw on error property for the request. If true, statuses in the 4xx and 5xx range will be turned in to exceptions.

| Name  | Type    | Required | Default | Description                           |
| ----- | ------- | -------- | ------- | ------------------------------------- |
| value | boolean | true     |         | The value of the throw on error flag. |

**Return**: `HyperRequest`

### `throwErrors`

A convenience method to throw on errors.

| Name         | Type | Required | Default | Description |
| ------------ | ---- | -------- | ------- | ----------- |
| No arguments |      |          |         |             |

**Return**: `HyperRequest`

### `allowErrors`

A convenience method to not throw on errors.

| Name         | Type | Required | Default | Description |
| ------------ | ---- | -------- | ------- | ----------- |
| No arguments |      |          |         |             |

**Return**: `HyperRequest`

### `clone`

Clones the current request into a new HyperRequest.

| Name         | Type | Required | Default | Description |
| ------------ | ---- | -------- | ------- | ----------- |
| No arguments |      |          |         |             |

**Return**: A new `HyperRequest` instance cloned from this one.

### `clear`

Clears the request of any set values, including defaults passed by the builder.

| Name         | Type | Required | Default | Description |
| ------------ | ---- | -------- | ------- | ----------- |
| No arguments |      |          |         |             |

**Return**: `HyperRequest`

### `when`

Helper to conditionally execute a callback for the `HyperRequest`. This method lets you use conditionals without breaking chaining.

| Name            | Type       | Required | Default | Description                                                                                            |
| --------------- | ---------- | -------- | ------- | ------------------------------------------------------------------------------------------------------ |
| condition       | `boolean`  | `true`   |         | The condition to check.                                                                                |
| successCallback | `function` | `true`   |         | The callback to execute if the condition is true. The callback is passed the `HyperRequest` instance.  |
| failureCallback | `function` | `false`  | `null`  | The callback to execute if the condition is false. The callback is passed the `HyperRequest` instance. |

**Return**: `HyperRequest`

### `setProperties`

Quickly set many request properties using a struct. The key should be the name of one of the properties on the request, e.g. `url`, `headers`, `method`, `body`.

| Name       | Type   | Required | Default | Description                                                                                                                                   |
| ---------- | ------ | -------- | ------- | --------------------------------------------------------------------------------------------------------------------------------------------- |
| properties | struct | true     |         | A struct of properties to set. Each property name will be set on the request. Properties that don't exist on the request will throw an error. |

**Return**: `HyperRequest`

### `setHttpClient`

Sets the [HTTP Client](/7.1.0-1/customizing-hyper/custom-http-clients) to use for the request. The client should conform to the `HyperHttpClientInterface` (though it does not need to use the `implements` keyword).

| Name       | Type                       | Required | Default | Description                            |
| ---------- | -------------------------- | -------- | ------- | -------------------------------------- |
| httpClient | `HyperHttpClientInterface` | `true`   |         | The httpClient to use for the request. |

**Return**: `HyperRequest`

### `setInterceptorService`

Sets the [ColdBox Interceptor Service](https://coldbox.ortusbooks.com/the-basics/interceptors) to announce request and response interception points. A noop option is provided in the `init` for non-ColdBox usage.

| Name               | Type | Required | Default | Description                                     |
| ------------------ | ---- | -------- | ------- | ----------------------------------------------- |
| interceptorService | any  | `true`   |         | The interceptor service to use for the request. |

**Return**: `HyperRequest`

### `setAsyncManager`

Sets the [ColdBox AsyncManager](https://coldbox.ortusbooks.com/digging-deeper/promises-async-programming) to send requests asynchronously. A noop option is provided in the `init` for non-ColdBox usage.

| Name         | Type | Required | Default | Description                              |
| ------------ | ---- | -------- | ------- | ---------------------------------------- |
| asyncManager | any  | `true`   |         | The asyncManager to use for the request. |

**Return**: `HyperRequest`

### `getMemento`

Returns a struct representing this `HyperRequest`.

| Name         | Type | Required | Default | Description |
| ------------ | ---- | -------- | ------- | ----------- |
| No arguments |      |          |         |             |

**Return**:

```json
{
    "requestID"          : getRequestID(),
    "baseUrl"            : getBaseUrl(),
    "url"                : getUrl(),
    "fullUrl"            : getFullUrl(),
    "method"             : getMethod(),
    "queryParams"        : getQueryParams(),
    "headers"            : getHeaders(),
    "files"              : getFiles(),
    "bodyFormat"         : getBodyFormat(),
    "body"               : getBody(),
    "referrer"           : isNull( variables.referrer ) ? "" : variables.referrer,
    "throwOnError"       : getThrowOnError(),
    "timeout"            : getTimeout(),
    "maximumRedirects"   : getMaximumRedirects(),
    "authType"           : getAuthType(),
    "username"           : getUsername(),
    "password"           : getPassword(),
    "clientCert"         : isNull( variables.clientCert ) ? "" : variables.clientCert,
    "clientCertPassword" : isNull( variables.clientCertPassword ) ? "" : variables.clientCertPassword,
    "domain"             : getDomain(),
    "workstation"        : getWorkstation(),
    "resolveUrls"        : getResolveUrls(),
    "encodeUrl"          : getEncodeUrl()
};
```

### `debug`

Creates a debug representation of the HTTP request for the current HTTP client.

{% hint style="danger" %}
**Throws**: `NoUrlException` when no URL is set.
{% endhint %}

| Name         | Type | Required | Default | Description |
| ------------ | ---- | -------- | ------- | ----------- |
| No arguments |      |          |         |             |

**Return**: Dependent on the configured HTTP Client.  See specific HTTP Client documentation for details.


# HyperResponse

The `HyperResponse` component is a read-only wrapper to easily grab different information about the response.

### `getResponseId`

Gets the unique response ID representing this response.

| Name         | Type | Required | Default | Description |
| ------------ | ---- | -------- | ------- | ----------- |
| No arguments |      |          |         |             |

**Return**: `String`

### `getStatusCode`

Gets the status code for the response.

| Name         | Type | Required | Default | Description |
| ------------ | ---- | -------- | ------- | ----------- |
| No arguments |      |          |         |             |

**Return**: `numeric`

### `getStatusText`

Gets the status text for the response.

| Name         | Type | Required | Default | Description |
| ------------ | ---- | -------- | ------- | ----------- |
| No arguments |      |          |         |             |

**Return**: `String`

### `getStatus`

Returns the status code and status text as a single string.

| Name         | Type | Required | Default | Description |
| ------------ | ---- | -------- | ------- | ----------- |
| No arguments |      |          |         |             |

**Return**: `String`

### `getData`

Gets the data for the response.

| Name         | Type | Required | Default | Description |
| ------------ | ---- | -------- | ------- | ----------- |
| No arguments |      |          |         |             |

**Return**: `String`

### `getRequestID`

Returns the id of the request to which this response is related.

| Name         | Type | Required | Default | Description |
| ------------ | ---- | -------- | ------- | ----------- |
| No arguments |      |          |         |             |

**Return**: `String`

### `getRequest`

Gets the [HyperRequest](/7.1.0-1/making-requests/hyperrequest) instance associated with this response.

| Name         | Type | Required | Default | Description |
| ------------ | ---- | -------- | ------- | ----------- |
| No arguments |      |          |         |             |

**Return**: [`HyperRequest`](/7.1.0-1/making-requests/hyperrequest)

### `getCharset`

Gets the charset value for the response.

| Name         | Type | Required | Default | Description |
| ------------ | ---- | -------- | ------- | ----------- |
| No arguments |      |          |         |             |

**Return**: `String`

### `getTimestamp`

Gets the timestamp for when this response was received.

| Name         | Type | Required | Default | Description |
| ------------ | ---- | -------- | ------- | ----------- |
| No arguments |      |          |         |             |

**Return**: `DateTime`

### `getExecutionTime`

Gets the execution time of the request, in milliseconds.

| Name         | Type | Required | Default | Description |
| ------------ | ---- | -------- | ------- | ----------- |
| No arguments |      |          |         |             |

**Return**: `numeric`

### `json`

Returns the data of the request as deserialized `JSON`.

{% hint style="danger" %}
**Throws**: `DeserializeJsonException` if the response is not `JSON`.
{% endhint %}

| Name         | Type | Required | Default | Description |
| ------------ | ---- | -------- | ------- | ----------- |
| No arguments |      |          |         |             |

**Return**: `any`

### `isSuccess`

Returns true if the request status code is considered successful.

| Name         | Type | Required | Default | Description |
| ------------ | ---- | -------- | ------- | ----------- |
| No arguments |      |          |         |             |

**Return**: `boolean`

### `isOK`

Returns true if the request status code is `200 OK`.

| Name         | Type | Required | Default | Description |
| ------------ | ---- | -------- | ------- | ----------- |
| No arguments |      |          |         |             |

**Return**: `boolean`

### `isCreated`

Returns true if the request status code is `201 Created`.

| Name         | Type | Required | Default | Description |
| ------------ | ---- | -------- | ------- | ----------- |
| No arguments |      |          |         |             |

**Return**: `boolean`

### `isRedirect`

Returns true if the request status code is considered a redirect.

| Name         | Type | Required | Default | Description |
| ------------ | ---- | -------- | ------- | ----------- |
| No arguments |      |          |         |             |

**Return**: `boolean`

### `isError`

Returns true if the request status code is considered either a client error (4xx status code) or a server error (5xx status code).

| Name         | Type | Required | Default | Description |
| ------------ | ---- | -------- | ------- | ----------- |
| No arguments |      |          |         |             |

**Return**: `boolean`

### `isClientError`

Returns true if the request status code is considered a client error (4xx status code).

| Name         | Type | Required | Default | Description |
| ------------ | ---- | -------- | ------- | ----------- |
| No arguments |      |          |         |             |

**Return**: `boolean`

### `isUnauthorized`

Returns true if the request status code is `401 Unauthorized`.

| Name         | Type | Required | Default | Description |
| ------------ | ---- | -------- | ------- | ----------- |
| No arguments |      |          |         |             |

**Return**: `boolean`

### `isForbidden`

Returns true if the request status code is `403 Forbidden`.

| Name         | Type | Required | Default | Description |
| ------------ | ---- | -------- | ------- | ----------- |
| No arguments |      |          |         |             |

**Return**: `boolean`

### `isNotFound`

Returns true if the request status code is `404 Not Found`.

| Name         | Type | Required | Default | Description |
| ------------ | ---- | -------- | ------- | ----------- |
| No arguments |      |          |         |             |

**Return**: `boolean`

### `isServerError`

Returns true if the request status code is considered a server error (5xx status code).

| Name         | Type | Required | Default | Description |
| ------------ | ---- | -------- | ------- | ----------- |
| No arguments |      |          |         |             |

**Return**: `boolean`

### `hasHeader`

Checks if a header exists in the response.

| Name | Type     | Required | Default | Description                      |
| ---- | -------- | -------- | ------- | -------------------------------- |
| name | `String` | `true`   |         | The name of the header to check. |

**Return**: `boolean`

### `getHeader`

Gets the value of a header from the response.

| Name         | Type     | Required | Default | Description                                       |
| ------------ | -------- | -------- | ------- | ------------------------------------------------- |
| name         | `String` | `true`   |         | The name of the header to retrieve.               |
| defaultValue | `any`    | `false`  | `""`    | The value to return if the header does not exist. |

**Return**: `any`

### `getMemento`

Gets a serializable representation of the response.

| Name         | Type | Required | Default | Description |
| ------------ | ---- | -------- | ------- | ----------- |
| No arguments |      |          |         |             |

**Return**:

```json
{
    "responseID"    : getResponseID(),
    "requestID"     : getRequestID(),
    "statusCode"    : getStatusCode(),
    "statusText"    : getStatusText(),
    "status"        : getStatus(),
    "data"          : getData(),
    "charset"       : getCharset(),
    "headers"       : getHeaders(),
    "timestamp"     : getTimestamp(),
    "executionTime" : getExecutionTime()
}
```


# Hyper Clients

Hyper allows you to configure defaults for your requests as custom Hyper Clients. This is particularly useful for reducing boilerplate in your application.

Defaults are set on the `HyperBuilder` instance. The easiest way to do this is to configure it in WireBox. In an `afterAspectsLoad` method, you can get a reference to a `HyperBuilder`, configure it as you would for a request, and then call the `registerAs` method passing in your desired WireBox alias.

```cfscript
// config/WireBox.cfc
component {

   // ...
   
   function afterApsectsLoad() {
       injector.getInstance( "HyperBuilder@hyper" )
           .setBaseUrl( "https://swapi.dev/api" )
           .asJson()
           .registerAs( "StarWarsClient" );
   }

}
```

{% hint style="info" %}
Putting the registration code in `afterAspectsLoad` is required so Hyper can be loaded and available for injection.
{% endhint %}

Now, you can inject this pre-configured builder wherever you need in your application:

```js
component {

    property name="StarWarsClient" inject="StarWarsClient";

    function findUser( id ) {
        return variables.StarWarsClient.get( "/people/#id#" );
    }

}
```

You can alternatively create the clients by passing in the desired defaults to the `initWith` method of a WireBox mapping.  These arguments must match the [`HyperRequest` property names](#hyperrequest-property-names).

```js
// config/WireBox.cfc
component {

    function configure() {
        map( "StarWarsClient" )
            .to( "hyper.models.HyperBuilder" )
            .asSingleton()
            .initWith(
                baseUrl = "https://swapi.dev/api"
            );
    }

}
```

You can even create multiple clients using this approach:

```js
// config/WireBox.cfc
component {

    function configure() {
        // ...
    }

    function afterAspectsLoad() {
        injector.getInstance( "HyperBuilder@hyper" )
           .setBaseUrl( "https://swapi.dev/api" )
           .asJson()
           .registerAs( "StarWarsClient" );

       injector.getInstance( "HyperBuilder@hyper" )
           .setBaseUrl( "https://api.github.com" )
           .asJson()
           .withHeaders( {
               "Authorization": coldbox.getUtil().getSystemSetting( "GITHUB_TOKEN" )
           } )
           .registerAs( "GitHubClient" );
    }

}
```

You can also set or change the defaults by either passing the key / value pairs in to the `init` method or by calling the appropriate `HyperRequest` method on the `HyperBuilder.defaults` property.

```js
var hyper = new Hyper.models.HyperBuilder(
    baseUrl = "https://api.github.com"
);
hyper.defaults.withHeaders( { "Authorization" = token } );
```

#### HyperRequest property names

```cfscript
/**
* The httpClient to use for the request
*/
property name="httpClient";

/**
* The baseURL for the request.
* e.g. https://api.github.com/
*/
property name="baseUrl" default="";

/**
* The URL for the request.
* It can either be a full url
* or a URI resource for use with the baseURL.
* e.g. /repos
*/
property name="url" default="";

/**
* Setting this to true will change all relative urls in the document to absolute.
*/
property name="resolveUrls" default="false";

/**
* Setting this to false will not automatically encode the url passed.
* WARNING: Setting this to false is not supported on Adobe engines.
*/
property name="encodeUrl" default="true";

/**
* The HTTP method for the request.
*/
property name="method" default="GET";

/**
* The username for the request for basic auth.
*/
property name="username" default="";

/**
* The password for the request for basic auth.
*/
property name="password" default="";

/**
* Timeout, in seconds, for the request.
*/
property name="timeout" default="10";

/**
* The maximum number of redirects to follow.
* A value of `*` will follow redirects infinitely.
*/
property name="maximumRedirects" default="*";

/**
* The body to send with the request.
* How the body is serialized is
* determined by the bodyFormat.
*/
property name="body" default="";

/**
* The format to serialize the body.
* e.g. `json` or `formFields`
*/
property name="bodyFormat" default="json";

/**
* The referring response in the case of redirects.
*/
property name="referrer";

/**
* A struct of headers for the request.
*/
property name="headers";

/**
* A struct of query parameters for the request.
*/
property name="queryParams";

/**
* Flag to throw on a cfhttp error.
*/
property name="throwOnError" default="false";

/**
* The full path to a PKCS12 format file that contains the client certificate for the request.
*/
property name="clientCert";

/**
* 	Password used to decrypt the client certificate.
*/
property name="clientCertPassword";

/**
* The domain for the request for NTLM auth.
*/
property name="domain" default="";

/**
* The workstation for the request for NTLM auth.
*/
property name="workstation" default="";

/**
* The authType for the request
*/
property name="authType" default="BASIC";

/**
* An array of callback functions to call
* before firing off a request.
*/
property name="requestCallbacks" type="array";

/**
* An array of callback functions to call
* after receiving a response.
*/
property name="responseCallbacks" type="array";
```

If you need per-request or per-response manipulation of defaults, use the [`requestCallbacks`](/7.1.0-1/making-requests/hyperrequest#withrequestcallback) and [`responseCallbacks`](/7.1.0-1/making-requests/hyperrequest#withresponsecallback) hooks.

```cfscript
map( "ApiClient" )
    .to( "hyper.models.HyperBuilder" )
    .asSingleton()
    .initWith(
        baseUrl = getColdBox().getUtil().getSystemSetting( "API_URL" ),
        requestCallbacks = [
            // provide the current user's token for the request
            function( req ) {
                var auth = getWireBox().getInstance( "AuthenticationService@cbauth" );
                req.withHeaders( "Authorization", auth.user().getApiToken() );
            }
        ],
        responseCallbacks = [
            // map custom `error` property to an exception
            function ( res ) {
                if ( !res.isError() ) {
                    return;
                }
                
                var body = res.json();
                throw(
                    type = "ApiError",
                    message = body.error.message,
                    detail = body.error.code
                );
            }
        ]
    );
```


# Custom HTTP Clients

By default, Hyper makes HTTP requests using `cfhttp` under the hood.  This can be swapped out by any compatible HTTP client that follows the `HyperHttpClientInterface`.

```cfscript
/**
 * Responsible for executing the HyperRequest and mapping it to a HyperResponse
 */
interface displayname="HyperHttpClientInterface" {

	/**
	 * Execute the HyperRequest and map it to a HyperResponse.
	 *
	 * @req     The HyperRequest to execute.
	 *
	 * @returns A HyperResponse of the executed request.
	 */
	public HyperResponse function send( required HyperRequest req );

	/**
	 * Return a struct of information showing how the client will execute the HyperRequest.
	 * This will be used by a developer to debug any differences between the generated
	 * request values and the expected request values.
	 *
	 * @req     The HyperRequest to debug.
	 *
	 * @returns A struct of information detailing how the client would execute the HyperRequest.
	 */
	public struct function debug( required HyperRequest req );

}
```


# CfhttpHttpClient

### `debug`

Return a struct of information showing how the client will execute the [`HyperRequest`](/7.1.0-1/making-requests/hyperrequest). This will be used by a developer to debug any differences between the generated request values and the expected request values.

| Name | Type                                                    | Required | Default | Description                                                           |
| ---- | ------------------------------------------------------- | -------- | ------- | --------------------------------------------------------------------- |
| req  | [`HyperRequest`](/7.1.0-1/making-requests/hyperrequest) | `true`   |         | The [`HyperRequest`](/7.1.0-1/making-requests/hyperrequest) to debug. |

**Return**:

```json
{
    "attributes" : attrCollection,
    "body"       : {
        "headers" : cfhttpHeaders,
        "params"  : cfhttpParams,
        "files"   : cfhttpFiles,
        "body"    : cfhttpBody
    }
}
```


# Faking Requests

Hyper has the ability to fake requests and return fake responses as a result.  This is perfect for [testing](https://testbox.ortusbooks.com/) scenarios where you don't actually want to make an HTTP request.

{% hint style="warning" %}
Non-ColdBox users will need to add a mapping to the [`Globber`](https://forgebox.io/view/globber) dependency included with Hyper.

```cfscript
// Application.cfc
component {
    this.mappings[ "/globber" ] = "/path/to/hyper" & "/modules/globber";
}
```

{% endhint %}

## Faking All Requests

Faking is enabled on a [`HyperBuilder`](/7.1.0-1/making-requests/hyperbuilder) instance, either the built-in one provided by Hyper or a [custom Hyper client](/7.1.0-1/customizing-hyper/custom-http-clients) you have created.

To enable faking requests, call the `fake` method:

```cfscript
var hyper = new Hyper.models.HyperBuilder();
hyper.fake();
```

After calling the `fake` method, all requests created by this `HyperBuilder` will be faked.  By default, they will return `200 OK` responses with empty bodies.

```cfscript
hyper.fake();
var res = hyper.get( "https://google.com" );
expect( res.getStatus() ).toBe( "200 OK" );
```

## Fake Configuration

When calling the `fake` method, you can provide a struct mapping URL patterns to response generator functions.

```cfscript
hyper.fake( {
    "https://google.com/*": function( newFakeResponse, req ) {
         return newFakeResponse( 404, "Not Found" );
    }
} );
```

The key is a URL pattern.  The pattern can be any valid glob. If the pattern is matched by the [`fullUrl`](/7.1.0-1/making-requests/hyperrequest#getfullurl) of the `HyperRequest`, then the response generator function will be called and the results returned.

A helper function, `newFakeResponse`, is provided as the first argument to the response generator function.  The current request is provided as the second argument.

## FakeHyperResponse

The resposne generator function must return a `FakeHyperResponse` instance.  A `FakeHyperResponse` instance acts similar to a normal `HyperResponse` except the properties are not read only.  Once you have an instance of your `FakeHyperResponse`, you can continue to set any properties you need.

```cfscript
hyper.fake( {
    "https://jsonplaceholder.typicode.com/posts": function( newFakeResponse, req ) {
         return newFakeResponse()
             .setStatusCode( 201 )
             .setStatusText( "Created" )
             .setBody( serializeJSON( {
                 "id": 101,
                 "title": "foo",
                 "body": "bar",
                 "userId": 1
             } ) );
    }
} );
```

You can also pass the values to the `newFakeResponse` function, if you'd like.

```cfscript
hyper.fake( {
    "https://jsonplaceholder.typicode.com/posts": function( newFakeResponse, req ) {
         return newFakeResponse( 201, "Created", serializeJSON( {
             "id": 101,
             "title": "foo",
             "body": "bar",
             "userId": 1
         } ) );
    }
} );
```

### `newFakeResponse`

Creates a new `FakeHyperResponse` instance.

<table><thead><tr><th width="160">Name</th><th>Type</th><th>Required</th><th>Default</th><th>Description</th></tr></thead><tbody><tr><td>statusCode</td><td><code>numeric</code></td><td><code>false</code></td><td>200</td><td>The status code for the fake response.</td></tr><tr><td>statusText</td><td><code>string</code></td><td><code>false</code></td><td><code>"OK"</code></td><td>The status text for the fake response.</td></tr><tr><td>data</td><td><code>string</code></td><td><code>false</code></td><td><code>""</code></td><td>The data for the fake response.</td></tr><tr><td>headers</td><td><code>{ string: string }</code></td><td><code>false</code></td><td><code>{}</code></td><td>The headers for the fake response.</td></tr><tr><td>executionTime</td><td><code>numeric</code></td><td><code>false</code></td><td>0</td><td>The execution time for the fake response.</td></tr><tr><td>charset</td><td><code>string</code></td><td><code>false</code></td><td><code>"UTF-8"</code></td><td>The charset for the fake response.</td></tr><tr><td>timestamp</td><td><code>datetime</code></td><td><code>false</code></td><td><code>now()</code></td><td>The timestamp of the fake response.</td></tr></tbody></table>

**Return**: `FakeHyperResponse`

## Sequencing Fake Responses

In addition to returning a single `FakeHyperResponse` per pattern, you can return an array of `FakeHyperResponse` instances.  These will be returned in a sequence.

```cfscript
hyper.fake( {
    "https://jsonplaceholder.typicode.com/posts": function( newFakeResponse, req ) {
         return [
             newFakeResponse( 201, "Created", serializeJSON( {
                 "id": 101,
                 "title": "foo",
                 "body": "bar",
                 "userId": 1
             } ) ),
             newFakeResponse( 422, "Unprocessable Entity", "Duplicate title" )
         ];
    }
} );

var resA = hyper.post( "https://jsonplaceholder.typicode.com/posts", { /* ... */ } );
expect( resA.getStatus() ).toBe( "201 Created" );

var resB = hyper.post( "https://jsonplaceholder.typicode.com/posts", { /* ... */ } );
expect( resA.getStatus() ).toBe( "422 Unprocessable Entity" );
```

If you continue to make requests to the same pattern after the sequence has been exhausted, an exception will be thrown.

```cfscript
hyper.fake( {
    "https://jsonplaceholder.typicode.com/posts": function( newFakeResponse, req ) {
         return [
             newFakeResponse( 201, "Created", serializeJSON( {
                 "id": 101,
                 "title": "foo",
                 "body": "bar",
                 "userId": 1
             } ) ),
             newFakeResponse( 422, "Unprocessable Entity", "Duplicate title" )
         ];
    }
} );

var resA = hyper.post( "https://jsonplaceholder.typicode.com/posts", { /* ... */ } );
expect( resA.getStatus() ).toBe( "201 Created" );

var resB = hyper.post( "https://jsonplaceholder.typicode.com/posts", { /* ... */ } );
expect( resA.getStatus() ).toBe( "422 Unprocessable Entity" );

// THROWS a `HyperFakeSequenceExhausted` exception
var resC = hyper.post( "https://jsonplaceholder.typicode.com/posts", { /* ... */ } );
```

## Preventing Stray Requests

By default, Hyper returns a default `FakeHyperResponse` for every request that doesn't match one of your configured patterns.  You can instead cause Hyper to throw an exception if it encounters one of these stray requests by calling the `preventStrayRequests` method.

```cfscript
hyper.fake( {
    "https://google.com/*": function( newFakeResponse, req ) {
         return newFakeResponse( 404, "Not Found" );
    }
} );

// THROWS a `HyperFakeStrayRequest` exception
var res = hyper.get( "https://github.com" );
```

## Making Assertions

In addition to assertions made against the `FakeHyperResponse` instances returned, you can also make assertions using the `HyperBuilder` instance you faked.  These come in the form of methods on the `HyperBuilder` instance as well as custom TestBox Assertions.

### HyperBuilder Method Assertions

The following methods are available to make assertions in your tests about the requests that were sent.

#### getFakeRequestCount

Returns the number of fake requests that have been made.

| Name         | Type | Required | Default | Description |
| ------------ | ---- | -------- | ------- | ----------- |
| No arguments |      |          |         |             |

**Return**: `numeric`

#### wasRequestSent

Returns whether a request has been made that matches the `predicate`. Each request that has been made is passed to the `predicate` in order. If the `predicate` returns `true`, the request is considered a match and `true` is returned. If no request passes the `predicate`, `false` is returned.

| Name      | Type       | Required | Default | Description                                                                                            |
| --------- | ---------- | -------- | ------- | ------------------------------------------------------------------------------------------------------ |
| predicate | `function` | `true`   |         | A callback function that returns true if the request matches the criteria and returns false otherwise. |

**Return**: `boolean`

### Custom TestBox Assertions

You can register [custom TestBox assertions](https://testbox.ortusbooks.com/in-depth/expectations/custom-matchers) provided by Hyper for more readable tests and test failure messages.

You must [register](https://testbox.ortusbooks.com/in-depth/expectations/custom-matchers#cfc-matchers) these assertions before using them.

```cfscript
component extends="testbox.system.BaseSpec" {

    function beforeAll() {
        addMatchers( "hyper.models.TestBoxMatchers" )
    }
    
    function run() {
        // ...
    }

}
```

The following custom assertions are provided:

#### toHaveSentRequest

This takes in the `HyperBuilder` instance as the actual and a predicate function as the expected. The predicate function is passed to the `HyperBuilder` instance's `wasRequestSent` method.

```cfscript
hyper.fake();

hyper.get( "https://google.com" );

expect( hyper ).toHaveSentRequest( function( req ) {
    return req.getFullUrl( "https://google.com" );
} );

expect( hyper ).notToHaveSentRequest( function( req ) {
    return req.getFullUrl( "https://github.com" );
} );
```

#### toHaveSentCount

This takes in the `HyperBuilder` instance as the actual and an integer number of requests that should have been sent.

```cfscript
hyper.fake();

hyper.get( "https://google.com" );

expect( hyper ).toHaveSentCount( 1 );
expect( hyper ).notToHaveSentCount( 2 );
```

#### toHaveSentNothing

This takes in the `HyperBuilder` instance as the actual and no other parameters.

```cfscript
hyper.fake();

expect( hyper ).toHaveSentNothing();

hyper.get( "https://google.com" );

expect( hyper ).notToHaveSentNothing();
```

## Resetting the Builder

To reset the `HyperBuilder` instance to normal operation call the `clearFakes` method:

```cfscript
hyper.fake();

hyper.get( "https://google.com" );

hyper.clearFakes();
```

{% hint style="info" %}
This is a useful method to call in an [`afterEach`](https://testbox.ortusbooks.com/in-depth/life-cycle-methods/bdd#aftereach-body-data) block in TestBox to make sure you are only faking requests when you want to.
{% endhint %}


# Introduction

## A CFML HTTP Builder

### Inspiration

Hyper was built after coding several API SDK's for various platforms — [S3SDK](https://github.com/coldbox-modules/s3sdk), [cbstripe](https://github.com/coldbox-modules/cbox-stripe), and [cbgithub](https://github.com/elpete/cbgithub), to name a few. We noticed that we spent a lot of time setting up the plumbing for the requests and a wrapper around `cfhttp`. Each implementation was mostly the same but slightly different. It was additionally frustrating because we really only needed to tweak a few values, usually just the `Authorization` header. It would be nice to create an HTTP client pre-configured for each of these SDK's. It seemed the perfect fit for a module.

### The problem it solves

Hyper exists to provide a fluent builder experience for HTTP requests and responses. It also provides a powerful way to create clients, i.e. Builder objects with pre-configured defaults like a base URL or certain headers.


# What's New?

## 7.2.0

### Cookies

Hyper can now [send cookies with a request](/7.2.0-1/making-requests/hyperrequest#withcookies) and [parse the returned cookies from a response](/7.2.0-1/making-requests/hyperresponse#getcookies). See the [HyperRequest](/7.2.0-1/making-requests/hyperrequest) and [HyperResponse](/7.2.0-1/making-requests/hyperresponse) docs for details.

## 7.1.0

### Fake Requests

Hyper now has the ability to fake requests and return fake responses as a result.  This is perfect for testing scenarios where you don't actually want to make an HTTP request.

{% content-ref url="/pages/fDs68ouvcjilusPgzOdw" %}
[Faking Requests](/7.2.0-1/testing/faking-requests)
{% endcontent-ref %}

### Custom Hyper Clients

It is now more straightforward to register a [custom Hyper client](/7.2.0-1/customizing-hyper/custom-http-clients).  Inside your `config/WireBox.cfc` in an `afterAspectsLoad` method, you can get a reference to a `HyperBuilder`, configure it as you would for a request, and then call the `registerAs` method passing in your desired WireBox alias.

```cfscript
// config/WireBox.cfc
component {

   // ...
   
   function afterApsectsLoad() {
       injector.getInstance( "HyperBuilder@hyper" )
           .setBaseUrl( "https://api.github.com" )
           .asJson()
           .withHeaders( {
               "Authorization": coldbox.getUtil().getSystemSetting( "GITHUB_TOKEN" )
           } )
           .registerAs( "GitHubClient" );
   }

}
```

This is a welcome improvement as the `init` arguments do not exactly match the method names.  Also, for defaults like `requestCallbacks`, `responseCallbacks`, or even `queryParams`, passing in arrays of functions or arrays or structs is not as straightforward as calling the related methods.  Now, you can use the Hyper methods you are familiar with when registering your custom Hyper clients.

{% hint style="info" %}
Putting the registration code in `afterAspectsLoad` is required so Hyper can be loaded and available for injection.
{% endhint %}

## 7.0.0

### CFHttp HTTP Client

This client now returns more accurate status codes for `502 Bad Gateway` and `408 Request Timeout` responses.

Previously, these responses were returned as `504 Gateway Timeout` responses. Hyper now normalizes the responses from the different CFML engines into a consistent response. `502 Bad Gateway` is returned instead of `504 Gateway Timeout` for invalid hosts. `408 Request Timeout` is returned if the request takes longer than the configured [`timeout`](/7.2.0-1/making-requests/hyperrequest#settimeout) value.

### Breaking Changes

If you were previously checking specifically for `504` status codes for bad hosts, you need to now either check for `502` status codes or use a more general method, like [`isServerError`](/7.2.0-1/making-requests/hyperresponse#isservererror) or [`isError`](/7.2.0-1/making-requests/hyperresponse#iserror).

If you were previously checking specifically for `504` status codes or [`isServerError`](/7.2.0-1/making-requests/hyperresponse#isservererror) for timed out requests, you need to now either check for `408` status codes, [`isClientError`](/7.2.0-1/making-requests/hyperresponse#isclienterror), or the more general [`isError`](/7.2.0-1/making-requests/hyperresponse#iserror).

## 6.1.0

Add [`head`](/7.2.0-1/making-requests/hyperrequest#head) and [`options`](/7.2.0-1/making-requests/hyperrequest#options) shortcut methods.

## 6.0.0

* Add `xml` support and an `asXML` method to set the body format and `Content-Type` header.
* Add `adobe@2023` to testing matrix.

### Breaking Changes

* Remove default `Content-Type` header. You must set this [manually](/7.2.0-1/making-requests/hyperrequest#setcontenttype) or use a format helper, such as [`asJson`](/7.2.0-1/making-requests/hyperrequest#asjson).
* Dropped `adobe@2016` support.

## 5.0.1

Correctly handle cases when the `body` is a string and format is `JSON`.

## 5.0.0

Add a `debug` method to see what the HTTP client generates.

### Breaking Changes

`HyperHttpClientInterface` now requires a `debug` method.

```cfscript
/**
 * Return a struct of information showing how the client will execute the HyperRequest.
 * This will be used by a developer to debug any differences between the generated
 * request values and the expected request values.
 *
 * @req     The HyperRequest to debug.
 *
 * @returns A struct of information detailing how the client would execute the HyperRequest.
 */
public struct function debug( required HyperRequest req );
```

## 4.0.3

* Do not prepend the base url when a full url is passed.
* Add `resolveUrls` and `encodeUrl` properties to the [memento](/7.2.0-1/making-requests/hyperrequest#getmemento).
* Correctly set the `encodeUrl` property when cloning a request.

## 4.0.2

Update README for builder `initWith` headers losing `Content-Type`.

## 4.0.1

Fix `HyperBuilder` example in the docs.

## 4.0.0

Allow adding multiple query params with the same key.

### Breaking Changes

Previously, query params were stored as a struct.  Some APIs expect multiple values for the same query param name to be passed as separate arguments.  Hyper now stores the query params as an array and provides new methods for interacting with query params:

* [`getQueryParamByName`](/7.2.0-1/making-requests/hyperrequest#getqueryparambyname)
* [`getAllQueryParamsByName`](/7.2.0-1/making-requests/hyperrequest#getallqueryparamsbyname)
* [`withQueryParams`](/7.2.0-1/making-requests/hyperrequest#withqueryparams)
* [`appendQueryParam`](/7.2.0-1/making-requests/hyperrequest#appendqueryparam)
* [`appendQueryParams`](/7.2.0-1/making-requests/hyperrequest#appendqueryparams)
* [`hasQueryParam`](/7.2.0-1/making-requests/hyperrequest#hasqueryparam)

The following methods still exist, but now interact with arrays of query param structs instead of a simple struct.

* [`getQueryParams`](/7.2.0-1/making-requests/hyperrequest#getqueryparams)
* [`setQueryParams`](/7.2.0-1/making-requests/hyperrequest#setqueryparams)

The following methods have been deprecated:

| Deprecated Method                                                      | Replacement Method                                                                 |
| ---------------------------------------------------------------------- | ---------------------------------------------------------------------------------- |
| [`getQueryParam`](/7.2.0-1/making-requests/hyperrequest#getqueryparam) | [`getQueryParamByName`](/7.2.0-1/making-requests/hyperrequest#getqueryparambyname) |

## 3.6.2

Convert array values correctly when sending form fields

## 3.6.1

Add a workaround for CommandBox not having the `box:asyncManager` injection DSL.

## 3.6.0

Add async requests using ColdBox's [AsyncManager](https://coldbox.ortusbooks.com/digging-deeper/promises-async-programming).

## 3.5.0

* Provide more useful error than cfhttp when [`throwOnErrors`](/7.2.0-1/making-requests/hyperrequest#throwerrors) is enabled.
* Provide mementos for [HyperRequest](/7.2.0-1/making-requests/hyperrequest#getmemento) and [HyperResponse](/7.2.0-1/making-requests/hyperresponse#getmemento) instances.
* Capture [statusText](/7.2.0-1/making-requests/hyperresponse#getstatustext) and provide a [status](/7.2.0-1/making-requests/hyperresponse#getstatus) convenience string.

## 3.4.2

Add MIT License file

## 3.4.1

Use `processState` over `announce` until CommandBox can update its `interceptorService`.

## 3.4.0

### HyperRequest

* Add [`forwardHeaders`](/7.2.0-1/making-requests/hyperrequest#forwardheaders) shortcut method.

### HyperResponse

* Allow for default values in [`getHeader`](/7.2.0-1/making-requests/hyperresponse#getheader).
* Add helper methods for checking for specific status codes:
  * [`isOk`](/7.2.0-1/making-requests/hyperresponse#isok)
  * [`isUnauthorized`](/7.2.0-1/making-requests/hyperresponse#isunauthorized)
  * [`isForbidden`](/7.2.0-1/making-requests/hyperresponse#isforbidden)
  * [`isNotFound`](/7.2.0-1/making-requests/hyperresponse#isnotfound)

## 3.3.0

Allowing [attaching](/7.2.0-1/making-requests/hyperrequest#attach) file uploads.

## 3.2.1

Support WireBox outside of ColdBox.

## 3.2.0

Include response data as detail in `DeserializeJsonException`.

## 3.1.0

* Add [`clone`](/7.2.0-1/making-requests/hyperrequest#clone) to quickly copy `HyperRequest` instances.
* Add interceptors and [local](/7.2.0-1/making-requests/hyperrequest#withrequestcallback) [callbacks](/7.2.0-1/making-requests/hyperrequest#withresponsecallback) for lifecycle events.

## 3.0.0

Add execution time to `HyperResponse` instances.

### Breaking Changes

Dropped support for ColdBox 5.

## 2.3.11

* Add support for [NTLM authentication](/7.2.0-1/making-requests/hyperrequest#withntlmauth).
* Include [`getFullURL`](/7.2.0-1/making-requests/hyperrequest#getfullurl) method in docs.

## 2.3.10

Fixed typo of `Bulider` to `Builder`.

## 2.3.9

Add [`withoutEncodingUrl`](/7.2.0-1/making-requests/hyperrequest#withoutencodingurl) flag.

## 2.3.8

Do not fail fast on cron job actions on CI.

## 2.3.7

Update fetch-depth for tests and release actions on CI.

## 2.3.6

Attempt to skip committing back changes on CI.

## 2.3.5

Add matrix and cron testing on CI.

## 2.3.4

Use better GitHub token on CI

## 2.3.1

Add workaround for `boolean` values in query strings.

## 2.3.0

Add [certificate](/7.2.0-1/making-requests/hyperrequest#withcertificateauth) auth.

## 2.2.1

Use the previous host for redirect if redirect does not include a full URL.

## 2.2.0

Add [`resolveUrls`](/7.2.0-1/making-requests/hyperrequest#setresolveurl) flag.

## 2.1.1

* Use OpenJDK instead of OracleJDK on CI.
* Store module in [ForgeBox Storage](https://commandbox.ortusbooks.com/5.6.0/developing-for-commandbox/commands).

## 2.1.0

Allow for pluggable [HTTP Clients](/7.2.0-1/customizing-hyper/custom-http-clients) that follow the `HyperHttpClientInterface`. (Clients do not need to use the `implements` keyword.)

## 2.0.2

Avoid double encoding using [`cfhttpparam`](https://cfdocs.org/cfhttpparam).

## 2.0.1

Remove Lucee 4.5 support from docs. (Support was dropped in [v2.0.0](#2.0.0))

## 2.0.0

* Do not include [`username`](/7.2.0-1/making-requests/hyperrequest#setusername) and [`password`](/7.2.0-1/making-requests/hyperrequest#setpassword) unless they have values.
* Add `adobe@2018` support to CI builds.

### Breaking Changes

Dropped support for `lucee@4.5`.

## 1.15.0

Add [`throwOnError`](/7.2.0-1/making-requests/hyperrequest#throwerrors) flag.

## 1.14.5

Use `504 Gateway Timeout` for incomplete responses.

## 1.14.4

Include equal signs in query param values.

## 1.14.0 – 1.0.0

### New Features

* Add [`when`](/7.2.0-1/making-requests/hyperrequest#when) helper to execute conditions without breaking chaining.
* Add [`clear`](/7.2.0-1/making-requests/hyperrequest#clear) method to reset HyperRequest instances.
* Add configurable [`timeout`](/7.2.0-1/making-requests/hyperrequest#settimeout).

### Bug Fixes

* Fix for Lucee 4 compatibility on `LinkedHashMaps` and `keyArray`.
* Preserve case in header names.
* Preserve case for query parameters.
* Serialize both params from the url and set on the `HyperRequest` instance.
* Default to `UTF-8` charset if none is present in the response.
* Fix withHeaders and withQueryParams for Lucee compatibility.
* Only map HyperBuilder as a singleton in WireBox

### Other

* Migrate to [coldbox-modules](https://github.com/coldbox-modules) organization on GitHub.
* Update `box.json` description.
* Enable [CommandBox Semantic Release](https://forgebox.io/view/commandbox-semantic-release) on CI.


# Upgrade Guide

## Upgrading from v6 to v7

### CFHttp HTTP Client

This client now returns more accurate status codes for `502 Bad Gateway` and `408 Request Timeout` responses.

If you were previously checking specifically for `504` status codes for bad hosts, you need to now either check for `502` status codes or use a more general method, like [`isServerError`](/7.2.0-1/making-requests/hyperresponse#isservererror) or [`isError`](/7.2.0-1/making-requests/hyperresponse#iserror).

If you were previously checking specifically for `504` status codes or [`isServerError`](/7.2.0-1/making-requests/hyperresponse#isservererror) for timed out requests, you need to now either check for `408` status codes, [`isClientError`](/7.2.0-1/making-requests/hyperresponse#isclienterror), or the more general [`isError`](/7.2.0-1/making-requests/hyperresponse#iserror).

## Upgrading from v5 to v6

* The default `Content-Type` header has been removed. You must set this [manually](/7.2.0-1/making-requests/hyperrequest#setcontenttype) or use a format helper, such as [`asJson`](/7.2.0-1/making-requests/hyperrequest#asjson).
* Dropped support for Adobe 2016.

## Upgrading from v4 to v5

`HyperHttpClientInterface` now requires a `debug` method.

```cfscript
/**
 * Return a struct of information showing how the client will execute the HyperRequest.
 * This will be used by a developer to debug any differences between the generated
 * request values and the expected request values.
 *
 * @req     The HyperRequest to debug.
 *
 * @returns A struct of information detailing how the client would execute the HyperRequest.
 */
public struct function debug( required HyperRequest req );
```

## Upgrading from v3 to v4

Previously, query params were stored as a struct.  Some APIs expect multiple values for the same query param name to be passed as separate arguments.  Hyper now stores the query params as an array and provides new methods for interacting with query params:

* [`getQueryParamByName`](/7.2.0-1/making-requests/hyperrequest#getqueryparambyname)
* [`getAllQueryParamsByName`](/7.2.0-1/making-requests/hyperrequest#getallqueryparamsbyname)
* [`withQueryParams`](/7.2.0-1/making-requests/hyperrequest#withqueryparams)
* [`appendQueryParam`](/7.2.0-1/making-requests/hyperrequest#appendqueryparam)
* [`appendQueryParams`](/7.2.0-1/making-requests/hyperrequest#appendqueryparams)
* [`hasQueryParam`](/7.2.0-1/making-requests/hyperrequest#hasqueryparam)

The following methods still exist, but now interact with arrays of query param structs instead of a simple struct.

* [`getQueryParams`](/7.2.0-1/making-requests/hyperrequest#getqueryparams)
* [`setQueryParams`](/7.2.0-1/making-requests/hyperrequest#setqueryparams)

The following methods have been deprecated:

| Deprecated Method                                                      | Replacement Method                                                                 |
| ---------------------------------------------------------------------- | ---------------------------------------------------------------------------------- |
| [`getQueryParam`](/7.2.0-1/making-requests/hyperrequest#getqueryparam) | [`getQueryParamByName`](/7.2.0-1/making-requests/hyperrequest#getqueryparambyname) |

## Upgrading from v2 to v3

Dropped support for ColdBox 5.

## Upgrading from v1 to v2

Dropped support for Lucee 4.5.


# Requirements

Hyper runs on Adobe ColdFusion 2018+ and Lucee 5+.

ColdBox is not required, but mappings are provided for ColdBox users automatically.


# Installation

Hyper is most easily installed via ForgeBox and CommandBox.

```sh
box install hyper
```

If you install Hyper in a non-ColdBox application, make sure to create a mapping in your `Application.cfc`

```cfscript
this.mappings[ "/hyper" ] = expandPath( "/modules/hyper" );
```


# HyperBuilder

A `HyperBuilder` is a singleton factory component that will give you a new [`HyperRequest`](/7.2.0-1/making-requests/hyperrequest) any time you call the `new` method.  It will also create a new [`HyperRequest`](/7.2.0-1/making-requests/hyperrequest) any time you call a method on `HyperBuilder` that exists on [`HyperRequest`](/7.2.0-1/making-requests/hyperrequest).

`HyperBuilder` is the component you want to inject into your singleton components, like handlers or services.  It will ensure you get a fresh [`HyperRequest`](/7.2.0-1/making-requests/hyperrequest) instance on each invocation.  This is important since reusing the same [`HyperRequest`](/7.2.0-1/making-requests/hyperrequest) instance will likely produce unintended results.

You can inject a `HyperBuilder` into your application using the `HyperBuilder@hyper` id.

```cfscript
component {
    
    property name="hyper" inject="HyperBuilder@hyper";

    function index( event, rc, prc ) {
        var reqA = hyper.new();
        // reqA is a new HyperRequest instance.
        
        var reqB = hyper.setUrl( "https://swapi.dev/api/people" );
        // reqB is a new HyperRequest instance with the url set.
    }

}
```

If you are not using ColdBox, you can create a `HyperBuilder` manually:

```cfscript
component {

    function init() {
        variables.hyper = new hyper.models.HyperBuilder();
    }

}
```

Additionally, you can register `HyperBuilder` instances as custom HTTP Clients.

{% content-ref url="/pages/sc1pmftTrug5lkmdOWQS" %}
[Custom HTTP Clients](/7.2.0-1/customizing-hyper/custom-http-clients)
{% endcontent-ref %}

Finally, you can enable faking of requests from any `HyperBuilder` instance.

{% content-ref url="/pages/fDs68ouvcjilusPgzOdw" %}
[Faking Requests](/7.2.0-1/testing/faking-requests)
{% endcontent-ref %}


# HyperRequest

Though the [`HyperBuilder`](/7.2.0-1/making-requests/hyperbuilder) is the component you will most likely inject, `HyperRequest` is the component will you interact with the most. `HyperRequest` provides a fluent interface to configure your HTTP call.

```cfscript
hyper.get( "https//api.github.com/users" );

hyper.setMethod( "PUT" )
    .withHeaders( { "Authorization" = "Bearer #token#" } )
    .setUrl( "https://jsonplaceholder.typicode.com/posts/1" )
    .setBody( {
        title: "New Title"
    } )
    .send();
```

## Defaults

The following are default properties for a `HyperRequest`:

```json
{
    "method": "GET"
    "resolveUrls": false,
    "encodeUrl": true,
    "timeout": 10, // in seconds
    "maximumRedirects": "*", // follow redirects indefinitely
    "bodyFormat": "json",
    "throwOnError": false
}
```

## Executing Requests

### `get`

Execute a `GET` request and return a [`HyperResponse`](/7.2.0-1/making-requests/hyperresponse).

| Name        | Type   | Required | Default | Description                                                    |
| ----------- | ------ | -------- | ------- | -------------------------------------------------------------- |
| url         | string | false    | null    | An optional URL to set for the request.                        |
| queryParams | struct | false    | null    | An optional struct of query parameters to set for the request. |

**Return**: [`HyperResponse`](/7.2.0-1/making-requests/hyperresponse)

### `getAsync`

Execute a `GET` request asynchronously. Returns a [ColdBox Future](https://coldbox.ortusbooks.com/digging-deeper/promises-async-programming) that returns a [`HyperResponse`](/7.2.0-1/making-requests/hyperresponse).

<table><thead><tr><th width="40">Name</th><th>Type</th><th>Required</th><th>Default</th><th>Description</th></tr></thead><tbody><tr><td>url</td><td>string</td><td>false</td><td>null</td><td>An optional URL to set for the request.</td></tr><tr><td>queryParams</td><td>struct</td><td>false</td><td>null</td><td>An optional struct of query parameters to set for the request.</td></tr></tbody></table>

**Return**: [`Future`](https://coldbox.ortusbooks.com/digging-deeper/promises-async-programming)`<`[`HyperResponse`](/7.2.0-1/making-requests/hyperresponse)`>`

### `post`

Execute a `POST` request and return a [`HyperResponse`](/7.2.0-1/making-requests/hyperresponse).

| Name | Type   | Required | Default | Description                              |
| ---- | ------ | -------- | ------- | ---------------------------------------- |
| url  | string | false    | null    | An optional URL to set for the request.  |
| body | struct | false    | null    | An optional body to set for the request. |

**Return**: [`HyperResponse`](/7.2.0-1/making-requests/hyperresponse)

### `postAsync`

Execute a `POST` request asynchronously. Returns a [ColdBox Future](https://coldbox.ortusbooks.com/digging-deeper/promises-async-programming) that returns a [`HyperResponse`](/7.2.0-1/making-requests/hyperresponse).

| Name | Type   | Required | Default | Description                              |
| ---- | ------ | -------- | ------- | ---------------------------------------- |
| url  | string | false    | null    | An optional URL to set for the request.  |
| body | struct | false    | null    | An optional body to set for the request. |

**Return**: [`Future`](https://coldbox.ortusbooks.com/digging-deeper/promises-async-programming)`<`[`HyperResponse`](/7.2.0-1/making-requests/hyperresponse)`>`

### `put`

Execute a `PUT` request and return a [`HyperResponse`](/7.2.0-1/making-requests/hyperresponse).

| Name | Type   | Required | Default | Description                              |
| ---- | ------ | -------- | ------- | ---------------------------------------- |
| url  | string | false    | null    | An optional URL to set for the request.  |
| body | struct | false    | null    | An optional body to set for the request. |

**Return**: [`HyperResponse`](/7.2.0-1/making-requests/hyperresponse)

### `putAsync`

Execute a `PUT` request asynchronously. Returns a [ColdBox Future](https://coldbox.ortusbooks.com/digging-deeper/promises-async-programming) that returns a [`HyperResponse`](/7.2.0-1/making-requests/hyperresponse).

| Name | Type   | Required | Default | Description                              |
| ---- | ------ | -------- | ------- | ---------------------------------------- |
| url  | string | false    | null    | An optional URL to set for the request.  |
| body | struct | false    | null    | An optional body to set for the request. |

**Return**: [`Future`](https://coldbox.ortusbooks.com/digging-deeper/promises-async-programming)`<`[`HyperResponse`](/7.2.0-1/making-requests/hyperresponse)`>`

### `patch`

Execute a `PATCH` request and return a [`HyperResponse`](/7.2.0-1/making-requests/hyperresponse).

| Name | Type   | Required | Default | Description                              |
| ---- | ------ | -------- | ------- | ---------------------------------------- |
| url  | string | false    | null    | An optional URL to set for the request.  |
| body | struct | false    | null    | An optional body to set for the request. |

**Return**: [`HyperResponse`](/7.2.0-1/making-requests/hyperresponse)

### `patchAsync`

Execute a `PATCH` request asynchronously. Returns a [ColdBox Future](https://coldbox.ortusbooks.com/digging-deeper/promises-async-programming) that returns a [`HyperResponse`](/7.2.0-1/making-requests/hyperresponse).

| Name | Type   | Required | Default | Description                              |
| ---- | ------ | -------- | ------- | ---------------------------------------- |
| url  | string | false    | null    | An optional URL to set for the request.  |
| body | struct | false    | null    | An optional body to set for the request. |

**Return**: [`Future`](https://coldbox.ortusbooks.com/digging-deeper/promises-async-programming)`<`[`HyperResponse`](/7.2.0-1/making-requests/hyperresponse)`>`

### `delete`

Execute a `DELETE` request and return a [`HyperResponse`](/7.2.0-1/making-requests/hyperresponse).

| Name | Type   | Required | Default | Description                              |
| ---- | ------ | -------- | ------- | ---------------------------------------- |
| url  | string | false    | null    | An optional URL to set for the request.  |
| body | struct | false    | null    | An optional body to set for the request. |

**Return**: [`HyperResponse`](/7.2.0-1/making-requests/hyperresponse)

### `deleteAsync`

Execute a `DELETE` request asynchronously. Returns a [ColdBox Future](https://coldbox.ortusbooks.com/digging-deeper/promises-async-programming) that returns a [`HyperResponse`](/7.2.0-1/making-requests/hyperresponse).

| Name | Type   | Required | Default | Description                              |
| ---- | ------ | -------- | ------- | ---------------------------------------- |
| url  | string | false    | null    | An optional URL to set for the request.  |
| body | struct | false    | null    | An optional body to set for the request. |

**Return**: [`Future`](https://coldbox.ortusbooks.com/digging-deeper/promises-async-programming)`<`[`HyperResponse`](/7.2.0-1/making-requests/hyperresponse)`>`

### `head`

Execute a `HEAD` request and return a [`HyperResponse`](/7.2.0-1/making-requests/hyperresponse).

| Name        | Type   | Required | Default | Description                                                    |
| ----------- | ------ | -------- | ------- | -------------------------------------------------------------- |
| url         | string | false    | null    | An optional URL to set for the request.                        |
| queryParams | struct | false    | null    | An optional struct of query parameters to set for the request. |

**Return**: [`HyperResponse`](/7.2.0-1/making-requests/hyperresponse)

### `headAsync`

Execute a `HEAD` request asynchronously. Returns a [ColdBox Future](https://coldbox.ortusbooks.com/digging-deeper/promises-async-programming) that returns a [`HyperResponse`](/7.2.0-1/making-requests/hyperresponse).

| Name        | Type   | Required | Default | Description                                                    |
| ----------- | ------ | -------- | ------- | -------------------------------------------------------------- |
| url         | string | false    | null    | An optional URL to set for the request.                        |
| queryParams | struct | false    | null    | An optional struct of query parameters to set for the request. |

**Return**: [`Future`](https://coldbox.ortusbooks.com/digging-deeper/promises-async-programming)`<`[`HyperResponse`](/7.2.0-1/making-requests/hyperresponse)`>`

### `options`

Execute an `OPTIONS` request and return a [`HyperResponse`](/7.2.0-1/making-requests/hyperresponse).

| Name        | Type   | Required | Default | Description                                                    |
| ----------- | ------ | -------- | ------- | -------------------------------------------------------------- |
| url         | string | false    | null    | An optional URL to set for the request.                        |
| queryParams | struct | false    | null    | An optional struct of query parameters to set for the request. |

**Return**: [`HyperResponse`](/7.2.0-1/making-requests/hyperresponse)

### `optionsAsync`

Execute an `OPTIONS` request asynchronously. Returns a [ColdBox Future](https://coldbox.ortusbooks.com/digging-deeper/promises-async-programming) that returns a [`HyperResponse`](/7.2.0-1/making-requests/hyperresponse).

| Name        | Type   | Required | Default | Description                                                    |
| ----------- | ------ | -------- | ------- | -------------------------------------------------------------- |
| url         | string | false    | null    | An optional URL to set for the request.                        |
| queryParams | struct | false    | null    | An optional struct of query parameters to set for the request. |

**Return**: [`Future`](https://coldbox.ortusbooks.com/digging-deeper/promises-async-programming)`<`[`HyperResponse`](/7.2.0-1/making-requests/hyperresponse)`>`

### `send`

Send the HTTP request and return a [`HyperResponse`](/7.2.0-1/making-requests/hyperresponse).

| Name         | Type | Required | Default | Description |
| ------------ | ---- | -------- | ------- | ----------- |
| No arguments |      |          |         |             |

**Return**: [`HyperResponse`](/7.2.0-1/making-requests/hyperresponse)

### `sendAsync`

Send the HTTP request asynchronously and return a [ColdBox Future](https://coldbox.ortusbooks.com/digging-deeper/promises-async-programming) that will resolve to a [`HyperResponse`](/7.2.0-1/making-requests/hyperresponse).

| Name         | Type | Required | Default | Description |
| ------------ | ---- | -------- | ------- | ----------- |
| No arguments |      |          |         |             |

**Return**: [`Future`](https://coldbox.ortusbooks.com/digging-deeper/promises-async-programming)`<`[`HyperResponse`](/7.2.0-1/making-requests/hyperresponse)`>`

## Building Requests

### `getRequestId`

Gets the unique request ID representing this request.

| Name         | Type | Required | Default | Description |
| ------------ | ---- | -------- | ------- | ----------- |
| No arguments |      |          |         |             |

**Return**: `String`

### `getFullURL`

Gets the full URL for the request.

| Name            | Type    | Required | Default | Description                                            |
| --------------- | ------- | -------- | ------- | ------------------------------------------------------ |
| withQueryString | boolean | false    | false   | Includes the configured query string with the full URL |

**Return**: `String`

### `getBaseURL`

Gets the base URL for the request. The base URL is combined with the URL when making the request.

| Name         | Type | Required | Default | Description |
| ------------ | ---- | -------- | ------- | ----------- |
| No arguments |      |          |         |             |

**Return**: `String`

### `setBaseURL`

Sets the base URL for the request. The base URL is combined with the URL when making the request.

| Name  | Type   | Required | Default | Description                                                   |
| ----- | ------ | -------- | ------- | ------------------------------------------------------------- |
| value | string | true     |         | The base URL for the request, e.g. `https://api.github.com/`. |

**Return**: `HyperRequest`

### `getURL`

Gets the URL for the request.

| Name         | Type | Required | Default | Description |
| ------------ | ---- | -------- | ------- | ----------- |
| No arguments |      |          |         |             |

**Return**: `String`

### `setURL`

Sets the URL for the request.

| Name  | Type   | Required | Default | Description                                                                                                     |
| ----- | ------ | -------- | ------- | --------------------------------------------------------------------------------------------------------------- |
| value | string | true     |         | The URL for the request. It can either be a full url or a URI resource for use with the baseURL. e.g. `/repos`. |

**Return**: `HyperRequest`

### `setResolveURL`

Sets the resolveURL parameter for the request.

| Name  | Type    | Required | Default | Description                                                                    |
| ----- | ------- | -------- | ------- | ------------------------------------------------------------------------------ |
| value | boolean | false    | false   | Resolves URLs in the response body to absolute URLs, including the port number |

**Return**: `HyperRequest`

### `getMethod`

Gets the HTTP method for the request.

| Name         | Type | Required | Default | Description |
| ------------ | ---- | -------- | ------- | ----------- |
| No arguments |      |          |         |             |

**Return**: `String`

### `setMethod`

Sets the HTTP method for the request.

| Name  | Type   | Required | Default | Description                      |
| ----- | ------ | -------- | ------- | -------------------------------- |
| value | string | true     |         | The HTTP method for the request. |

**Return**: `HyperRequest`

### `withBasicAuth`

Sets the username and password for HTTP Basic Auth.

| Name     | Type   | Required | Default | Description                      |
| -------- | ------ | -------- | ------- | -------------------------------- |
| username | string | true     |         | The username for the basic auth. |
| password | string | true     |         | The password for the basic auth. |

**Return**: `HyperRequest`

### `withCertificateAuth`

Sets the username and password for HTTP Basic Auth.

| Name            | Type   | Required | Default | Description                                              |
| --------------- | ------ | -------- | ------- | -------------------------------------------------------- |
| certificatePath | string | true     |         | The mapped path to the certificate used to authenticate. |
| password        | string | false    |         | The optional password used to decrypt the certificate.   |

**Return**: `HyperRequest`

### `withNTLMAuth`

Sets the username, password, domain and workstation for NTLM Auth.

| Name        | Type   | Required | Default | Description                        |
| ----------- | ------ | -------- | ------- | ---------------------------------- |
| username    | string | true     |         | The username for the NTLM auth.    |
| password    | string | true     |         | The password for the NTLM auth.    |
| domain      | string | true     |         | The domain for the NTLM auth.      |
| workstation | string | true     |         | The workstation for the NTLM auth. |

Workstation can be obtained with `createObject('java','java.net.InetAddress').getLocalHost().getHostName()`

**Return**: `HyperRequest`

### `withRequestCallback`

Schedules a callback to be ran when executing the request.

| Name     | Type     | Required | Default | Description                                     |
| -------- | -------- | -------- | ------- | ----------------------------------------------- |
| callback | function | true     |         | The callback to run when executing the request. |

**Return**: `HyperRequest`

### `withResponseCallback`

Schedules a callback to be ran when receiving the response.

| Name     | Type     | Required | Default | Description                                      |
| -------- | -------- | -------- | ------- | ------------------------------------------------ |
| callback | function | true     |         | The callback to run when receiving the response. |

**Return**: `HyperRequest`

### `getUsername`

Gets the username for the request.

| Name         | Type | Required | Default | Description |
| ------------ | ---- | -------- | ------- | ----------- |
| No arguments |      |          |         |             |

**Return**: `String`

### `setUsername`

Sets the username for the request.

| Name  | Type   | Required | Default | Description                   |
| ----- | ------ | -------- | ------- | ----------------------------- |
| value | string | true     |         | The username for the request. |

**Return**: `HyperRequest`

### `getPassword`

Gets the password for the request.

| Name         | Type | Required | Default | Description |
| ------------ | ---- | -------- | ------- | ----------- |
| No arguments |      |          |         |             |

**Return**: `String`

### `setPassword`

Sets the password for the request.

| Name  | Type   | Required | Default | Description                   |
| ----- | ------ | -------- | ------- | ----------------------------- |
| value | string | true     |         | The password for the request. |

**Return**: `HyperRequest`

### `getTimeout`

Gets the timeout for the request, in seconds.

| Name         | Type | Required | Default | Description |
| ------------ | ---- | -------- | ------- | ----------- |
| No arguments |      |          |         |             |

**Return**: `numeric`

### `setTimeout`

Sets the timeout for the request, in seconds.

| Name  | Type   | Required | Default | Description                              |
| ----- | ------ | -------- | ------- | ---------------------------------------- |
| value | string | true     |         | The timeout for the request, in seconds. |

**Return**: `HyperRequest`

### `withoutRedirecting`

A convenience method to not follow any redirects.

| Name         | Type | Required | Default | Description |
| ------------ | ---- | -------- | ------- | ----------- |
| No arguments |      |          |         |             |

**Return**: `HyperRequest`

### `withoutEncodingUrl`

A convenience method to not encode the url.

{% hint style="warning" %}
**WARNING**: Not supported on Adobe engines.
{% endhint %}

| Name         | Type | Required | Default | Description |
| ------------ | ---- | -------- | ------- | ----------- |
| No arguments |      |          |         |             |

**Return**: `HyperRequest`

### `getMaximumRedirects`

Gets the maximum number of redirects to follow.

| Name         | Type | Required | Default | Description |
| ------------ | ---- | -------- | ------- | ----------- |
| No arguments |      |          |         |             |

**Return**: `numeric | String`

### `setMaximumRedirects`

Sets the maximum number of redirects to follow. A value of `*` will follow redirects infinitely.

| Name  | Type | Required | Default | Description                                |
| ----- | ---- | -------- | ------- | ------------------------------------------ |
| value | any  | true     |         | The maximum number of redirects to follow. |

**Return**: `HyperRequest`

### `getBody`

Gets the body for the request.

| Name         | Type | Required | Default | Description |
| ------------ | ---- | -------- | ------- | ----------- |
| No arguments |      |          |         |             |

**Return**: `any`

### `setBody`

Sets the body for the request. Complex values will be serialized before sending the request.

| Name  | Type | Required | Default | Description               |
| ----- | ---- | -------- | ------- | ------------------------- |
| value | any  | true     |         | The body for the request. |

**Return**: `HyperRequest`

### `hasBody`

Checks if the request has a body.

| Name         | Type | Required | Default | Description |
| ------------ | ---- | -------- | ------- | ----------- |
| No arguments |      |          |         |             |

**Return**: `boolean`

### `getBodyFormat`

Gets the body format for the request.

| Name         | Type | Required | Default | Description |
| ------------ | ---- | -------- | ------- | ----------- |
| No arguments |      |          |         |             |

**Return**: `String`

### `setBodyFormat`

Sets the body format for the request. Recognized values are `formFields`, `json`, or `xml`. It is highly recommended to use `asFormFields`, `asJson`, or `asXML` instead.  If you set this value to a non-recognized value, the body will be passed along as-is to the body of the HTTP request.

| Name  | Type | Required | Default | Description                      |
| ----- | ---- | -------- | ------- | -------------------------------- |
| value | any  | true     |         | The body format for the request. |

**Return**: `HyperRequest`

### `asJson`

A convenience method to set the body format and Content-Type to `json`.

| Name         | Type | Required | Default | Description |
| ------------ | ---- | -------- | ------- | ----------- |
| No arguments |      |          |         |             |

**Return**: `HyperRequest`

### `asFormFields`

A convenience method to set the body format and Content-Type to form fields.

| Name         | Type | Required | Default | Description |
| ------------ | ---- | -------- | ------- | ----------- |
| No arguments |      |          |         |             |

**Return**: `HyperRequest`

### `asXML`

A convenience method to set the body format and Content-Type to `xml`.

| Name         | Type | Required | Default | Description |
| ------------ | ---- | -------- | ------- | ----------- |
| No arguments |      |          |         |             |

**Return**: `HyperRequest`

### `getReferrer`

Gets the referrer for the request, if any.

| Name         | Type | Required | Default | Description |
| ------------ | ---- | -------- | ------- | ----------- |
| No arguments |      |          |         |             |

**Return**: `String`

### `getHeaders`

Gets the headers for the request.

| Name         | Type | Required | Default | Description |
| ------------ | ---- | -------- | ------- | ----------- |
| No arguments |      |          |         |             |

**Return**: `java.util.LinkedHashMap`

### `setHeaders`

Sets the headers for the request.

| Name  | Type   | Required | Default | Description                  |
| ----- | ------ | -------- | ------- | ---------------------------- |
| value | struct | true     |         | The headers for the request. |

**Return**: `HyperRequest`

### `setHeader`

Set a header for the request.

| Name  | Type   | Required | Default | Description              |
| ----- | ------ | -------- | ------- | ------------------------ |
| name  | string | true     |         | The name of the header.  |
| value | string | true     |         | The value of the header. |

**Return**: `HyperRequest`

### `withHeaders`

Add additional headers to the request.

| Name    | Type   | Required | Default | Description                                |
| ------- | ------ | -------- | ------- | ------------------------------------------ |
| headers | struct | true     |         | A struct of headers to add to the request. |

**Return**: `HyperRequest`

### `forwardHeaders`

Adds specified headers to the request if they exist. Usually used in conjunction with the current CFML request headers.

| Name    | Type   | Required | Default                               | Description                                                                           |
| ------- | ------ | -------- | ------------------------------------- | ------------------------------------------------------------------------------------- |
| names   | array  | true     |                                       | An array of header names to add to the request if they exist in the `headers` struct. |
| headers | struct | false    | `getHTTPRequestData( false ).headers` | A struct of headers to inspect.                                                       |

**Return**: `HyperRequest`

### `hasHeader`

Check if the request has a header with the given name.

| Name | Type   | Required | Default | Description                      |
| ---- | ------ | -------- | ------- | -------------------------------- |
| name | string | true     |         | The name of the header to check. |

**Return**: `boolean`

### `getCookies`

Gets the cookies for the request.

| Name         | Type | Required | Default | Description |
| ------------ | ---- | -------- | ------- | ----------- |
| No arguments |      |          |         |             |

**Return**: `struct<ordered>`

### `setCookies`

Sets the cookies for the request.

| Name  | Type   | Required | Default | Description                  |
| ----- | ------ | -------- | ------- | ---------------------------- |
| value | struct | true     |         | The headers for the request. |

**Return**: `HyperRequest`

### `setCookie`

Set a cookie for the request.

| Name  | Type   | Required | Default | Description              |
| ----- | ------ | -------- | ------- | ------------------------ |
| name  | string | true     |         | The name of the header.  |
| value | string | true     |         | The value of the header. |

**Return**: `HyperRequest`

### `withCookies`

Add additional cookies to the request.

| Name    | Type   | Required | Default | Description                                |
| ------- | ------ | -------- | ------- | ------------------------------------------ |
| cookies | struct | true     |         | A struct of headers to add to the request. |

**Return**: `HyperRequest`

### `withCredentials`

Sends all current cookies along with the request.

| Name         | Type | Required | Default | Description |
| ------------ | ---- | -------- | ------- | ----------- |
| No arguments |      |          |         |             |

**Return**: `HyperRequest`

### `hasCookie`

Check if the request has a cookie with the given name.

| Name | Type   | Required | Default | Description                      |
| ---- | ------ | -------- | ------- | -------------------------------- |
| name | string | true     |         | The name of the header to check. |

**Return**: `boolean`

### `setContentType`

A convenience method to set the [`Content-Type` header](https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Content-Type).

| Name | Type   | Required | Default | Description                            |
| ---- | ------ | -------- | ------- | -------------------------------------- |
| type | string | true     |         | The Content-Type value for the request |

**Return**: `HyperRequest`

### `setAccept`

A convenience method to set the [`Accept` header](https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Accept).

| Name | Type   | Required | Default | Description                      |
| ---- | ------ | -------- | ------- | -------------------------------- |
| type | string | true     |         | The Accept value for the request |

**Return**: `HyperRequest`

### `getQueryParams`

Gets the query parameters for the request.

{% hint style="warning" %}
This method returns an array of param structs that is used under the hood by Hyper. You probably want to use [`getQueryParamByName`](#getqueryparambyname) or [`getAllQueryParamsByName`](#getallqueryparamsbyname) instead.
{% endhint %}

| Name         | Type | Required | Default | Description |
| ------------ | ---- | -------- | ------- | ----------- |
| No arguments |      |          |         |             |

**Return**: `array<struct<string, any>>`

### `setQueryParams`

Sets the query parameters for the request.

{% hint style="warning" %}
This method accepts an array of param structs that is used under the hood by Hyper. You probably want to use [`withQueryParams`](#withqueryparams) or [`appendQueryParams`](#appendqueryparams) instead.
{% endhint %}

If needed, param structs have two keys, `name` and `value`.

| Name  | Type  | Required | Default | Description                                                |
| ----- | ----- | -------- | ------- | ---------------------------------------------------------- |
| value | array | true     |         | The query parameters for the as an array of param structs. |

**Return**: `HyperRequest`

### `getQueryParam`

{% hint style="danger" %}
**DEPRECATED:** Use [`getQueryParamByName`](#getqueryparambyname)
{% endhint %}

Gets the first value for a certain query parameter. Returns an empty string if the query parameter does not exist.

| Name | Type   | Required | Default | Description                                                  |
| ---- | ------ | -------- | ------- | ------------------------------------------------------------ |
| name | string | true     |         | The name of the query parameter to retrieve the first value. |

**Return**: `any`

### `getQueryParamByName`

Gets the first value for a certian query parameter. Returns an empty string if the query parameter does not exist.

| Name | Type   | Required | Default | Description                                                  |
| ---- | ------ | -------- | ------- | ------------------------------------------------------------ |
| name | string | true     |         | The name of the query parameter to retrieve the first value. |

**Return**: `any`

### `getAllQueryParamsByName`

Get all the values for a certain query parameter. Returns an empty array if the query parameter does not exist.

| Name | Type   | Required | Default | Description                                                    |
| ---- | ------ | -------- | ------- | -------------------------------------------------------------- |
| name | string | true     |         | The name of the query parameter to retrieve all of its values. |

**Return**: `array<any>`

### `setQueryParam`

Set a query parameter for the request.

{% hint style="info" %}
**Note:** This removes all other query params with the same name.
{% endhint %}

| Name  | Type   | Required | Default | Description                       |
| ----- | ------ | -------- | ------- | --------------------------------- |
| name  | string | true     |         | The name of the query parameter.  |
| value | string | true     |         | The value of the query parameter. |

**Return**: `HyperRequest`

### `appendQueryParam`

Append a query parameter for the request.

| Name  | Type   | Required | Default | Description                       |
| ----- | ------ | -------- | ------- | --------------------------------- |
| name  | string | true     |         | The name of the query parameter.  |
| value | string | true     |         | The value of the query parameter. |

**Return**: `HyperRequest`

### `withQueryParams`

Add additional query parameters to the request.&#x20;

{% hint style="info" %}
**Note:** This will remove any values with duplicate keys prior to adding the new struct of params.
{% endhint %}

| Name        | Type   | Required | Default | Description                                         |
| ----------- | ------ | -------- | ------- | --------------------------------------------------- |
| queryParams | struct | true     |         | A struct of query parameters to add to the request. |

**Return**: `HyperRequest`

### `appendQueryParams`

Appends additional query parameters to the request.

| Name        | Type   | Required | Default | Description                                         |
| ----------- | ------ | -------- | ------- | --------------------------------------------------- |
| queryParams | struct | true     |         | A struct of query parameters to add to the request. |

**Return**: `HyperRequest`

### `hasQueryParam`

Check if the request has a query parameter with the given name.

| Name | Type   | Required | Default | Description                               |
| ---- | ------ | -------- | ------- | ----------------------------------------- |
| name | string | true     |         | The name of the query parameter to check. |

**Return**: `boolean`

### `attach`

Attaches a file to the Hyper request. Also sets the Content-Type as `multipart/form-data`. Multiple files can be attached by calling `attach` multiple times before calling a send method.

| Name     | Type   | Required | Default | Description                                       |
| -------- | ------ | -------- | ------- | ------------------------------------------------- |
| name     | string | true     |         | The name of the file being uploaded.              |
| path     | string | true     |         | The absolute path to the file to be uploaded.     |
| mimeType | string | false    |         | An optional mime type to associate with the file. |

**Return**: `HyperRequest`

### `setThrowOnError`

Sets the throw on error property for the request. If true, statuses in the 4xx and 5xx range will be turned in to exceptions.

| Name  | Type    | Required | Default | Description                           |
| ----- | ------- | -------- | ------- | ------------------------------------- |
| value | boolean | true     |         | The value of the throw on error flag. |

**Return**: `HyperRequest`

### `throwErrors`

A convenience method to throw on errors.

| Name         | Type | Required | Default | Description |
| ------------ | ---- | -------- | ------- | ----------- |
| No arguments |      |          |         |             |

**Return**: `HyperRequest`

### `allowErrors`

A convenience method to not throw on errors.

| Name         | Type | Required | Default | Description |
| ------------ | ---- | -------- | ------- | ----------- |
| No arguments |      |          |         |             |

**Return**: `HyperRequest`

### `clone`

Clones the current request into a new HyperRequest.

| Name         | Type | Required | Default | Description |
| ------------ | ---- | -------- | ------- | ----------- |
| No arguments |      |          |         |             |

**Return**: A new `HyperRequest` instance cloned from this one.

### `clear`

Clears the request of any set values, including defaults passed by the builder.

| Name         | Type | Required | Default | Description |
| ------------ | ---- | -------- | ------- | ----------- |
| No arguments |      |          |         |             |

**Return**: `HyperRequest`

### `when`

Helper to conditionally execute a callback for the `HyperRequest`. This method lets you use conditionals without breaking chaining.

| Name            | Type       | Required | Default | Description                                                                                            |
| --------------- | ---------- | -------- | ------- | ------------------------------------------------------------------------------------------------------ |
| condition       | `boolean`  | `true`   |         | The condition to check.                                                                                |
| successCallback | `function` | `true`   |         | The callback to execute if the condition is true. The callback is passed the `HyperRequest` instance.  |
| failureCallback | `function` | `false`  | `null`  | The callback to execute if the condition is false. The callback is passed the `HyperRequest` instance. |

**Return**: `HyperRequest`

### `setProperties`

Quickly set many request properties using a struct. The key should be the name of one of the properties on the request, e.g. `url`, `headers`, `method`, `body`.

| Name       | Type   | Required | Default | Description                                                                                                                                   |
| ---------- | ------ | -------- | ------- | --------------------------------------------------------------------------------------------------------------------------------------------- |
| properties | struct | true     |         | A struct of properties to set. Each property name will be set on the request. Properties that don't exist on the request will throw an error. |

**Return**: `HyperRequest`

### `setHttpClient`

Sets the [HTTP Client](/7.2.0-1/customizing-hyper/custom-http-clients) to use for the request. The client should conform to the `HyperHttpClientInterface` (though it does not need to use the `implements` keyword).

| Name       | Type                       | Required | Default | Description                            |
| ---------- | -------------------------- | -------- | ------- | -------------------------------------- |
| httpClient | `HyperHttpClientInterface` | `true`   |         | The httpClient to use for the request. |

**Return**: `HyperRequest`

### `setInterceptorService`

Sets the [ColdBox Interceptor Service](https://coldbox.ortusbooks.com/the-basics/interceptors) to announce request and response interception points. A noop option is provided in the `init` for non-ColdBox usage.

| Name               | Type | Required | Default | Description                                     |
| ------------------ | ---- | -------- | ------- | ----------------------------------------------- |
| interceptorService | any  | `true`   |         | The interceptor service to use for the request. |

**Return**: `HyperRequest`

### `setAsyncManager`

Sets the [ColdBox AsyncManager](https://coldbox.ortusbooks.com/digging-deeper/promises-async-programming) to send requests asynchronously. A noop option is provided in the `init` for non-ColdBox usage.

| Name         | Type | Required | Default | Description                              |
| ------------ | ---- | -------- | ------- | ---------------------------------------- |
| asyncManager | any  | `true`   |         | The asyncManager to use for the request. |

**Return**: `HyperRequest`

### `getMemento`

Returns a struct representing this `HyperRequest`.

| Name         | Type | Required | Default | Description |
| ------------ | ---- | -------- | ------- | ----------- |
| No arguments |      |          |         |             |

**Return**:

```json
{
    "requestID"          : getRequestID(),
    "baseUrl"            : getBaseUrl(),
    "url"                : getUrl(),
    "fullUrl"            : getFullUrl(),
    "method"             : getMethod(),
    "queryParams"        : getQueryParams(),
    "headers"            : getHeaders(),
    "cookies"            : getCookies(),
    "files"              : getFiles(),
    "bodyFormat"         : getBodyFormat(),
    "body"               : getBody(),
    "referrer"           : isNull( variables.referrer ) ? "" : variables.referrer,
    "throwOnError"       : getThrowOnError(),
    "timeout"            : getTimeout(),
    "maximumRedirects"   : getMaximumRedirects(),
    "authType"           : getAuthType(),
    "username"           : getUsername(),
    "password"           : getPassword(),
    "clientCert"         : isNull( variables.clientCert ) ? "" : variables.clientCert,
    "clientCertPassword" : isNull( variables.clientCertPassword ) ? "" : variables.clientCertPassword,
    "domain"             : getDomain(),
    "workstation"        : getWorkstation(),
    "resolveUrls"        : getResolveUrls(),
    "encodeUrl"          : getEncodeUrl()
};
```

### `debug`

Creates a debug representation of the HTTP request for the current HTTP client.

{% hint style="danger" %}
**Throws**: `NoUrlException` when no URL is set.
{% endhint %}

| Name         | Type | Required | Default | Description |
| ------------ | ---- | -------- | ------- | ----------- |
| No arguments |      |          |         |             |

**Return**: Dependent on the configured HTTP Client.  See specific HTTP Client documentation for details.


# HyperResponse

The `HyperResponse` component is a read-only wrapper to easily grab different information about the response.

### `getResponseId`

Gets the unique response ID representing this response.

| Name         | Type | Required | Default | Description |
| ------------ | ---- | -------- | ------- | ----------- |
| No arguments |      |          |         |             |

**Return**: `String`

### `getStatusCode`

Gets the status code for the response.

| Name         | Type | Required | Default | Description |
| ------------ | ---- | -------- | ------- | ----------- |
| No arguments |      |          |         |             |

**Return**: `numeric`

### `getStatusText`

Gets the status text for the response.

| Name         | Type | Required | Default | Description |
| ------------ | ---- | -------- | ------- | ----------- |
| No arguments |      |          |         |             |

**Return**: `String`

### `getStatus`

Returns the status code and status text as a single string.

| Name         | Type | Required | Default | Description |
| ------------ | ---- | -------- | ------- | ----------- |
| No arguments |      |          |         |             |

**Return**: `String`

### `getData`

Gets the data for the response.

| Name         | Type | Required | Default | Description |
| ------------ | ---- | -------- | ------- | ----------- |
| No arguments |      |          |         |             |

**Return**: `String`

### `getRequestID`

Returns the id of the request to which this response is related.

| Name         | Type | Required | Default | Description |
| ------------ | ---- | -------- | ------- | ----------- |
| No arguments |      |          |         |             |

**Return**: `String`

### `getRequest`

Gets the [HyperRequest](/7.2.0-1/making-requests/hyperrequest) instance associated with this response.

| Name         | Type | Required | Default | Description |
| ------------ | ---- | -------- | ------- | ----------- |
| No arguments |      |          |         |             |

**Return**: [`HyperRequest`](/7.2.0-1/making-requests/hyperrequest)

### `getCharset`

Gets the charset value for the response.

| Name         | Type | Required | Default | Description |
| ------------ | ---- | -------- | ------- | ----------- |
| No arguments |      |          |         |             |

**Return**: `String`

### `getTimestamp`

Gets the timestamp for when this response was received.

| Name         | Type | Required | Default | Description |
| ------------ | ---- | -------- | ------- | ----------- |
| No arguments |      |          |         |             |

**Return**: `DateTime`

### `getExecutionTime`

Gets the execution time of the request, in milliseconds.

| Name         | Type | Required | Default | Description |
| ------------ | ---- | -------- | ------- | ----------- |
| No arguments |      |          |         |             |

**Return**: `numeric`

### `json`

Returns the data of the request as deserialized `JSON`.

{% hint style="danger" %}
**Throws**: `DeserializeJsonException` if the response is not `JSON`.
{% endhint %}

| Name         | Type | Required | Default | Description |
| ------------ | ---- | -------- | ------- | ----------- |
| No arguments |      |          |         |             |

**Return**: `any`

### `isSuccess`

Returns true if the request status code is considered successful.

| Name         | Type | Required | Default | Description |
| ------------ | ---- | -------- | ------- | ----------- |
| No arguments |      |          |         |             |

**Return**: `boolean`

### `isOK`

Returns true if the request status code is `200 OK`.

| Name         | Type | Required | Default | Description |
| ------------ | ---- | -------- | ------- | ----------- |
| No arguments |      |          |         |             |

**Return**: `boolean`

### `isCreated`

Returns true if the request status code is `201 Created`.

| Name         | Type | Required | Default | Description |
| ------------ | ---- | -------- | ------- | ----------- |
| No arguments |      |          |         |             |

**Return**: `boolean`

### `isRedirect`

Returns true if the request status code is considered a redirect.

| Name         | Type | Required | Default | Description |
| ------------ | ---- | -------- | ------- | ----------- |
| No arguments |      |          |         |             |

**Return**: `boolean`

### `isError`

Returns true if the request status code is considered either a client error (4xx status code) or a server error (5xx status code).

| Name         | Type | Required | Default | Description |
| ------------ | ---- | -------- | ------- | ----------- |
| No arguments |      |          |         |             |

**Return**: `boolean`

### `isClientError`

Returns true if the request status code is considered a client error (4xx status code).

| Name         | Type | Required | Default | Description |
| ------------ | ---- | -------- | ------- | ----------- |
| No arguments |      |          |         |             |

**Return**: `boolean`

### `isUnauthorized`

Returns true if the request status code is `401 Unauthorized`.

| Name         | Type | Required | Default | Description |
| ------------ | ---- | -------- | ------- | ----------- |
| No arguments |      |          |         |             |

**Return**: `boolean`

### `isForbidden`

Returns true if the request status code is `403 Forbidden`.

| Name         | Type | Required | Default | Description |
| ------------ | ---- | -------- | ------- | ----------- |
| No arguments |      |          |         |             |

**Return**: `boolean`

### `isNotFound`

Returns true if the request status code is `404 Not Found`.

| Name         | Type | Required | Default | Description |
| ------------ | ---- | -------- | ------- | ----------- |
| No arguments |      |          |         |             |

**Return**: `boolean`

### `isServerError`

Returns true if the request status code is considered a server error (5xx status code).

| Name         | Type | Required | Default | Description |
| ------------ | ---- | -------- | ------- | ----------- |
| No arguments |      |          |         |             |

**Return**: `boolean`

### `hasHeader`

Checks if a header exists in the response.

| Name | Type     | Required | Default | Description                      |
| ---- | -------- | -------- | ------- | -------------------------------- |
| name | `String` | `true`   |         | The name of the header to check. |

**Return**: `boolean`

### `getHeader`

Gets the value of a header from the response.

| Name         | Type     | Required | Default | Description                                       |
| ------------ | -------- | -------- | ------- | ------------------------------------------------- |
| name         | `String` | `true`   |         | The name of the header to retrieve.               |
| defaultValue | `any`    | `false`  | `""`    | The value to return if the header does not exist. |

**Return**: `any`

### `getCookies`

Caches the result of parsing the `Set-Cookie` header and returns it.

| Name         | Type | Required | Default | Description |
| ------------ | ---- | -------- | ------- | ----------- |
| No arguments |      |          |         |             |

**Return**: `struct`

### `persistCookies`

Parses and saves the cookies to the cookie scope.

| Name         | Type | Required | Default | Description |
| ------------ | ---- | -------- | ------- | ----------- |
| No arguments |      |          |         |             |

**Return**: `HyperResponse`

### `getMemento`

Gets a serializable representation of the response.

| Name         | Type | Required | Default | Description |
| ------------ | ---- | -------- | ------- | ----------- |
| No arguments |      |          |         |             |

**Return**:

```json
{
    "responseID"    : getResponseID(),
    "requestID"     : getRequestID(),
    "statusCode"    : getStatusCode(),
    "statusText"    : getStatusText(),
    "status"        : getStatus(),
    "data"          : getData(),
    "charset"       : getCharset(),
    "headers"       : getHeaders(),
    "timestamp"     : getTimestamp(),
    "executionTime" : getExecutionTime(),
    "cookies"       : getCookies()
}
```


# Hyper Clients

Hyper allows you to configure defaults for your requests as custom Hyper Clients. This is particularly useful for reducing boilerplate in your application.

Defaults are set on the `HyperBuilder` instance. The easiest way to do this is to configure it in WireBox. In an `afterAspectsLoad` method, you can get a reference to a `HyperBuilder`, configure it as you would for a request, and then call the `registerAs` method passing in your desired WireBox alias.

```cfscript
// config/WireBox.cfc
component {

   // ...
   
   function afterApsectsLoad() {
       injector.getInstance( "HyperBuilder@hyper" )
           .setBaseUrl( "https://swapi.dev/api" )
           .asJson()
           .registerAs( "StarWarsClient" );
   }

}
```

{% hint style="info" %}
Putting the registration code in `afterAspectsLoad` is required so Hyper can be loaded and available for injection.
{% endhint %}

Now, you can inject this pre-configured builder wherever you need in your application:

```js
component {

    property name="StarWarsClient" inject="StarWarsClient";

    function findUser( id ) {
        return variables.StarWarsClient.get( "/people/#id#" );
    }

}
```

You can alternatively create the clients by passing in the desired defaults to the `initWith` method of a WireBox mapping.  These arguments must match the [`HyperRequest` property names](#hyperrequest-property-names).

```js
// config/WireBox.cfc
component {

    function configure() {
        map( "StarWarsClient" )
            .to( "hyper.models.HyperBuilder" )
            .asSingleton()
            .initWith(
                baseUrl = "https://swapi.dev/api"
            );
    }

}
```

You can even create multiple clients using this approach:

```js
// config/WireBox.cfc
component {

    function configure() {
        // ...
    }

    function afterAspectsLoad() {
        injector.getInstance( "HyperBuilder@hyper" )
           .setBaseUrl( "https://swapi.dev/api" )
           .asJson()
           .registerAs( "StarWarsClient" );

       injector.getInstance( "HyperBuilder@hyper" )
           .setBaseUrl( "https://api.github.com" )
           .asJson()
           .withHeaders( {
               "Authorization": coldbox.getUtil().getSystemSetting( "GITHUB_TOKEN" )
           } )
           .registerAs( "GitHubClient" );
    }

}
```

You can also set or change the defaults by either passing the key / value pairs in to the `init` method or by calling the appropriate `HyperRequest` method on the `HyperBuilder.defaults` property.

```js
var hyper = new Hyper.models.HyperBuilder(
    baseUrl = "https://api.github.com"
);
hyper.defaults.withHeaders( { "Authorization" = token } );
```

#### HyperRequest property names

```cfscript
/**
* The httpClient to use for the request
*/
property name="httpClient";

/**
* The baseURL for the request.
* e.g. https://api.github.com/
*/
property name="baseUrl" default="";

/**
* The URL for the request.
* It can either be a full url
* or a URI resource for use with the baseURL.
* e.g. /repos
*/
property name="url" default="";

/**
* Setting this to true will change all relative urls in the document to absolute.
*/
property name="resolveUrls" default="false";

/**
* Setting this to false will not automatically encode the url passed.
* WARNING: Setting this to false is not supported on Adobe engines.
*/
property name="encodeUrl" default="true";

/**
* The HTTP method for the request.
*/
property name="method" default="GET";

/**
* The username for the request for basic auth.
*/
property name="username" default="";

/**
* The password for the request for basic auth.
*/
property name="password" default="";

/**
* Timeout, in seconds, for the request.
*/
property name="timeout" default="10";

/**
* The maximum number of redirects to follow.
* A value of `*` will follow redirects infinitely.
*/
property name="maximumRedirects" default="*";

/**
* The body to send with the request.
* How the body is serialized is
* determined by the bodyFormat.
*/
property name="body" default="";

/**
* The format to serialize the body.
* e.g. `json` or `formFields`
*/
property name="bodyFormat" default="json";

/**
* The referring response in the case of redirects.
*/
property name="referrer";

/**
* A struct of headers for the request.
*/
property name="headers";

/**
* A struct of query parameters for the request.
*/
property name="queryParams";

/**
* Flag to throw on a cfhttp error.
*/
property name="throwOnError" default="false";

/**
* The full path to a PKCS12 format file that contains the client certificate for the request.
*/
property name="clientCert";

/**
* 	Password used to decrypt the client certificate.
*/
property name="clientCertPassword";

/**
* The domain for the request for NTLM auth.
*/
property name="domain" default="";

/**
* The workstation for the request for NTLM auth.
*/
property name="workstation" default="";

/**
* The authType for the request
*/
property name="authType" default="BASIC";

/**
* An array of callback functions to call
* before firing off a request.
*/
property name="requestCallbacks" type="array";

/**
* An array of callback functions to call
* after receiving a response.
*/
property name="responseCallbacks" type="array";
```

If you need per-request or per-response manipulation of defaults, use the [`requestCallbacks`](/7.2.0-1/making-requests/hyperrequest#withrequestcallback) and [`responseCallbacks`](/7.2.0-1/making-requests/hyperrequest#withresponsecallback) hooks.

```cfscript
map( "ApiClient" )
    .to( "hyper.models.HyperBuilder" )
    .asSingleton()
    .initWith(
        baseUrl = getColdBox().getUtil().getSystemSetting( "API_URL" ),
        requestCallbacks = [
            // provide the current user's token for the request
            function( req ) {
                var auth = getWireBox().getInstance( "AuthenticationService@cbauth" );
                req.withHeaders( "Authorization", auth.user().getApiToken() );
            }
        ],
        responseCallbacks = [
            // map custom `error` property to an exception
            function ( res ) {
                if ( !res.isError() ) {
                    return;
                }
                
                var body = res.json();
                throw(
                    type = "ApiError",
                    message = body.error.message,
                    detail = body.error.code
                );
            }
        ]
    );
```


# Custom HTTP Clients

By default, Hyper makes HTTP requests using `cfhttp` under the hood.  This can be swapped out by any compatible HTTP client that follows the `HyperHttpClientInterface`.

```cfscript
/**
 * Responsible for executing the HyperRequest and mapping it to a HyperResponse
 */
interface displayname="HyperHttpClientInterface" {

	/**
	 * Execute the HyperRequest and map it to a HyperResponse.
	 *
	 * @req     The HyperRequest to execute.
	 *
	 * @returns A HyperResponse of the executed request.
	 */
	public HyperResponse function send( required HyperRequest req );

	/**
	 * Return a struct of information showing how the client will execute the HyperRequest.
	 * This will be used by a developer to debug any differences between the generated
	 * request values and the expected request values.
	 *
	 * @req     The HyperRequest to debug.
	 *
	 * @returns A struct of information detailing how the client would execute the HyperRequest.
	 */
	public struct function debug( required HyperRequest req );

}
```


# CfhttpHttpClient

### `debug`

Return a struct of information showing how the client will execute the [`HyperRequest`](/7.2.0-1/making-requests/hyperrequest). This will be used by a developer to debug any differences between the generated request values and the expected request values.

| Name | Type                                                    | Required | Default | Description                                                           |
| ---- | ------------------------------------------------------- | -------- | ------- | --------------------------------------------------------------------- |
| req  | [`HyperRequest`](/7.2.0-1/making-requests/hyperrequest) | `true`   |         | The [`HyperRequest`](/7.2.0-1/making-requests/hyperrequest) to debug. |

**Return**:

```json
{
    "attributes" : attrCollection,
    "body"       : {
        "headers" : cfhttpHeaders,
        "params"  : cfhttpParams,
        "files"   : cfhttpFiles,
        "body"    : cfhttpBody,
        "cookies" : cfhttpCookies
    }
}
```


# Faking Requests

Hyper has the ability to fake requests and return fake responses as a result.  This is perfect for [testing](https://testbox.ortusbooks.com/) scenarios where you don't actually want to make an HTTP request.

{% hint style="warning" %}
Non-ColdBox users will need to add a mapping to the [`Globber`](https://forgebox.io/view/globber) dependency included with Hyper.

```cfscript
// Application.cfc
component {
    this.mappings[ "/globber" ] = "/path/to/hyper" & "/modules/globber";
}
```

{% endhint %}

## Faking All Requests

Faking is enabled on a [`HyperBuilder`](/7.2.0-1/making-requests/hyperbuilder) instance, either the built-in one provided by Hyper or a [custom Hyper client](/7.2.0-1/customizing-hyper/custom-http-clients) you have created.

To enable faking requests, call the `fake` method:

```cfscript
var hyper = new Hyper.models.HyperBuilder();
hyper.fake();
```

After calling the `fake` method, all requests created by this `HyperBuilder` will be faked.  By default, they will return `200 OK` responses with empty bodies.

```cfscript
hyper.fake();
var res = hyper.get( "https://google.com" );
expect( res.getStatus() ).toBe( "200 OK" );
```

## Fake Configuration

When calling the `fake` method, you can provide a struct mapping URL patterns to response generator functions.

```cfscript
hyper.fake( {
    "https://google.com/*": function( newFakeResponse, req ) {
         return newFakeResponse( 404, "Not Found" );
    }
} );
```

The key is a URL pattern.  The pattern can be any valid glob. If the pattern is matched by the [`fullUrl`](/7.2.0-1/making-requests/hyperrequest#getfullurl) of the `HyperRequest`, then the response generator function will be called and the results returned.

A helper function, `newFakeResponse`, is provided as the first argument to the response generator function.  The current request is provided as the second argument.

## FakeHyperResponse

The resposne generator function must return a `FakeHyperResponse` instance.  A `FakeHyperResponse` instance acts similar to a normal `HyperResponse` except the properties are not read only.  Once you have an instance of your `FakeHyperResponse`, you can continue to set any properties you need.

```cfscript
hyper.fake( {
    "https://jsonplaceholder.typicode.com/posts": function( newFakeResponse, req ) {
         return newFakeResponse()
             .setStatusCode( 201 )
             .setStatusText( "Created" )
             .setData( serializeJSON( {
                 "id": 101,
                 "title": "foo",
                 "body": "bar",
                 "userId": 1
             } ) );
    }
} );
```

You can also pass the values to the `newFakeResponse` function, if you'd like.

```cfscript
hyper.fake( {
    "https://jsonplaceholder.typicode.com/posts": function( newFakeResponse, req ) {
         return newFakeResponse( 201, "Created", serializeJSON( {
             "id": 101,
             "title": "foo",
             "body": "bar",
             "userId": 1
         } ) );
    }
} );
```

### `newFakeResponse`

Creates a new `FakeHyperResponse` instance.

<table><thead><tr><th width="160">Name</th><th>Type</th><th>Required</th><th>Default</th><th>Description</th></tr></thead><tbody><tr><td>statusCode</td><td><code>numeric</code></td><td><code>false</code></td><td>200</td><td>The status code for the fake response.</td></tr><tr><td>statusText</td><td><code>string</code></td><td><code>false</code></td><td><code>"OK"</code></td><td>The status text for the fake response.</td></tr><tr><td>data</td><td><code>string</code></td><td><code>false</code></td><td><code>""</code></td><td>The data for the fake response.</td></tr><tr><td>headers</td><td><code>{ string: string }</code></td><td><code>false</code></td><td><code>{}</code></td><td>The headers for the fake response.</td></tr><tr><td>executionTime</td><td><code>numeric</code></td><td><code>false</code></td><td>0</td><td>The execution time for the fake response.</td></tr><tr><td>charset</td><td><code>string</code></td><td><code>false</code></td><td><code>"UTF-8"</code></td><td>The charset for the fake response.</td></tr><tr><td>timestamp</td><td><code>datetime</code></td><td><code>false</code></td><td><code>now()</code></td><td>The timestamp of the fake response.</td></tr></tbody></table>

**Return**: `FakeHyperResponse`

## Sequencing Fake Responses

In addition to returning a single `FakeHyperResponse` per pattern, you can return an array of `FakeHyperResponse` instances.  These will be returned in a sequence.

```cfscript
hyper.fake( {
    "https://jsonplaceholder.typicode.com/posts": function( newFakeResponse, req ) {
         return [
             newFakeResponse( 201, "Created", serializeJSON( {
                 "id": 101,
                 "title": "foo",
                 "body": "bar",
                 "userId": 1
             } ) ),
             newFakeResponse( 422, "Unprocessable Entity", "Duplicate title" )
         ];
    }
} );

var resA = hyper.post( "https://jsonplaceholder.typicode.com/posts", { /* ... */ } );
expect( resA.getStatus() ).toBe( "201 Created" );

var resB = hyper.post( "https://jsonplaceholder.typicode.com/posts", { /* ... */ } );
expect( resA.getStatus() ).toBe( "422 Unprocessable Entity" );
```

If you continue to make requests to the same pattern after the sequence has been exhausted, an exception will be thrown.

```cfscript
hyper.fake( {
    "https://jsonplaceholder.typicode.com/posts": function( newFakeResponse, req ) {
         return [
             newFakeResponse( 201, "Created", serializeJSON( {
                 "id": 101,
                 "title": "foo",
                 "body": "bar",
                 "userId": 1
             } ) ),
             newFakeResponse( 422, "Unprocessable Entity", "Duplicate title" )
         ];
    }
} );

var resA = hyper.post( "https://jsonplaceholder.typicode.com/posts", { /* ... */ } );
expect( resA.getStatus() ).toBe( "201 Created" );

var resB = hyper.post( "https://jsonplaceholder.typicode.com/posts", { /* ... */ } );
expect( resA.getStatus() ).toBe( "422 Unprocessable Entity" );

// THROWS a `HyperFakeSequenceExhausted` exception
var resC = hyper.post( "https://jsonplaceholder.typicode.com/posts", { /* ... */ } );
```

## Preventing Stray Requests

By default, Hyper returns a default `FakeHyperResponse` for every request that doesn't match one of your configured patterns.  You can instead cause Hyper to throw an exception if it encounters one of these stray requests by calling the `preventStrayRequests` method.

```cfscript
hyper.fake( {
    "https://google.com/*": function( newFakeResponse, req ) {
         return newFakeResponse( 404, "Not Found" );
    }
} ).preventStrayRequests();

// THROWS a `HyperFakeStrayRequest` exception
var res = hyper.get( "https://github.com" );
```

## Making Assertions

In addition to assertions made against the `FakeHyperResponse` instances returned, you can also make assertions using the `HyperBuilder` instance you faked.  These come in the form of methods on the `HyperBuilder` instance as well as custom TestBox Assertions.

### HyperBuilder Method Assertions

The following methods are available to make assertions in your tests about the requests that were sent.

#### getFakeRequestCount

Returns the number of fake requests that have been made.

| Name         | Type | Required | Default | Description |
| ------------ | ---- | -------- | ------- | ----------- |
| No arguments |      |          |         |             |

**Return**: `numeric`

#### wasRequestSent

Returns whether a request has been made that matches the `predicate`. Each request that has been made is passed to the `predicate` in order. If the `predicate` returns `true`, the request is considered a match and `true` is returned. If no request passes the `predicate`, `false` is returned.

| Name      | Type       | Required | Default | Description                                                                                            |
| --------- | ---------- | -------- | ------- | ------------------------------------------------------------------------------------------------------ |
| predicate | `function` | `true`   |         | A callback function that returns true if the request matches the criteria and returns false otherwise. |

**Return**: `boolean`

### Custom TestBox Assertions

You can register [custom TestBox assertions](https://testbox.ortusbooks.com/in-depth/expectations/custom-matchers) provided by Hyper for more readable tests and test failure messages.

You must [register](https://testbox.ortusbooks.com/in-depth/expectations/custom-matchers#cfc-matchers) these assertions before using them.

```cfscript
component extends="testbox.system.BaseSpec" {

    function beforeAll() {
        addMatchers( "hyper.models.TestBoxMatchers" )
    }
    
    function run() {
        // ...
    }

}
```

The following custom assertions are provided:

#### toHaveSentRequest

This takes in the `HyperBuilder` instance as the actual and a predicate function as the expected. The predicate function is passed to the `HyperBuilder` instance's `wasRequestSent` method.

```cfscript
hyper.fake();

hyper.get( "https://google.com" );

expect( hyper ).toHaveSentRequest( function( req ) {
    return req.getFullUrl( "https://google.com" );
} );

expect( hyper ).notToHaveSentRequest( function( req ) {
    return req.getFullUrl( "https://github.com" );
} );
```

#### toHaveSentCount

This takes in the `HyperBuilder` instance as the actual and an integer number of requests that should have been sent.

```cfscript
hyper.fake();

hyper.get( "https://google.com" );

expect( hyper ).toHaveSentCount( 1 );
expect( hyper ).notToHaveSentCount( 2 );
```

#### toHaveSentNothing

This takes in the `HyperBuilder` instance as the actual and no other parameters.

```cfscript
hyper.fake();

expect( hyper ).toHaveSentNothing();

hyper.get( "https://google.com" );

expect( hyper ).notToHaveSentNothing();
```

## Resetting the Builder

To reset the `HyperBuilder` instance to normal operation call the `clearFakes` method:

```cfscript
hyper.fake();

hyper.get( "https://google.com" );

hyper.clearFakes();
```

{% hint style="info" %}
This is a useful method to call in an [`afterEach`](https://testbox.ortusbooks.com/in-depth/life-cycle-methods/bdd#aftereach-body-data) block in TestBox to make sure you are only faking requests when you want to.
{% endhint %}


# Introduction

## A CFML HTTP Builder

### Inspiration

Hyper was built after coding several API SDK's for various platforms — [S3SDK](https://github.com/coldbox-modules/s3sdk), [cbstripe](https://github.com/coldbox-modules/cbox-stripe), and [cbgithub](https://github.com/elpete/cbgithub), to name a few. We noticed that we spent a lot of time setting up the plumbing for the requests and a wrapper around `cfhttp`. Each implementation was mostly the same but slightly different. It was additionally frustrating because we really only needed to tweak a few values, usually just the `Authorization` header. It would be nice to create an HTTP client pre-configured for each of these SDK's. It seemed the perfect fit for a module.

### The problem it solves

Hyper exists to provide a fluent builder experience for HTTP requests and responses. It also provides a powerful way to create clients, i.e. Builder objects with pre-configured defaults like a base URL or certain headers.


# What's New?

## 7.3.0

### Retrying Failed Requests

You can now configure a `HyperRequest` to automatically retry failed requests.  [See the `HyperRequest` docs for details.](/7.3.0-1/making-requests/hyperrequest#retry)

### Default User-Agent

Hyper now sends a default User-Agent of `HyperCFML/#versionNumber#`.

### Reset Fake Request Counts and Sequences

Hyper can now reset the fake request counts and sequences without losing the fake configuration using the [`resetFakes`](/7.3.0-1/testing/faking-requests#resetting-the-builder) method.

## 7.2.0

### Cookies

Hyper can now [send cookies with a request](/7.3.0-1/making-requests/hyperrequest#withcookies) and [parse the returned cookies from a response](/7.3.0-1/making-requests/hyperresponse#getcookies). See the [HyperRequest](/7.3.0-1/making-requests/hyperrequest) and [HyperResponse](/7.3.0-1/making-requests/hyperresponse) docs for details.

## 7.1.0

### Fake Requests

Hyper now has the ability to fake requests and return fake responses as a result.  This is perfect for testing scenarios where you don't actually want to make an HTTP request.

{% content-ref url="/pages/fDs68ouvcjilusPgzOdw" %}
[Faking Requests](/7.3.0-1/testing/faking-requests)
{% endcontent-ref %}

### Custom Hyper Clients

It is now more straightforward to register a [custom Hyper client](/7.3.0-1/customizing-hyper/custom-http-clients).  Inside your `config/WireBox.cfc` in an `afterAspectsLoad` method, you can get a reference to a `HyperBuilder`, configure it as you would for a request, and then call the `registerAs` method passing in your desired WireBox alias.

```cfscript
// config/WireBox.cfc
component {

   // ...
   
   function afterApsectsLoad() {
       injector.getInstance( "HyperBuilder@hyper" )
           .setBaseUrl( "https://api.github.com" )
           .asJson()
           .withHeaders( {
               "Authorization": coldbox.getUtil().getSystemSetting( "GITHUB_TOKEN" )
           } )
           .registerAs( "GitHubClient" );
   }

}
```

This is a welcome improvement as the `init` arguments do not exactly match the method names.  Also, for defaults like `requestCallbacks`, `responseCallbacks`, or even `queryParams`, passing in arrays of functions or arrays or structs is not as straightforward as calling the related methods.  Now, you can use the Hyper methods you are familiar with when registering your custom Hyper clients.

{% hint style="info" %}
Putting the registration code in `afterAspectsLoad` is required so Hyper can be loaded and available for injection.
{% endhint %}

## 7.0.0

### CFHttp HTTP Client

This client now returns more accurate status codes for `502 Bad Gateway` and `408 Request Timeout` responses.

Previously, these responses were returned as `504 Gateway Timeout` responses. Hyper now normalizes the responses from the different CFML engines into a consistent response. `502 Bad Gateway` is returned instead of `504 Gateway Timeout` for invalid hosts. `408 Request Timeout` is returned if the request takes longer than the configured [`timeout`](/7.3.0-1/making-requests/hyperrequest#settimeout) value.

### Breaking Changes

If you were previously checking specifically for `504` status codes for bad hosts, you need to now either check for `502` status codes or use a more general method, like [`isServerError`](/7.3.0-1/making-requests/hyperresponse#isservererror) or [`isError`](/7.3.0-1/making-requests/hyperresponse#iserror).

If you were previously checking specifically for `504` status codes or [`isServerError`](/7.3.0-1/making-requests/hyperresponse#isservererror) for timed out requests, you need to now either check for `408` status codes, [`isClientError`](/7.3.0-1/making-requests/hyperresponse#isclienterror), or the more general [`isError`](/7.3.0-1/making-requests/hyperresponse#iserror).

## 6.1.0

Add [`head`](/7.3.0-1/making-requests/hyperrequest#head) and [`options`](/7.3.0-1/making-requests/hyperrequest#options) shortcut methods.

## 6.0.0

* Add `xml` support and an `asXML` method to set the body format and `Content-Type` header.
* Add `adobe@2023` to testing matrix.

### Breaking Changes

* Remove default `Content-Type` header. You must set this [manually](/7.3.0-1/making-requests/hyperrequest#setcontenttype) or use a format helper, such as [`asJson`](/7.3.0-1/making-requests/hyperrequest#asjson).
* Dropped `adobe@2016` support.

## 5.0.1

Correctly handle cases when the `body` is a string and format is `JSON`.

## 5.0.0

Add a `debug` method to see what the HTTP client generates.

### Breaking Changes

`HyperHttpClientInterface` now requires a `debug` method.

```cfscript
/**
 * Return a struct of information showing how the client will execute the HyperRequest.
 * This will be used by a developer to debug any differences between the generated
 * request values and the expected request values.
 *
 * @req     The HyperRequest to debug.
 *
 * @returns A struct of information detailing how the client would execute the HyperRequest.
 */
public struct function debug( required HyperRequest req );
```

## 4.0.3

* Do not prepend the base url when a full url is passed.
* Add `resolveUrls` and `encodeUrl` properties to the [memento](/7.3.0-1/making-requests/hyperrequest#getmemento).
* Correctly set the `encodeUrl` property when cloning a request.

## 4.0.2

Update README for builder `initWith` headers losing `Content-Type`.

## 4.0.1

Fix `HyperBuilder` example in the docs.

## 4.0.0

Allow adding multiple query params with the same key.

### Breaking Changes

Previously, query params were stored as a struct.  Some APIs expect multiple values for the same query param name to be passed as separate arguments.  Hyper now stores the query params as an array and provides new methods for interacting with query params:

* [`getQueryParamByName`](/7.3.0-1/making-requests/hyperrequest#getqueryparambyname)
* [`getAllQueryParamsByName`](/7.3.0-1/making-requests/hyperrequest#getallqueryparamsbyname)
* [`withQueryParams`](/7.3.0-1/making-requests/hyperrequest#withqueryparams)
* [`appendQueryParam`](/7.3.0-1/making-requests/hyperrequest#appendqueryparam)
* [`appendQueryParams`](/7.3.0-1/making-requests/hyperrequest#appendqueryparams)
* [`hasQueryParam`](/7.3.0-1/making-requests/hyperrequest#hasqueryparam)

The following methods still exist, but now interact with arrays of query param structs instead of a simple struct.

* [`getQueryParams`](/7.3.0-1/making-requests/hyperrequest#getqueryparams)
* [`setQueryParams`](/7.3.0-1/making-requests/hyperrequest#setqueryparams)

The following methods have been deprecated:

| Deprecated Method                                                      | Replacement Method                                                                 |
| ---------------------------------------------------------------------- | ---------------------------------------------------------------------------------- |
| [`getQueryParam`](/7.3.0-1/making-requests/hyperrequest#getqueryparam) | [`getQueryParamByName`](/7.3.0-1/making-requests/hyperrequest#getqueryparambyname) |

## 3.6.2

Convert array values correctly when sending form fields

## 3.6.1

Add a workaround for CommandBox not having the `box:asyncManager` injection DSL.

## 3.6.0

Add async requests using ColdBox's [AsyncManager](https://coldbox.ortusbooks.com/digging-deeper/promises-async-programming).

## 3.5.0

* Provide more useful error than cfhttp when [`throwOnErrors`](/7.3.0-1/making-requests/hyperrequest#throwerrors) is enabled.
* Provide mementos for [HyperRequest](/7.3.0-1/making-requests/hyperrequest#getmemento) and [HyperResponse](/7.3.0-1/making-requests/hyperresponse#getmemento) instances.
* Capture [statusText](/7.3.0-1/making-requests/hyperresponse#getstatustext) and provide a [status](/7.3.0-1/making-requests/hyperresponse#getstatus) convenience string.

## 3.4.2

Add MIT License file

## 3.4.1

Use `processState` over `announce` until CommandBox can update its `interceptorService`.

## 3.4.0

### HyperRequest

* Add [`forwardHeaders`](/7.3.0-1/making-requests/hyperrequest#forwardheaders) shortcut method.

### HyperResponse

* Allow for default values in [`getHeader`](/7.3.0-1/making-requests/hyperresponse#getheader).
* Add helper methods for checking for specific status codes:
  * [`isOk`](/7.3.0-1/making-requests/hyperresponse#isok)
  * [`isUnauthorized`](/7.3.0-1/making-requests/hyperresponse#isunauthorized)
  * [`isForbidden`](/7.3.0-1/making-requests/hyperresponse#isforbidden)
  * [`isNotFound`](/7.3.0-1/making-requests/hyperresponse#isnotfound)

## 3.3.0

Allowing [attaching](/7.3.0-1/making-requests/hyperrequest#attach) file uploads.

## 3.2.1

Support WireBox outside of ColdBox.

## 3.2.0

Include response data as detail in `DeserializeJsonException`.

## 3.1.0

* Add [`clone`](/7.3.0-1/making-requests/hyperrequest#clone) to quickly copy `HyperRequest` instances.
* Add interceptors and [local](/7.3.0-1/making-requests/hyperrequest#withrequestcallback) [callbacks](/7.3.0-1/making-requests/hyperrequest#withresponsecallback) for lifecycle events.

## 3.0.0

Add execution time to `HyperResponse` instances.

### Breaking Changes

Dropped support for ColdBox 5.

## 2.3.11

* Add support for [NTLM authentication](/7.3.0-1/making-requests/hyperrequest#withntlmauth).
* Include [`getFullURL`](/7.3.0-1/making-requests/hyperrequest#getfullurl) method in docs.

## 2.3.10

Fixed typo of `Bulider` to `Builder`.

## 2.3.9

Add [`withoutEncodingUrl`](/7.3.0-1/making-requests/hyperrequest#withoutencodingurl) flag.

## 2.3.8

Do not fail fast on cron job actions on CI.

## 2.3.7

Update fetch-depth for tests and release actions on CI.

## 2.3.6

Attempt to skip committing back changes on CI.

## 2.3.5

Add matrix and cron testing on CI.

## 2.3.4

Use better GitHub token on CI

## 2.3.1

Add workaround for `boolean` values in query strings.

## 2.3.0

Add [certificate](/7.3.0-1/making-requests/hyperrequest#withcertificateauth) auth.

## 2.2.1

Use the previous host for redirect if redirect does not include a full URL.

## 2.2.0

Add [`resolveUrls`](/7.3.0-1/making-requests/hyperrequest#setresolveurl) flag.

## 2.1.1

* Use OpenJDK instead of OracleJDK on CI.
* Store module in [ForgeBox Storage](https://commandbox.ortusbooks.com/5.6.0/developing-for-commandbox/commands).

## 2.1.0

Allow for pluggable [HTTP Clients](/7.3.0-1/customizing-hyper/custom-http-clients) that follow the `HyperHttpClientInterface`. (Clients do not need to use the `implements` keyword.)

## 2.0.2

Avoid double encoding using [`cfhttpparam`](https://cfdocs.org/cfhttpparam).

## 2.0.1

Remove Lucee 4.5 support from docs. (Support was dropped in [v2.0.0](#2.0.0))

## 2.0.0

* Do not include [`username`](/7.3.0-1/making-requests/hyperrequest#setusername) and [`password`](/7.3.0-1/making-requests/hyperrequest#setpassword) unless they have values.
* Add `adobe@2018` support to CI builds.

### Breaking Changes

Dropped support for `lucee@4.5`.

## 1.15.0

Add [`throwOnError`](/7.3.0-1/making-requests/hyperrequest#throwerrors) flag.

## 1.14.5

Use `504 Gateway Timeout` for incomplete responses.

## 1.14.4

Include equal signs in query param values.

## 1.14.0 – 1.0.0

### New Features

* Add [`when`](/7.3.0-1/making-requests/hyperrequest#when) helper to execute conditions without breaking chaining.
* Add [`clear`](/7.3.0-1/making-requests/hyperrequest#clear) method to reset HyperRequest instances.
* Add configurable [`timeout`](/7.3.0-1/making-requests/hyperrequest#settimeout).

### Bug Fixes

* Fix for Lucee 4 compatibility on `LinkedHashMaps` and `keyArray`.
* Preserve case in header names.
* Preserve case for query parameters.
* Serialize both params from the url and set on the `HyperRequest` instance.
* Default to `UTF-8` charset if none is present in the response.
* Fix withHeaders and withQueryParams for Lucee compatibility.
* Only map HyperBuilder as a singleton in WireBox

### Other

* Migrate to [coldbox-modules](https://github.com/coldbox-modules) organization on GitHub.
* Update `box.json` description.
* Enable [CommandBox Semantic Release](https://forgebox.io/view/commandbox-semantic-release) on CI.


# Upgrade Guide

## Upgrading from v6 to v7

### CFHttp HTTP Client

This client now returns more accurate status codes for `502 Bad Gateway` and `408 Request Timeout` responses.

If you were previously checking specifically for `504` status codes for bad hosts, you need to now either check for `502` status codes or use a more general method, like [`isServerError`](/7.3.0-1/making-requests/hyperresponse#isservererror) or [`isError`](/7.3.0-1/making-requests/hyperresponse#iserror).

If you were previously checking specifically for `504` status codes or [`isServerError`](/7.3.0-1/making-requests/hyperresponse#isservererror) for timed out requests, you need to now either check for `408` status codes, [`isClientError`](/7.3.0-1/making-requests/hyperresponse#isclienterror), or the more general [`isError`](/7.3.0-1/making-requests/hyperresponse#iserror).

## Upgrading from v5 to v6

* The default `Content-Type` header has been removed. You must set this [manually](/7.3.0-1/making-requests/hyperrequest#setcontenttype) or use a format helper, such as [`asJson`](/7.3.0-1/making-requests/hyperrequest#asjson).
* Dropped support for Adobe 2016.

## Upgrading from v4 to v5

`HyperHttpClientInterface` now requires a `debug` method.

```cfscript
/**
 * Return a struct of information showing how the client will execute the HyperRequest.
 * This will be used by a developer to debug any differences between the generated
 * request values and the expected request values.
 *
 * @req     The HyperRequest to debug.
 *
 * @returns A struct of information detailing how the client would execute the HyperRequest.
 */
public struct function debug( required HyperRequest req );
```

## Upgrading from v3 to v4

Previously, query params were stored as a struct.  Some APIs expect multiple values for the same query param name to be passed as separate arguments.  Hyper now stores the query params as an array and provides new methods for interacting with query params:

* [`getQueryParamByName`](/7.3.0-1/making-requests/hyperrequest#getqueryparambyname)
* [`getAllQueryParamsByName`](/7.3.0-1/making-requests/hyperrequest#getallqueryparamsbyname)
* [`withQueryParams`](/7.3.0-1/making-requests/hyperrequest#withqueryparams)
* [`appendQueryParam`](/7.3.0-1/making-requests/hyperrequest#appendqueryparam)
* [`appendQueryParams`](/7.3.0-1/making-requests/hyperrequest#appendqueryparams)
* [`hasQueryParam`](/7.3.0-1/making-requests/hyperrequest#hasqueryparam)

The following methods still exist, but now interact with arrays of query param structs instead of a simple struct.

* [`getQueryParams`](/7.3.0-1/making-requests/hyperrequest#getqueryparams)
* [`setQueryParams`](/7.3.0-1/making-requests/hyperrequest#setqueryparams)

The following methods have been deprecated:

| Deprecated Method                                                      | Replacement Method                                                                 |
| ---------------------------------------------------------------------- | ---------------------------------------------------------------------------------- |
| [`getQueryParam`](/7.3.0-1/making-requests/hyperrequest#getqueryparam) | [`getQueryParamByName`](/7.3.0-1/making-requests/hyperrequest#getqueryparambyname) |

## Upgrading from v2 to v3

Dropped support for ColdBox 5.

## Upgrading from v1 to v2

Dropped support for Lucee 4.5.


# Requirements

Hyper runs on Adobe ColdFusion 2018+ and Lucee 5+.

ColdBox is not required, but mappings are provided for ColdBox users automatically.


# Installation

Hyper is most easily installed via ForgeBox and CommandBox.

```sh
box install hyper
```

If you install Hyper in a non-ColdBox application, make sure to create a mapping in your `Application.cfc`

```cfscript
this.mappings[ "/hyper" ] = expandPath( "/modules/hyper" );
```


# HyperBuilder

A `HyperBuilder` is a singleton factory component that will give you a new [`HyperRequest`](/7.3.0-1/making-requests/hyperrequest) any time you call the `new` method.  It will also create a new [`HyperRequest`](/7.3.0-1/making-requests/hyperrequest) any time you call a method on `HyperBuilder` that exists on [`HyperRequest`](/7.3.0-1/making-requests/hyperrequest).

`HyperBuilder` is the component you want to inject into your singleton components, like handlers or services.  It will ensure you get a fresh [`HyperRequest`](/7.3.0-1/making-requests/hyperrequest) instance on each invocation.  This is important since reusing the same [`HyperRequest`](/7.3.0-1/making-requests/hyperrequest) instance will likely produce unintended results.

You can inject a `HyperBuilder` into your application using the `HyperBuilder@hyper` id.

```cfscript
component {
    
    property name="hyper" inject="HyperBuilder@hyper";

    function index( event, rc, prc ) {
        var reqA = hyper.new();
        // reqA is a new HyperRequest instance.
        
        var reqB = hyper.setUrl( "https://swapi.dev/api/people" );
        // reqB is a new HyperRequest instance with the url set.
    }

}
```

If you are not using ColdBox, you can create a `HyperBuilder` manually:

```cfscript
component {

    function init() {
        variables.hyper = new hyper.models.HyperBuilder();
    }

}
```

Additionally, you can register `HyperBuilder` instances as custom HTTP Clients.

{% content-ref url="/pages/sc1pmftTrug5lkmdOWQS" %}
[Custom HTTP Clients](/7.3.0-1/customizing-hyper/custom-http-clients)
{% endcontent-ref %}

Finally, you can enable faking of requests from any `HyperBuilder` instance.

{% content-ref url="/pages/fDs68ouvcjilusPgzOdw" %}
[Faking Requests](/7.3.0-1/testing/faking-requests)
{% endcontent-ref %}


# HyperRequest

Though the [`HyperBuilder`](/7.3.0-1/making-requests/hyperbuilder) is the component you will most likely inject, `HyperRequest` is the component will you interact with the most. `HyperRequest` provides a fluent interface to configure your HTTP call.

```cfscript
hyper.get( "https//api.github.com/users" );

hyper.setMethod( "PUT" )
    .withHeaders( { "Authorization" = "Bearer #token#" } )
    .setUrl( "https://jsonplaceholder.typicode.com/posts/1" )
    .setBody( {
        title: "New Title"
    } )
    .send();
```

## Defaults

The following are default properties for a `HyperRequest`:

```json
{
    "method": "GET"
    "resolveUrls": false,
    "encodeUrl": true,
    "timeout": 10, // in seconds
    "maximumRedirects": "*", // follow redirects indefinitely
    "bodyFormat": "json",
    "throwOnError": false,
    "headers": { "User-Agent": "HyperCFML/#versionNumber#" }
}
```

## Executing Requests

### `get`

Execute a `GET` request and return a [`HyperResponse`](/7.3.0-1/making-requests/hyperresponse).

| Name        | Type   | Required | Default | Description                                                    |
| ----------- | ------ | -------- | ------- | -------------------------------------------------------------- |
| url         | string | false    | null    | An optional URL to set for the request.                        |
| queryParams | struct | false    | null    | An optional struct of query parameters to set for the request. |

**Return**: [`HyperResponse`](/7.3.0-1/making-requests/hyperresponse)

### `getAsync`

Execute a `GET` request asynchronously. Returns a [ColdBox Future](https://coldbox.ortusbooks.com/digging-deeper/promises-async-programming) that returns a [`HyperResponse`](/7.3.0-1/making-requests/hyperresponse).

<table><thead><tr><th width="40">Name</th><th>Type</th><th>Required</th><th>Default</th><th>Description</th></tr></thead><tbody><tr><td>url</td><td>string</td><td>false</td><td>null</td><td>An optional URL to set for the request.</td></tr><tr><td>queryParams</td><td>struct</td><td>false</td><td>null</td><td>An optional struct of query parameters to set for the request.</td></tr></tbody></table>

**Return**: [`Future`](https://coldbox.ortusbooks.com/digging-deeper/promises-async-programming)`<`[`HyperResponse`](/7.3.0-1/making-requests/hyperresponse)`>`

### `post`

Execute a `POST` request and return a [`HyperResponse`](/7.3.0-1/making-requests/hyperresponse).

| Name | Type   | Required | Default | Description                              |
| ---- | ------ | -------- | ------- | ---------------------------------------- |
| url  | string | false    | null    | An optional URL to set for the request.  |
| body | struct | false    | null    | An optional body to set for the request. |

**Return**: [`HyperResponse`](/7.3.0-1/making-requests/hyperresponse)

### `postAsync`

Execute a `POST` request asynchronously. Returns a [ColdBox Future](https://coldbox.ortusbooks.com/digging-deeper/promises-async-programming) that returns a [`HyperResponse`](/7.3.0-1/making-requests/hyperresponse).

| Name | Type   | Required | Default | Description                              |
| ---- | ------ | -------- | ------- | ---------------------------------------- |
| url  | string | false    | null    | An optional URL to set for the request.  |
| body | struct | false    | null    | An optional body to set for the request. |

**Return**: [`Future`](https://coldbox.ortusbooks.com/digging-deeper/promises-async-programming)`<`[`HyperResponse`](/7.3.0-1/making-requests/hyperresponse)`>`

### `put`

Execute a `PUT` request and return a [`HyperResponse`](/7.3.0-1/making-requests/hyperresponse).

| Name | Type   | Required | Default | Description                              |
| ---- | ------ | -------- | ------- | ---------------------------------------- |
| url  | string | false    | null    | An optional URL to set for the request.  |
| body | struct | false    | null    | An optional body to set for the request. |

**Return**: [`HyperResponse`](/7.3.0-1/making-requests/hyperresponse)

### `putAsync`

Execute a `PUT` request asynchronously. Returns a [ColdBox Future](https://coldbox.ortusbooks.com/digging-deeper/promises-async-programming) that returns a [`HyperResponse`](/7.3.0-1/making-requests/hyperresponse).

| Name | Type   | Required | Default | Description                              |
| ---- | ------ | -------- | ------- | ---------------------------------------- |
| url  | string | false    | null    | An optional URL to set for the request.  |
| body | struct | false    | null    | An optional body to set for the request. |

**Return**: [`Future`](https://coldbox.ortusbooks.com/digging-deeper/promises-async-programming)`<`[`HyperResponse`](/7.3.0-1/making-requests/hyperresponse)`>`

### `patch`

Execute a `PATCH` request and return a [`HyperResponse`](/7.3.0-1/making-requests/hyperresponse).

| Name | Type   | Required | Default | Description                              |
| ---- | ------ | -------- | ------- | ---------------------------------------- |
| url  | string | false    | null    | An optional URL to set for the request.  |
| body | struct | false    | null    | An optional body to set for the request. |

**Return**: [`HyperResponse`](/7.3.0-1/making-requests/hyperresponse)

### `patchAsync`

Execute a `PATCH` request asynchronously. Returns a [ColdBox Future](https://coldbox.ortusbooks.com/digging-deeper/promises-async-programming) that returns a [`HyperResponse`](/7.3.0-1/making-requests/hyperresponse).

| Name | Type   | Required | Default | Description                              |
| ---- | ------ | -------- | ------- | ---------------------------------------- |
| url  | string | false    | null    | An optional URL to set for the request.  |
| body | struct | false    | null    | An optional body to set for the request. |

**Return**: [`Future`](https://coldbox.ortusbooks.com/digging-deeper/promises-async-programming)`<`[`HyperResponse`](/7.3.0-1/making-requests/hyperresponse)`>`

### `delete`

Execute a `DELETE` request and return a [`HyperResponse`](/7.3.0-1/making-requests/hyperresponse).

| Name | Type   | Required | Default | Description                              |
| ---- | ------ | -------- | ------- | ---------------------------------------- |
| url  | string | false    | null    | An optional URL to set for the request.  |
| body | struct | false    | null    | An optional body to set for the request. |

**Return**: [`HyperResponse`](/7.3.0-1/making-requests/hyperresponse)

### `deleteAsync`

Execute a `DELETE` request asynchronously. Returns a [ColdBox Future](https://coldbox.ortusbooks.com/digging-deeper/promises-async-programming) that returns a [`HyperResponse`](/7.3.0-1/making-requests/hyperresponse).

| Name | Type   | Required | Default | Description                              |
| ---- | ------ | -------- | ------- | ---------------------------------------- |
| url  | string | false    | null    | An optional URL to set for the request.  |
| body | struct | false    | null    | An optional body to set for the request. |

**Return**: [`Future`](https://coldbox.ortusbooks.com/digging-deeper/promises-async-programming)`<`[`HyperResponse`](/7.3.0-1/making-requests/hyperresponse)`>`

### `head`

Execute a `HEAD` request and return a [`HyperResponse`](/7.3.0-1/making-requests/hyperresponse).

| Name        | Type   | Required | Default | Description                                                    |
| ----------- | ------ | -------- | ------- | -------------------------------------------------------------- |
| url         | string | false    | null    | An optional URL to set for the request.                        |
| queryParams | struct | false    | null    | An optional struct of query parameters to set for the request. |

**Return**: [`HyperResponse`](/7.3.0-1/making-requests/hyperresponse)

### `headAsync`

Execute a `HEAD` request asynchronously. Returns a [ColdBox Future](https://coldbox.ortusbooks.com/digging-deeper/promises-async-programming) that returns a [`HyperResponse`](/7.3.0-1/making-requests/hyperresponse).

| Name        | Type   | Required | Default | Description                                                    |
| ----------- | ------ | -------- | ------- | -------------------------------------------------------------- |
| url         | string | false    | null    | An optional URL to set for the request.                        |
| queryParams | struct | false    | null    | An optional struct of query parameters to set for the request. |

**Return**: [`Future`](https://coldbox.ortusbooks.com/digging-deeper/promises-async-programming)`<`[`HyperResponse`](/7.3.0-1/making-requests/hyperresponse)`>`

### `options`

Execute an `OPTIONS` request and return a [`HyperResponse`](/7.3.0-1/making-requests/hyperresponse).

| Name        | Type   | Required | Default | Description                                                    |
| ----------- | ------ | -------- | ------- | -------------------------------------------------------------- |
| url         | string | false    | null    | An optional URL to set for the request.                        |
| queryParams | struct | false    | null    | An optional struct of query parameters to set for the request. |

**Return**: [`HyperResponse`](/7.3.0-1/making-requests/hyperresponse)

### `optionsAsync`

Execute an `OPTIONS` request asynchronously. Returns a [ColdBox Future](https://coldbox.ortusbooks.com/digging-deeper/promises-async-programming) that returns a [`HyperResponse`](/7.3.0-1/making-requests/hyperresponse).

| Name        | Type   | Required | Default | Description                                                    |
| ----------- | ------ | -------- | ------- | -------------------------------------------------------------- |
| url         | string | false    | null    | An optional URL to set for the request.                        |
| queryParams | struct | false    | null    | An optional struct of query parameters to set for the request. |

**Return**: [`Future`](https://coldbox.ortusbooks.com/digging-deeper/promises-async-programming)`<`[`HyperResponse`](/7.3.0-1/making-requests/hyperresponse)`>`

### `send`

Send the HTTP request and return a [`HyperResponse`](/7.3.0-1/making-requests/hyperresponse).

| Name         | Type | Required | Default | Description |
| ------------ | ---- | -------- | ------- | ----------- |
| No arguments |      |          |         |             |

**Return**: [`HyperResponse`](/7.3.0-1/making-requests/hyperresponse)

### `sendAsync`

Send the HTTP request asynchronously and return a [ColdBox Future](https://coldbox.ortusbooks.com/digging-deeper/promises-async-programming) that will resolve to a [`HyperResponse`](/7.3.0-1/making-requests/hyperresponse).

| Name         | Type | Required | Default | Description |
| ------------ | ---- | -------- | ------- | ----------- |
| No arguments |      |          |         |             |

**Return**: [`Future`](https://coldbox.ortusbooks.com/digging-deeper/promises-async-programming)`<`[`HyperResponse`](/7.3.0-1/making-requests/hyperresponse)`>`

## Building Requests

### `getRequestId`

Gets the unique request ID representing this request.

| Name         | Type | Required | Default | Description |
| ------------ | ---- | -------- | ------- | ----------- |
| No arguments |      |          |         |             |

**Return**: `String`

### `getFullURL`

Gets the full URL for the request.

| Name            | Type    | Required | Default | Description                                            |
| --------------- | ------- | -------- | ------- | ------------------------------------------------------ |
| withQueryString | boolean | false    | false   | Includes the configured query string with the full URL |

**Return**: `String`

### `getBaseURL`

Gets the base URL for the request. The base URL is combined with the URL when making the request.

| Name         | Type | Required | Default | Description |
| ------------ | ---- | -------- | ------- | ----------- |
| No arguments |      |          |         |             |

**Return**: `String`

### `setBaseURL`

Sets the base URL for the request. The base URL is combined with the URL when making the request.

| Name  | Type   | Required | Default | Description                                                   |
| ----- | ------ | -------- | ------- | ------------------------------------------------------------- |
| value | string | true     |         | The base URL for the request, e.g. `https://api.github.com/`. |

**Return**: `HyperRequest`

### `getURL`

Gets the URL for the request.

| Name         | Type | Required | Default | Description |
| ------------ | ---- | -------- | ------- | ----------- |
| No arguments |      |          |         |             |

**Return**: `String`

### `setURL`

Sets the URL for the request.

| Name  | Type   | Required | Default | Description                                                                                                     |
| ----- | ------ | -------- | ------- | --------------------------------------------------------------------------------------------------------------- |
| value | string | true     |         | The URL for the request. It can either be a full url or a URI resource for use with the baseURL. e.g. `/repos`. |

**Return**: `HyperRequest`

### `setResolveURL`

Sets the resolveURL parameter for the request.

| Name  | Type    | Required | Default | Description                                                                    |
| ----- | ------- | -------- | ------- | ------------------------------------------------------------------------------ |
| value | boolean | false    | false   | Resolves URLs in the response body to absolute URLs, including the port number |

**Return**: `HyperRequest`

### `getMethod`

Gets the HTTP method for the request.

| Name         | Type | Required | Default | Description |
| ------------ | ---- | -------- | ------- | ----------- |
| No arguments |      |          |         |             |

**Return**: `String`

### `setMethod`

Sets the HTTP method for the request.

| Name  | Type   | Required | Default | Description                      |
| ----- | ------ | -------- | ------- | -------------------------------- |
| value | string | true     |         | The HTTP method for the request. |

**Return**: `HyperRequest`

### `withBasicAuth`

Sets the username and password for HTTP Basic Auth.

| Name     | Type   | Required | Default | Description                      |
| -------- | ------ | -------- | ------- | -------------------------------- |
| username | string | true     |         | The username for the basic auth. |
| password | string | true     |         | The password for the basic auth. |

**Return**: `HyperRequest`

### `withCertificateAuth`

Sets the username and password for HTTP Basic Auth.

| Name            | Type   | Required | Default | Description                                              |
| --------------- | ------ | -------- | ------- | -------------------------------------------------------- |
| certificatePath | string | true     |         | The mapped path to the certificate used to authenticate. |
| password        | string | false    |         | The optional password used to decrypt the certificate.   |

**Return**: `HyperRequest`

### `withNTLMAuth`

Sets the username, password, domain and workstation for NTLM Auth.

| Name        | Type   | Required | Default | Description                        |
| ----------- | ------ | -------- | ------- | ---------------------------------- |
| username    | string | true     |         | The username for the NTLM auth.    |
| password    | string | true     |         | The password for the NTLM auth.    |
| domain      | string | true     |         | The domain for the NTLM auth.      |
| workstation | string | true     |         | The workstation for the NTLM auth. |

Workstation can be obtained with `createObject('java','java.net.InetAddress').getLocalHost().getHostName()`

**Return**: `HyperRequest`

### `withRequestCallback`

Schedules a callback to be ran when executing the request.

| Name     | Type     | Required | Default | Description                                     |
| -------- | -------- | -------- | ------- | ----------------------------------------------- |
| callback | function | true     |         | The callback to run when executing the request. |

**Return**: `HyperRequest`

### `withResponseCallback`

Schedules a callback to be ran when receiving the response.

| Name     | Type     | Required | Default | Description                                      |
| -------- | -------- | -------- | ------- | ------------------------------------------------ |
| callback | function | true     |         | The callback to run when receiving the response. |

**Return**: `HyperRequest`

### `getUsername`

Gets the username for the request.

| Name         | Type | Required | Default | Description |
| ------------ | ---- | -------- | ------- | ----------- |
| No arguments |      |          |         |             |

**Return**: `String`

### `setUsername`

Sets the username for the request.

| Name  | Type   | Required | Default | Description                   |
| ----- | ------ | -------- | ------- | ----------------------------- |
| value | string | true     |         | The username for the request. |

**Return**: `HyperRequest`

### `getPassword`

Gets the password for the request.

| Name         | Type | Required | Default | Description |
| ------------ | ---- | -------- | ------- | ----------- |
| No arguments |      |          |         |             |

**Return**: `String`

### `setPassword`

Sets the password for the request.

| Name  | Type   | Required | Default | Description                   |
| ----- | ------ | -------- | ------- | ----------------------------- |
| value | string | true     |         | The password for the request. |

**Return**: `HyperRequest`

### `getTimeout`

Gets the timeout for the request, in seconds.

| Name         | Type | Required | Default | Description |
| ------------ | ---- | -------- | ------- | ----------- |
| No arguments |      |          |         |             |

**Return**: `numeric`

### `setTimeout`

Sets the timeout for the request, in seconds.

| Name  | Type   | Required | Default | Description                              |
| ----- | ------ | -------- | ------- | ---------------------------------------- |
| value | string | true     |         | The timeout for the request, in seconds. |

**Return**: `HyperRequest`

### `withoutRedirecting`

A convenience method to not follow any redirects.

| Name         | Type | Required | Default | Description |
| ------------ | ---- | -------- | ------- | ----------- |
| No arguments |      |          |         |             |

**Return**: `HyperRequest`

### `withoutEncodingUrl`

A convenience method to not encode the url.

{% hint style="warning" %}
**WARNING**: Not supported on Adobe engines.
{% endhint %}

| Name         | Type | Required | Default | Description |
| ------------ | ---- | -------- | ------- | ----------- |
| No arguments |      |          |         |             |

**Return**: `HyperRequest`

### `getMaximumRedirects`

Gets the maximum number of redirects to follow.

| Name         | Type | Required | Default | Description |
| ------------ | ---- | -------- | ------- | ----------- |
| No arguments |      |          |         |             |

**Return**: `numeric | String`

### `setMaximumRedirects`

Sets the maximum number of redirects to follow. A value of `*` will follow redirects infinitely.

| Name  | Type | Required | Default | Description                                |
| ----- | ---- | -------- | ------- | ------------------------------------------ |
| value | any  | true     |         | The maximum number of redirects to follow. |

**Return**: `HyperRequest`

### `getBody`

Gets the body for the request.

| Name         | Type | Required | Default | Description |
| ------------ | ---- | -------- | ------- | ----------- |
| No arguments |      |          |         |             |

**Return**: `any`

### `setBody`

Sets the body for the request. Complex values will be serialized before sending the request.

| Name  | Type | Required | Default | Description               |
| ----- | ---- | -------- | ------- | ------------------------- |
| value | any  | true     |         | The body for the request. |

**Return**: `HyperRequest`

### `hasBody`

Checks if the request has a body.

| Name         | Type | Required | Default | Description |
| ------------ | ---- | -------- | ------- | ----------- |
| No arguments |      |          |         |             |

**Return**: `boolean`

### `getBodyFormat`

Gets the body format for the request.

| Name         | Type | Required | Default | Description |
| ------------ | ---- | -------- | ------- | ----------- |
| No arguments |      |          |         |             |

**Return**: `String`

### `setBodyFormat`

Sets the body format for the request. Recognized values are `formFields`, `json`, or `xml`. It is highly recommended to use `asFormFields`, `asJson`, or `asXML` instead.  If you set this value to a non-recognized value, the body will be passed along as-is to the body of the HTTP request.

| Name  | Type | Required | Default | Description                      |
| ----- | ---- | -------- | ------- | -------------------------------- |
| value | any  | true     |         | The body format for the request. |

**Return**: `HyperRequest`

### `asJson`

A convenience method to set the body format and Content-Type to `json`.

| Name         | Type | Required | Default | Description |
| ------------ | ---- | -------- | ------- | ----------- |
| No arguments |      |          |         |             |

**Return**: `HyperRequest`

### `asFormFields`

A convenience method to set the body format and Content-Type to form fields.

| Name         | Type | Required | Default | Description |
| ------------ | ---- | -------- | ------- | ----------- |
| No arguments |      |          |         |             |

**Return**: `HyperRequest`

### `asXML`

A convenience method to set the body format and Content-Type to `xml`.

| Name         | Type | Required | Default | Description |
| ------------ | ---- | -------- | ------- | ----------- |
| No arguments |      |          |         |             |

**Return**: `HyperRequest`

### `getReferrer`

Gets the referrer for the request, if any.

| Name         | Type | Required | Default | Description |
| ------------ | ---- | -------- | ------- | ----------- |
| No arguments |      |          |         |             |

**Return**: `String`

### `getHeaders`

Gets the headers for the request.

| Name         | Type | Required | Default | Description |
| ------------ | ---- | -------- | ------- | ----------- |
| No arguments |      |          |         |             |

**Return**: `java.util.LinkedHashMap`

### `setHeaders`

Sets the headers for the request.

| Name  | Type   | Required | Default | Description                  |
| ----- | ------ | -------- | ------- | ---------------------------- |
| value | struct | true     |         | The headers for the request. |

**Return**: `HyperRequest`

### `setHeader`

Set a header for the request.

| Name  | Type   | Required | Default | Description              |
| ----- | ------ | -------- | ------- | ------------------------ |
| name  | string | true     |         | The name of the header.  |
| value | string | true     |         | The value of the header. |

**Return**: `HyperRequest`

### `withHeaders`

Add additional headers to the request.

| Name    | Type   | Required | Default | Description                                |
| ------- | ------ | -------- | ------- | ------------------------------------------ |
| headers | struct | true     |         | A struct of headers to add to the request. |

**Return**: `HyperRequest`

### `forwardHeaders`

Adds specified headers to the request if they exist. Usually used in conjunction with the current CFML request headers.

| Name    | Type   | Required | Default                               | Description                                                                           |
| ------- | ------ | -------- | ------------------------------------- | ------------------------------------------------------------------------------------- |
| names   | array  | true     |                                       | An array of header names to add to the request if they exist in the `headers` struct. |
| headers | struct | false    | `getHTTPRequestData( false ).headers` | A struct of headers to inspect.                                                       |

**Return**: `HyperRequest`

### `hasHeader`

Check if the request has a header with the given name.

| Name | Type   | Required | Default | Description                      |
| ---- | ------ | -------- | ------- | -------------------------------- |
| name | string | true     |         | The name of the header to check. |

**Return**: `boolean`

### `getCookies`

Gets the cookies for the request.

| Name         | Type | Required | Default | Description |
| ------------ | ---- | -------- | ------- | ----------- |
| No arguments |      |          |         |             |

**Return**: `struct<ordered>`

### `setCookies`

Sets the cookies for the request.

| Name  | Type   | Required | Default | Description                  |
| ----- | ------ | -------- | ------- | ---------------------------- |
| value | struct | true     |         | The headers for the request. |

**Return**: `HyperRequest`

### `setCookie`

Set a cookie for the request.

| Name  | Type   | Required | Default | Description              |
| ----- | ------ | -------- | ------- | ------------------------ |
| name  | string | true     |         | The name of the header.  |
| value | string | true     |         | The value of the header. |

**Return**: `HyperRequest`

### `withCookies`

Add additional cookies to the request.

| Name    | Type   | Required | Default | Description                                |
| ------- | ------ | -------- | ------- | ------------------------------------------ |
| cookies | struct | true     |         | A struct of headers to add to the request. |

**Return**: `HyperRequest`

### `withCredentials`

Sends all current cookies along with the request.

| Name         | Type | Required | Default | Description |
| ------------ | ---- | -------- | ------- | ----------- |
| No arguments |      |          |         |             |

**Return**: `HyperRequest`

### `hasCookie`

Check if the request has a cookie with the given name.

| Name | Type   | Required | Default | Description                      |
| ---- | ------ | -------- | ------- | -------------------------------- |
| name | string | true     |         | The name of the header to check. |

**Return**: `boolean`

### `setUserAgent`

A convenience method to set the [`User-Agent` header](https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/User-Agent).

| Name      | Type   | Required | Default | Description                          |
| --------- | ------ | -------- | ------- | ------------------------------------ |
| userAgent | string | true     |         | The User-Agent value for the request |

**Return**: `HyperRequest`

### `setContentType`

A convenience method to set the [`Content-Type` header](https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Content-Type).

| Name | Type   | Required | Default | Description                            |
| ---- | ------ | -------- | ------- | -------------------------------------- |
| type | string | true     |         | The Content-Type value for the request |

**Return**: `HyperRequest`

### `setAccept`

A convenience method to set the [`Accept` header](https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Accept).

| Name | Type   | Required | Default | Description                      |
| ---- | ------ | -------- | ------- | -------------------------------- |
| type | string | true     |         | The Accept value for the request |

**Return**: `HyperRequest`

### `getQueryParams`

Gets the query parameters for the request.

{% hint style="warning" %}
This method returns an array of param structs that is used under the hood by Hyper. You probably want to use [`getQueryParamByName`](#getqueryparambyname) or [`getAllQueryParamsByName`](#getallqueryparamsbyname) instead.
{% endhint %}

| Name         | Type | Required | Default | Description |
| ------------ | ---- | -------- | ------- | ----------- |
| No arguments |      |          |         |             |

**Return**: `array<struct<string, any>>`

### `setQueryParams`

Sets the query parameters for the request.

{% hint style="warning" %}
This method accepts an array of param structs that is used under the hood by Hyper. You probably want to use [`withQueryParams`](#withqueryparams) or [`appendQueryParams`](#appendqueryparams) instead.
{% endhint %}

If needed, param structs have two keys, `name` and `value`.

| Name  | Type  | Required | Default | Description                                                |
| ----- | ----- | -------- | ------- | ---------------------------------------------------------- |
| value | array | true     |         | The query parameters for the as an array of param structs. |

**Return**: `HyperRequest`

### `getQueryParam`

{% hint style="danger" %}
**DEPRECATED:** Use [`getQueryParamByName`](#getqueryparambyname)
{% endhint %}

Gets the first value for a certain query parameter. Returns an empty string if the query parameter does not exist.

| Name | Type   | Required | Default | Description                                                  |
| ---- | ------ | -------- | ------- | ------------------------------------------------------------ |
| name | string | true     |         | The name of the query parameter to retrieve the first value. |

**Return**: `any`

### `getQueryParamByName`

Gets the first value for a certian query parameter. Returns an empty string if the query parameter does not exist.

| Name | Type   | Required | Default | Description                                                  |
| ---- | ------ | -------- | ------- | ------------------------------------------------------------ |
| name | string | true     |         | The name of the query parameter to retrieve the first value. |

**Return**: `any`

### `getAllQueryParamsByName`

Get all the values for a certain query parameter. Returns an empty array if the query parameter does not exist.

| Name | Type   | Required | Default | Description                                                    |
| ---- | ------ | -------- | ------- | -------------------------------------------------------------- |
| name | string | true     |         | The name of the query parameter to retrieve all of its values. |

**Return**: `array<any>`

### `setQueryParam`

Set a query parameter for the request.

{% hint style="info" %}
**Note:** This removes all other query params with the same name.
{% endhint %}

| Name  | Type   | Required | Default | Description                       |
| ----- | ------ | -------- | ------- | --------------------------------- |
| name  | string | true     |         | The name of the query parameter.  |
| value | string | true     |         | The value of the query parameter. |

**Return**: `HyperRequest`

### `appendQueryParam`

Append a query parameter for the request.

| Name  | Type   | Required | Default | Description                       |
| ----- | ------ | -------- | ------- | --------------------------------- |
| name  | string | true     |         | The name of the query parameter.  |
| value | string | true     |         | The value of the query parameter. |

**Return**: `HyperRequest`

### `withQueryParams`

Add additional query parameters to the request.&#x20;

{% hint style="info" %}
**Note:** This will remove any values with duplicate keys prior to adding the new struct of params.
{% endhint %}

| Name        | Type   | Required | Default | Description                                         |
| ----------- | ------ | -------- | ------- | --------------------------------------------------- |
| queryParams | struct | true     |         | A struct of query parameters to add to the request. |

**Return**: `HyperRequest`

### `appendQueryParams`

Appends additional query parameters to the request.

| Name        | Type   | Required | Default | Description                                         |
| ----------- | ------ | -------- | ------- | --------------------------------------------------- |
| queryParams | struct | true     |         | A struct of query parameters to add to the request. |

**Return**: `HyperRequest`

### `hasQueryParam`

Check if the request has a query parameter with the given name.

| Name | Type   | Required | Default | Description                               |
| ---- | ------ | -------- | ------- | ----------------------------------------- |
| name | string | true     |         | The name of the query parameter to check. |

**Return**: `boolean`

### `attach`

Attaches a file to the Hyper request. Also sets the Content-Type as `multipart/form-data`. Multiple files can be attached by calling `attach` multiple times before calling a send method.

| Name     | Type   | Required | Default | Description                                       |
| -------- | ------ | -------- | ------- | ------------------------------------------------- |
| name     | string | true     |         | The name of the file being uploaded.              |
| path     | string | true     |         | The absolute path to the file to be uploaded.     |
| mimeType | string | false    |         | An optional mime type to associate with the file. |

**Return**: `HyperRequest`

### `setThrowOnError`

Sets the throw on error property for the request. If true, statuses in the 4xx and 5xx range will be turned in to exceptions.

| Name  | Type    | Required | Default | Description                           |
| ----- | ------- | -------- | ------- | ------------------------------------- |
| value | boolean | true     |         | The value of the throw on error flag. |

**Return**: `HyperRequest`

### `throwErrors`

A convenience method to throw on errors.

| Name         | Type | Required | Default | Description |
| ------------ | ---- | -------- | ------- | ----------- |
| No arguments |      |          |         |             |

**Return**: `HyperRequest`

### `allowErrors`

A convenience method to not throw on errors.

| Name         | Type | Required | Default | Description |
| ------------ | ---- | -------- | ------- | ----------- |
| No arguments |      |          |         |             |

**Return**: `HyperRequest`

### `clone`

Clones the current request into a new HyperRequest.

| Name         | Type | Required | Default | Description |
| ------------ | ---- | -------- | ------- | ----------- |
| No arguments |      |          |         |             |

**Return**: A new `HyperRequest` instance cloned from this one.

### `clear`

Clears the request of any set values, including defaults passed by the builder.

| Name         | Type | Required | Default | Description |
| ------------ | ---- | -------- | ------- | ----------- |
| No arguments |      |          |         |             |

**Return**: `HyperRequest`

### `when`

Helper to conditionally execute a callback for the `HyperRequest`. This method lets you use conditionals without breaking chaining.

| Name            | Type       | Required | Default | Description                                                                                            |
| --------------- | ---------- | -------- | ------- | ------------------------------------------------------------------------------------------------------ |
| condition       | `boolean`  | `true`   |         | The condition to check.                                                                                |
| successCallback | `function` | `true`   |         | The callback to execute if the condition is true. The callback is passed the `HyperRequest` instance.  |
| failureCallback | `function` | `false`  | `null`  | The callback to execute if the condition is false. The callback is passed the `HyperRequest` instance. |

**Return**: `HyperRequest`

### `retry`

Configures the request to retry failed requests.

| Name      | Type                         | Required | Default | Description                                                                                                                                                                                                                                                                                                                                                                                                                                |
| --------- | ---------------------------- | -------- | ------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------ |
| attempts  | `numeric` / `array<numeric>` | `true`   |         | Either the max number of retry attempts to make or an array containing retry delays between each attempt.  If a numeric value is passed in, the `delay` argument is required.                                                                                                                                                                                                                                                              |
| delay     | `numeric`                    | `false`  |         | The delay to use for each of the `attempts`. This argument is required if `attempts` is a numeric value.  If `attempts` is an array, this value is ignored.                                                                                                                                                                                                                                                                                |
| predicate | `function`                   | `false`  |         | <p>The predicate function to call to determine if a retry should be attempted.<br><br>This function is only called if there are configured retries available.<br><br>To retry a request, this function should return <code>true</code>.<br><br>It is passed the <code>response</code> and <code>request</code> as parameters.<br><br>Additionally, the <code>request</code> can be modified in this method for the next retry attempt.</p> |

**Return**: `HyperRequest`

### `getRetries`

Returns the current retry configuration which is an array of delay times.  A request that needs to be retried will be retried up to the amount of items in this array.  This array can be set using the `retry` method.

{% hint style="warning" %}
In most cases, you do not need to interact with this method directly.  Use the `retry` method instead.
{% endhint %}

| Name         | Type | Required | Default | Description |
| ------------ | ---- | -------- | ------- | ----------- |
| No arguments |      |          |         |             |

**Return**: `array<numeric>`

### `getCurrentRequestCount`

Returns the current request count.  Defaults to `1`. The only time this will increase is if `retries` have been configured for the request.

| Name         | Type | Required | Default | Description |
| ------------ | ---- | -------- | ------- | ----------- |
| No arguments |      |          |         |             |

**Return**: `numeric`

### `getRetryPredicate`

Returns the current callback function that is called to decide if a request should be retried.  This is only called if there are available retries left.

This callback is passed the response and the request as parameters.

A request will be retried if this function returns `true`.

In this function, the passed in request can be modified for the next retry.

{% hint style="warning" %}
In most cases, you do not need to interact with this method directly.  Use the `retry` method instead.
{% endhint %}

| Name         | Type | Required | Default | Description |
| ------------ | ---- | -------- | ------- | ----------- |
| No arguments |      |          |         |             |

**Return**: `numeric`

### `setProperties`

Quickly set many request properties using a struct. The key should be the name of one of the properties on the request, e.g. `url`, `headers`, `method`, `body`.

| Name       | Type   | Required | Default | Description                                                                                                                                   |
| ---------- | ------ | -------- | ------- | --------------------------------------------------------------------------------------------------------------------------------------------- |
| properties | struct | true     |         | A struct of properties to set. Each property name will be set on the request. Properties that don't exist on the request will throw an error. |

**Return**: `HyperRequest`

### `setHttpClient`

Sets the [HTTP Client](/7.3.0-1/customizing-hyper/custom-http-clients) to use for the request. The client should conform to the `HyperHttpClientInterface` (though it does not need to use the `implements` keyword).

| Name       | Type                       | Required | Default | Description                            |
| ---------- | -------------------------- | -------- | ------- | -------------------------------------- |
| httpClient | `HyperHttpClientInterface` | `true`   |         | The httpClient to use for the request. |

**Return**: `HyperRequest`

### `setInterceptorService`

Sets the [ColdBox Interceptor Service](https://coldbox.ortusbooks.com/the-basics/interceptors) to announce request and response interception points. A noop option is provided in the `init` for non-ColdBox usage.

| Name               | Type | Required | Default | Description                                     |
| ------------------ | ---- | -------- | ------- | ----------------------------------------------- |
| interceptorService | any  | `true`   |         | The interceptor service to use for the request. |

**Return**: `HyperRequest`

### `setAsyncManager`

Sets the [ColdBox AsyncManager](https://coldbox.ortusbooks.com/digging-deeper/promises-async-programming) to send requests asynchronously. A noop option is provided in the `init` for non-ColdBox usage.

| Name         | Type | Required | Default | Description                              |
| ------------ | ---- | -------- | ------- | ---------------------------------------- |
| asyncManager | any  | `true`   |         | The asyncManager to use for the request. |

**Return**: `HyperRequest`

### `getMemento`

Returns a struct representing this `HyperRequest`.

| Name         | Type | Required | Default | Description |
| ------------ | ---- | -------- | ------- | ----------- |
| No arguments |      |          |         |             |

**Return**:

```json
{
    "requestID"           : getRequestID(),
    "baseUrl"             : getBaseUrl(),
    "url"                 : getUrl(),
    "fullUrl"             : getFullUrl(),
    "method"              : getMethod(),
    "queryParams"         : getQueryParams(),
    "headers"             : getHeaders(),
    "cookies"             : getCookies(),
    "files"               : getFiles(),
    "bodyFormat"          : getBodyFormat(),
    "body"                : getBody(),
    "referrer"            : isNull( variables.referrer ) ? "" : variables.referrer,
    "throwOnError"        : getThrowOnError(),
    "timeout"             : getTimeout(),
    "maximumRedirects"    : getMaximumRedirects(),
    "authType"            : getAuthType(),
    "username"            : getUsername(),
    "password"            : getPassword(),
    "clientCert"          : isNull( variables.clientCert ) ? "" : variables.clientCert,
    "clientCertPassword"  : isNull( variables.clientCertPassword ) ? "" : variables.clientCertPassword,
    "domain"              : getDomain(),
    "workstation"         : getWorkstation(),
    "resolveUrls"         : getResolveUrls(),
    "encodeUrl"           : getEncodeUrl(),
    "retries"             : getRetries(),
    "currentRequestCount" : getCurrentRequestCount()
};
```

### `debug`

Creates a debug representation of the HTTP request for the current HTTP client.

{% hint style="danger" %}
**Throws**: `NoUrlException` when no URL is set.
{% endhint %}

| Name         | Type | Required | Default | Description |
| ------------ | ---- | -------- | ------- | ----------- |
| No arguments |      |          |         |             |

**Return**: Dependent on the configured HTTP Client.  See specific HTTP Client documentation for details.


# HyperResponse

The `HyperResponse` component is a read-only wrapper to easily grab different information about the response.

### `getResponseId`

Gets the unique response ID representing this response.

| Name         | Type | Required | Default | Description |
| ------------ | ---- | -------- | ------- | ----------- |
| No arguments |      |          |         |             |

**Return**: `String`

### `getStatusCode`

Gets the status code for the response.

| Name         | Type | Required | Default | Description |
| ------------ | ---- | -------- | ------- | ----------- |
| No arguments |      |          |         |             |

**Return**: `numeric`

### `getStatusText`

Gets the status text for the response.

| Name         | Type | Required | Default | Description |
| ------------ | ---- | -------- | ------- | ----------- |
| No arguments |      |          |         |             |

**Return**: `String`

### `getStatus`

Returns the status code and status text as a single string.

| Name         | Type | Required | Default | Description |
| ------------ | ---- | -------- | ------- | ----------- |
| No arguments |      |          |         |             |

**Return**: `String`

### `getData`

Gets the data for the response.

| Name         | Type | Required | Default | Description |
| ------------ | ---- | -------- | ------- | ----------- |
| No arguments |      |          |         |             |

**Return**: `String`

### `getRequestID`

Returns the id of the request to which this response is related.

| Name         | Type | Required | Default | Description |
| ------------ | ---- | -------- | ------- | ----------- |
| No arguments |      |          |         |             |

**Return**: `String`

### `getRequest`

Gets the [HyperRequest](/7.3.0-1/making-requests/hyperrequest) instance associated with this response.

| Name         | Type | Required | Default | Description |
| ------------ | ---- | -------- | ------- | ----------- |
| No arguments |      |          |         |             |

**Return**: [`HyperRequest`](/7.3.0-1/making-requests/hyperrequest)

### `getCharset`

Gets the charset value for the response.

| Name         | Type | Required | Default | Description |
| ------------ | ---- | -------- | ------- | ----------- |
| No arguments |      |          |         |             |

**Return**: `String`

### `getTimestamp`

Gets the timestamp for when this response was received.

| Name         | Type | Required | Default | Description |
| ------------ | ---- | -------- | ------- | ----------- |
| No arguments |      |          |         |             |

**Return**: `DateTime`

### `getExecutionTime`

Gets the execution time of the request, in milliseconds.

| Name         | Type | Required | Default | Description |
| ------------ | ---- | -------- | ------- | ----------- |
| No arguments |      |          |         |             |

**Return**: `numeric`

### `json`

Returns the data of the request as deserialized `JSON`.

{% hint style="danger" %}
**Throws**: `DeserializeJsonException` if the response is not `JSON`.
{% endhint %}

| Name         | Type | Required | Default | Description |
| ------------ | ---- | -------- | ------- | ----------- |
| No arguments |      |          |         |             |

**Return**: `any`

### `isSuccess`

Returns true if the request status code is considered successful.

| Name         | Type | Required | Default | Description |
| ------------ | ---- | -------- | ------- | ----------- |
| No arguments |      |          |         |             |

**Return**: `boolean`

### `isOK`

Returns true if the request status code is `200 OK`.

| Name         | Type | Required | Default | Description |
| ------------ | ---- | -------- | ------- | ----------- |
| No arguments |      |          |         |             |

**Return**: `boolean`

### `isCreated`

Returns true if the request status code is `201 Created`.

| Name         | Type | Required | Default | Description |
| ------------ | ---- | -------- | ------- | ----------- |
| No arguments |      |          |         |             |

**Return**: `boolean`

### `isRedirect`

Returns true if the request status code is considered a redirect.

| Name         | Type | Required | Default | Description |
| ------------ | ---- | -------- | ------- | ----------- |
| No arguments |      |          |         |             |

**Return**: `boolean`

### `isError`

Returns true if the request status code is considered either a client error (4xx status code) or a server error (5xx status code).

| Name         | Type | Required | Default | Description |
| ------------ | ---- | -------- | ------- | ----------- |
| No arguments |      |          |         |             |

**Return**: `boolean`

### `isClientError`

Returns true if the request status code is considered a client error (4xx status code).

| Name         | Type | Required | Default | Description |
| ------------ | ---- | -------- | ------- | ----------- |
| No arguments |      |          |         |             |

**Return**: `boolean`

### `isUnauthorized`

Returns true if the request status code is `401 Unauthorized`.

| Name         | Type | Required | Default | Description |
| ------------ | ---- | -------- | ------- | ----------- |
| No arguments |      |          |         |             |

**Return**: `boolean`

### `isForbidden`

Returns true if the request status code is `403 Forbidden`.

| Name         | Type | Required | Default | Description |
| ------------ | ---- | -------- | ------- | ----------- |
| No arguments |      |          |         |             |

**Return**: `boolean`

### `isNotFound`

Returns true if the request status code is `404 Not Found`.

| Name         | Type | Required | Default | Description |
| ------------ | ---- | -------- | ------- | ----------- |
| No arguments |      |          |         |             |

**Return**: `boolean`

### `isServerError`

Returns true if the request status code is considered a server error (5xx status code).

| Name         | Type | Required | Default | Description |
| ------------ | ---- | -------- | ------- | ----------- |
| No arguments |      |          |         |             |

**Return**: `boolean`

### `hasHeader`

Checks if a header exists in the response.

| Name | Type     | Required | Default | Description                      |
| ---- | -------- | -------- | ------- | -------------------------------- |
| name | `String` | `true`   |         | The name of the header to check. |

**Return**: `boolean`

### `getHeader`

Gets the value of a header from the response.

| Name         | Type     | Required | Default | Description                                       |
| ------------ | -------- | -------- | ------- | ------------------------------------------------- |
| name         | `String` | `true`   |         | The name of the header to retrieve.               |
| defaultValue | `any`    | `false`  | `""`    | The value to return if the header does not exist. |

**Return**: `any`

### `getCookies`

Caches the result of parsing the `Set-Cookie` header and returns it.

| Name         | Type | Required | Default | Description |
| ------------ | ---- | -------- | ------- | ----------- |
| No arguments |      |          |         |             |

**Return**: `struct`

### `persistCookies`

Parses and saves the cookies to the cookie scope.

| Name         | Type | Required | Default | Description |
| ------------ | ---- | -------- | ------- | ----------- |
| No arguments |      |          |         |             |

**Return**: `HyperResponse`

### `getMemento`

Gets a serializable representation of the response.

| Name         | Type | Required | Default | Description |
| ------------ | ---- | -------- | ------- | ----------- |
| No arguments |      |          |         |             |

**Return**:

```json
{
    "responseID"    : getResponseID(),
    "requestID"     : getRequestID(),
    "statusCode"    : getStatusCode(),
    "statusText"    : getStatusText(),
    "status"        : getStatus(),
    "data"          : getData(),
    "charset"       : getCharset(),
    "headers"       : getHeaders(),
    "timestamp"     : getTimestamp(),
    "executionTime" : getExecutionTime(),
    "cookies"       : getCookies()
}
```


# Hyper Clients

Hyper allows you to configure defaults for your requests as custom Hyper Clients. This is particularly useful for reducing boilerplate in your application.

Defaults are set on the `HyperBuilder` instance. The easiest way to do this is to configure it in WireBox. In an `afterAspectsLoad` method, you can get a reference to a `HyperBuilder`, configure it as you would for a request, and then call the `registerAs` method passing in your desired WireBox alias.

```cfscript
// config/WireBox.cfc
component {

   // ...
   
   function afterApsectsLoad() {
       injector.getInstance( "HyperBuilder@hyper" )
           .setBaseUrl( "https://swapi.dev/api" )
           .asJson()
           .registerAs( "StarWarsClient" );
   }

}
```

{% hint style="info" %}
Putting the registration code in `afterAspectsLoad` is required so Hyper can be loaded and available for injection.
{% endhint %}

Now, you can inject this pre-configured builder wherever you need in your application:

```js
component {

    property name="StarWarsClient" inject="StarWarsClient";

    function findUser( id ) {
        return variables.StarWarsClient.get( "/people/#id#" );
    }

}
```

You can alternatively create the clients by passing in the desired defaults to the `initWith` method of a WireBox mapping.  These arguments must match the [`HyperRequest` property names](#hyperrequest-property-names).

```js
// config/WireBox.cfc
component {

    function configure() {
        map( "StarWarsClient" )
            .to( "hyper.models.HyperBuilder" )
            .asSingleton()
            .initWith(
                baseUrl = "https://swapi.dev/api"
            );
    }

}
```

You can even create multiple clients using this approach:

```js
// config/WireBox.cfc
component {

    function configure() {
        // ...
    }

    function afterAspectsLoad() {
        injector.getInstance( "HyperBuilder@hyper" )
           .setBaseUrl( "https://swapi.dev/api" )
           .asJson()
           .registerAs( "StarWarsClient" );

       injector.getInstance( "HyperBuilder@hyper" )
           .setBaseUrl( "https://api.github.com" )
           .asJson()
           .withHeaders( {
               "Authorization": coldbox.getUtil().getSystemSetting( "GITHUB_TOKEN" )
           } )
           .registerAs( "GitHubClient" );
    }

}
```

You can also set or change the defaults by either passing the key / value pairs in to the `init` method or by calling the appropriate `HyperRequest` method on the `HyperBuilder.defaults` property.

```js
var hyper = new Hyper.models.HyperBuilder(
    baseUrl = "https://api.github.com"
);
hyper.defaults.withHeaders( { "Authorization" = token } );
```

#### HyperRequest property names

```cfscript
/**
* The httpClient to use for the request
*/
property name="httpClient";

/**
* The baseURL for the request.
* e.g. https://api.github.com/
*/
property name="baseUrl" default="";

/**
* The URL for the request.
* It can either be a full url
* or a URI resource for use with the baseURL.
* e.g. /repos
*/
property name="url" default="";

/**
* Setting this to true will change all relative urls in the document to absolute.
*/
property name="resolveUrls" default="false";

/**
* Setting this to false will not automatically encode the url passed.
* WARNING: Setting this to false is not supported on Adobe engines.
*/
property name="encodeUrl" default="true";

/**
* The HTTP method for the request.
*/
property name="method" default="GET";

/**
* The username for the request for basic auth.
*/
property name="username" default="";

/**
* The password for the request for basic auth.
*/
property name="password" default="";

/**
* Timeout, in seconds, for the request.
*/
property name="timeout" default="10";

/**
* The maximum number of redirects to follow.
* A value of `*` will follow redirects infinitely.
*/
property name="maximumRedirects" default="*";

/**
* The body to send with the request.
* How the body is serialized is
* determined by the bodyFormat.
*/
property name="body" default="";

/**
* The format to serialize the body.
* e.g. `json` or `formFields`
*/
property name="bodyFormat" default="json";

/**
* The referring response in the case of redirects.
*/
property name="referrer";

/**
* A struct of headers for the request.
*/
property name="headers";

/**
* A struct of query parameters for the request.
*/
property name="queryParams";

/**
* Flag to throw on a cfhttp error.
*/
property name="throwOnError" default="false";

/**
* The full path to a PKCS12 format file that contains the client certificate for the request.
*/
property name="clientCert";

/**
* 	Password used to decrypt the client certificate.
*/
property name="clientCertPassword";

/**
* The domain for the request for NTLM auth.
*/
property name="domain" default="";

/**
* The workstation for the request for NTLM auth.
*/
property name="workstation" default="";

/**
* The authType for the request
*/
property name="authType" default="BASIC";

/**
* An array of callback functions to call
* before firing off a request.
*/
property name="requestCallbacks" type="array";

/**
* An array of callback functions to call
* after receiving a response.
*/
property name="responseCallbacks" type="array";
```

If you need per-request or per-response manipulation of defaults, use the [`requestCallbacks`](/7.3.0-1/making-requests/hyperrequest#withrequestcallback) and [`responseCallbacks`](/7.3.0-1/making-requests/hyperrequest#withresponsecallback) hooks.

```cfscript
map( "ApiClient" )
    .to( "hyper.models.HyperBuilder" )
    .asSingleton()
    .initWith(
        baseUrl = getColdBox().getUtil().getSystemSetting( "API_URL" ),
        requestCallbacks = [
            // provide the current user's token for the request
            function( req ) {
                var auth = getWireBox().getInstance( "AuthenticationService@cbauth" );
                req.withHeaders( "Authorization", auth.user().getApiToken() );
            }
        ],
        responseCallbacks = [
            // map custom `error` property to an exception
            function ( res ) {
                if ( !res.isError() ) {
                    return;
                }
                
                var body = res.json();
                throw(
                    type = "ApiError",
                    message = body.error.message,
                    detail = body.error.code
                );
            }
        ]
    );
```


# Custom HTTP Clients

By default, Hyper makes HTTP requests using `cfhttp` under the hood.  This can be swapped out by any compatible HTTP client that follows the `HyperHttpClientInterface`.

```cfscript
/**
 * Responsible for executing the HyperRequest and mapping it to a HyperResponse
 */
interface displayname="HyperHttpClientInterface" {

	/**
	 * Execute the HyperRequest and map it to a HyperResponse.
	 *
	 * @req     The HyperRequest to execute.
	 *
	 * @returns A HyperResponse of the executed request.
	 */
	public HyperResponse function send( required HyperRequest req );

	/**
	 * Return a struct of information showing how the client will execute the HyperRequest.
	 * This will be used by a developer to debug any differences between the generated
	 * request values and the expected request values.
	 *
	 * @req     The HyperRequest to debug.
	 *
	 * @returns A struct of information detailing how the client would execute the HyperRequest.
	 */
	public struct function debug( required HyperRequest req );

}
```


# CfhttpHttpClient

### `debug`

Return a struct of information showing how the client will execute the [`HyperRequest`](/7.3.0-1/making-requests/hyperrequest). This will be used by a developer to debug any differences between the generated request values and the expected request values.

| Name | Type                                                    | Required | Default | Description                                                           |
| ---- | ------------------------------------------------------- | -------- | ------- | --------------------------------------------------------------------- |
| req  | [`HyperRequest`](/7.3.0-1/making-requests/hyperrequest) | `true`   |         | The [`HyperRequest`](/7.3.0-1/making-requests/hyperrequest) to debug. |

**Return**:

```json
{
    "attributes" : attrCollection,
    "body"       : {
        "headers" : cfhttpHeaders,
        "params"  : cfhttpParams,
        "files"   : cfhttpFiles,
        "body"    : cfhttpBody,
        "cookies" : cfhttpCookies
    }
}
```


# Faking Requests

Hyper has the ability to fake requests and return fake responses as a result.  This is perfect for [testing](https://testbox.ortusbooks.com/) scenarios where you don't actually want to make an HTTP request.

{% hint style="warning" %}
Non-ColdBox users will need to add a mapping to the [`Globber`](https://forgebox.io/view/globber) dependency included with Hyper.

```cfscript
// Application.cfc
component {
    this.mappings[ "/globber" ] = "/path/to/hyper" & "/modules/globber";
}
```

{% endhint %}

## Faking All Requests

Faking is enabled on a [`HyperBuilder`](/7.3.0-1/making-requests/hyperbuilder) instance, either the built-in one provided by Hyper or a [custom Hyper client](/7.3.0-1/customizing-hyper/custom-http-clients) you have created.

To enable faking requests, call the `fake` method:

```cfscript
var hyper = new Hyper.models.HyperBuilder();
hyper.fake();
```

After calling the `fake` method, all requests created by this `HyperBuilder` will be faked.  By default, they will return `200 OK` responses with empty bodies.

```cfscript
hyper.fake();
var res = hyper.get( "https://google.com" );
expect( res.getStatus() ).toBe( "200 OK" );
```

## Fake Configuration

When calling the `fake` method, you can provide a struct mapping URL patterns to response generator functions.

```cfscript
hyper.fake( {
    "https://google.com/*": function( newFakeResponse, req ) {
         return newFakeResponse( 404, "Not Found" );
    }
} );
```

The key is a URL pattern.  The pattern can be any valid glob. If the pattern is matched by the [`fullUrl`](/7.3.0-1/making-requests/hyperrequest#getfullurl) of the `HyperRequest`, then the response generator function will be called and the results returned.

A helper function, `newFakeResponse`, is provided as the first argument to the response generator function.  The current request is provided as the second argument.

## FakeHyperResponse

The resposne generator function must return a `FakeHyperResponse` instance.  A `FakeHyperResponse` instance acts similar to a normal `HyperResponse` except the properties are not read only.  Once you have an instance of your `FakeHyperResponse`, you can continue to set any properties you need.

```cfscript
hyper.fake( {
    "https://jsonplaceholder.typicode.com/posts": function( newFakeResponse, req ) {
         return newFakeResponse()
             .setStatusCode( 201 )
             .setStatusText( "Created" )
             .setData( serializeJSON( {
                 "id": 101,
                 "title": "foo",
                 "body": "bar",
                 "userId": 1
             } ) );
    }
} );
```

You can also pass the values to the `newFakeResponse` function, if you'd like.

```cfscript
hyper.fake( {
    "https://jsonplaceholder.typicode.com/posts": function( newFakeResponse, req ) {
         return newFakeResponse( 201, "Created", serializeJSON( {
             "id": 101,
             "title": "foo",
             "body": "bar",
             "userId": 1
         } ) );
    }
} );
```

### `newFakeResponse`

Creates a new `FakeHyperResponse` instance.

<table><thead><tr><th width="160">Name</th><th>Type</th><th>Required</th><th>Default</th><th>Description</th></tr></thead><tbody><tr><td>statusCode</td><td><code>numeric</code></td><td><code>false</code></td><td>200</td><td>The status code for the fake response.</td></tr><tr><td>statusText</td><td><code>string</code></td><td><code>false</code></td><td><code>"OK"</code></td><td>The status text for the fake response.</td></tr><tr><td>data</td><td><code>string</code></td><td><code>false</code></td><td><code>""</code></td><td>The data for the fake response.</td></tr><tr><td>headers</td><td><code>{ string: string }</code></td><td><code>false</code></td><td><code>{}</code></td><td>The headers for the fake response.</td></tr><tr><td>executionTime</td><td><code>numeric</code></td><td><code>false</code></td><td>0</td><td>The execution time for the fake response.</td></tr><tr><td>charset</td><td><code>string</code></td><td><code>false</code></td><td><code>"UTF-8"</code></td><td>The charset for the fake response.</td></tr><tr><td>timestamp</td><td><code>datetime</code></td><td><code>false</code></td><td><code>now()</code></td><td>The timestamp of the fake response.</td></tr></tbody></table>

**Return**: `FakeHyperResponse`

## Sequencing Fake Responses

In addition to returning a single `FakeHyperResponse` per pattern, you can return an array of `FakeHyperResponse` instances.  These will be returned in a sequence.

```cfscript
hyper.fake( {
    "https://jsonplaceholder.typicode.com/posts": function( newFakeResponse, req ) {
         return [
             newFakeResponse( 201, "Created", serializeJSON( {
                 "id": 101,
                 "title": "foo",
                 "body": "bar",
                 "userId": 1
             } ) ),
             newFakeResponse( 422, "Unprocessable Entity", "Duplicate title" )
         ];
    }
} );

var resA = hyper.post( "https://jsonplaceholder.typicode.com/posts", { /* ... */ } );
expect( resA.getStatus() ).toBe( "201 Created" );

var resB = hyper.post( "https://jsonplaceholder.typicode.com/posts", { /* ... */ } );
expect( resA.getStatus() ).toBe( "422 Unprocessable Entity" );
```

If you continue to make requests to the same pattern after the sequence has been exhausted, an exception will be thrown.

```cfscript
hyper.fake( {
    "https://jsonplaceholder.typicode.com/posts": function( newFakeResponse, req ) {
         return [
             newFakeResponse( 201, "Created", serializeJSON( {
                 "id": 101,
                 "title": "foo",
                 "body": "bar",
                 "userId": 1
             } ) ),
             newFakeResponse( 422, "Unprocessable Entity", "Duplicate title" )
         ];
    }
} );

var resA = hyper.post( "https://jsonplaceholder.typicode.com/posts", { /* ... */ } );
expect( resA.getStatus() ).toBe( "201 Created" );

var resB = hyper.post( "https://jsonplaceholder.typicode.com/posts", { /* ... */ } );
expect( resA.getStatus() ).toBe( "422 Unprocessable Entity" );

// THROWS a `HyperFakeSequenceExhausted` exception
var resC = hyper.post( "https://jsonplaceholder.typicode.com/posts", { /* ... */ } );
```

## Preventing Stray Requests

By default, Hyper returns a default `FakeHyperResponse` for every request that doesn't match one of your configured patterns.  You can instead cause Hyper to throw an exception if it encounters one of these stray requests by calling the `preventStrayRequests` method.

```cfscript
hyper.fake( {
    "https://google.com/*": function( newFakeResponse, req ) {
         return newFakeResponse( 404, "Not Found" );
    }
} ).preventStrayRequests();

// THROWS a `HyperFakeStrayRequest` exception
var res = hyper.get( "https://github.com" );
```

## Making Assertions

In addition to assertions made against the `FakeHyperResponse` instances returned, you can also make assertions using the `HyperBuilder` instance you faked.  These come in the form of methods on the `HyperBuilder` instance as well as custom TestBox Assertions.

### HyperBuilder Method Assertions

The following methods are available to make assertions in your tests about the requests that were sent.

#### getFakeRequestCount

Returns the number of fake requests that have been made.

| Name         | Type | Required | Default | Description |
| ------------ | ---- | -------- | ------- | ----------- |
| No arguments |      |          |         |             |

**Return**: `numeric`

#### wasRequestSent

Returns whether a request has been made that matches the `predicate`. Each request that has been made is passed to the `predicate` in order. If the `predicate` returns `true`, the request is considered a match and `true` is returned. If no request passes the `predicate`, `false` is returned.

| Name      | Type       | Required | Default | Description                                                                                            |
| --------- | ---------- | -------- | ------- | ------------------------------------------------------------------------------------------------------ |
| predicate | `function` | `true`   |         | A callback function that returns true if the request matches the criteria and returns false otherwise. |

**Return**: `boolean`

### Custom TestBox Assertions

You can register [custom TestBox assertions](https://testbox.ortusbooks.com/in-depth/expectations/custom-matchers) provided by Hyper for more readable tests and test failure messages.

You must [register](https://testbox.ortusbooks.com/in-depth/expectations/custom-matchers#cfc-matchers) these assertions before using them.

```cfscript
component extends="testbox.system.BaseSpec" {

    function beforeAll() {
        addMatchers( "hyper.models.TestBoxMatchers" )
    }
    
    function run() {
        // ...
    }

}
```

The following custom assertions are provided:

#### toHaveSentRequest

This takes in the `HyperBuilder` instance as the actual and a predicate function as the expected. The predicate function is passed to the `HyperBuilder` instance's `wasRequestSent` method.

```cfscript
hyper.fake();

hyper.get( "https://google.com" );

expect( hyper ).toHaveSentRequest( function( req ) {
    return req.getFullUrl( "https://google.com" );
} );

expect( hyper ).notToHaveSentRequest( function( req ) {
    return req.getFullUrl( "https://github.com" );
} );
```

#### toHaveSentCount

This takes in the `HyperBuilder` instance as the actual and an integer number of requests that should have been sent.

```cfscript
hyper.fake();

hyper.get( "https://google.com" );

expect( hyper ).toHaveSentCount( 1 );
expect( hyper ).notToHaveSentCount( 2 );
```

#### toHaveSentNothing

This takes in the `HyperBuilder` instance as the actual and no other parameters.

```cfscript
hyper.fake();

expect( hyper ).toHaveSentNothing();

hyper.get( "https://google.com" );

expect( hyper ).notToHaveSentNothing();
```

## Resetting the Builder

To reset the sent request counts and sequences but keep the fake configuration, use the `resetFakes` method:

```javascript
hyper.fake();

hyper.get( "https://google.com" );

expect( hyper ).toHaveSentCount( 1 );

hyper.resetFakes();

expect( hyper ).toHaveSentNothing();
```

To reset the `HyperBuilder` instance to normal operation call the `clearFakes` method:

```cfscript
hyper.fake();

hyper.get( "https://google.com" );

hyper.clearFakes();
```

{% hint style="info" %}
These are useful methods to call in an [`afterEach`](https://testbox.ortusbooks.com/in-depth/life-cycle-methods/bdd#aftereach-body-data) block in TestBox to make sure you are only faking requests when you want to.
{% endhint %}


# Introduction

## A CFML HTTP Builder

### Inspiration

Hyper was built after coding several API SDK's for various platforms — [S3SDK](https://github.com/coldbox-modules/s3sdk), [cbstripe](https://github.com/coldbox-modules/cbox-stripe), and [cbgithub](https://github.com/elpete/cbgithub), to name a few. We noticed that we spent a lot of time setting up the plumbing for the requests and a wrapper around `cfhttp`. Each implementation was mostly the same but slightly different. It was additionally frustrating because we really only needed to tweak a few values, usually just the `Authorization` header. It would be nice to create an HTTP client pre-configured for each of these SDK's. It seemed the perfect fit for a module.

### The problem it solves

Hyper exists to provide a fluent builder experience for HTTP requests and responses. It also provides a powerful way to create clients, i.e. Builder objects with pre-configured defaults like a base URL or certain headers.


# What's New?

## 7.4.0

### asBinary

Added a [convenience method](/7.4.0-1/making-requests/hyperrequest#asbinary) to set the `bodyFormat` to `binary` and the `Content-Type` to `application/octet-stream`.

## 7.3.0

### Retrying Failed Requests

You can now configure a `HyperRequest` to automatically retry failed requests.  [See the `HyperRequest` docs for details.](/7.4.0-1/making-requests/hyperrequest#retry)

### Default User-Agent

Hyper now sends a default User-Agent of `HyperCFML/#versionNumber#`.

### Reset Fake Request Counts and Sequences

Hyper can now reset the fake request counts and sequences without losing the fake configuration using the [`resetFakes`](/7.4.0-1/testing/faking-requests#resetting-the-builder) method.

## 7.2.0

### Cookies

Hyper can now [send cookies with a request](/7.4.0-1/making-requests/hyperrequest#withcookies) and [parse the returned cookies from a response](/7.4.0-1/making-requests/hyperresponse#getcookies). See the [HyperRequest](/7.4.0-1/making-requests/hyperrequest) and [HyperResponse](/7.4.0-1/making-requests/hyperresponse) docs for details.

## 7.1.0

### Fake Requests

Hyper now has the ability to fake requests and return fake responses as a result.  This is perfect for testing scenarios where you don't actually want to make an HTTP request.

{% content-ref url="/pages/fDs68ouvcjilusPgzOdw" %}
[Faking Requests](/7.4.0-1/testing/faking-requests)
{% endcontent-ref %}

### Custom Hyper Clients

It is now more straightforward to register a [custom Hyper client](/7.4.0-1/customizing-hyper/custom-http-clients).  Inside your `config/WireBox.cfc` in an `afterAspectsLoad` method, you can get a reference to a `HyperBuilder`, configure it as you would for a request, and then call the `registerAs` method passing in your desired WireBox alias.

```cfscript
// config/WireBox.cfc
component {

   // ...
   
   function afterApsectsLoad() {
       injector.getInstance( "HyperBuilder@hyper" )
           .setBaseUrl( "https://api.github.com" )
           .asJson()
           .withHeaders( {
               "Authorization": coldbox.getUtil().getSystemSetting( "GITHUB_TOKEN" )
           } )
           .registerAs( "GitHubClient" );
   }

}
```

This is a welcome improvement as the `init` arguments do not exactly match the method names.  Also, for defaults like `requestCallbacks`, `responseCallbacks`, or even `queryParams`, passing in arrays of functions or arrays or structs is not as straightforward as calling the related methods.  Now, you can use the Hyper methods you are familiar with when registering your custom Hyper clients.

{% hint style="info" %}
Putting the registration code in `afterAspectsLoad` is required so Hyper can be loaded and available for injection.
{% endhint %}

## 7.0.0

### CFHttp HTTP Client

This client now returns more accurate status codes for `502 Bad Gateway` and `408 Request Timeout` responses.

Previously, these responses were returned as `504 Gateway Timeout` responses. Hyper now normalizes the responses from the different CFML engines into a consistent response. `502 Bad Gateway` is returned instead of `504 Gateway Timeout` for invalid hosts. `408 Request Timeout` is returned if the request takes longer than the configured [`timeout`](/7.4.0-1/making-requests/hyperrequest#settimeout) value.

### Breaking Changes

If you were previously checking specifically for `504` status codes for bad hosts, you need to now either check for `502` status codes or use a more general method, like [`isServerError`](/7.4.0-1/making-requests/hyperresponse#isservererror) or [`isError`](/7.4.0-1/making-requests/hyperresponse#iserror).

If you were previously checking specifically for `504` status codes or [`isServerError`](/7.4.0-1/making-requests/hyperresponse#isservererror) for timed out requests, you need to now either check for `408` status codes, [`isClientError`](/7.4.0-1/making-requests/hyperresponse#isclienterror), or the more general [`isError`](/7.4.0-1/making-requests/hyperresponse#iserror).

## 6.1.0

Add [`head`](/7.4.0-1/making-requests/hyperrequest#head) and [`options`](/7.4.0-1/making-requests/hyperrequest#options) shortcut methods.

## 6.0.0

* Add `xml` support and an `asXML` method to set the body format and `Content-Type` header.
* Add `adobe@2023` to testing matrix.

### Breaking Changes

* Remove default `Content-Type` header. You must set this [manually](/7.4.0-1/making-requests/hyperrequest#setcontenttype) or use a format helper, such as [`asJson`](/7.4.0-1/making-requests/hyperrequest#asjson).
* Dropped `adobe@2016` support.

## 5.0.1

Correctly handle cases when the `body` is a string and format is `JSON`.

## 5.0.0

Add a `debug` method to see what the HTTP client generates.

### Breaking Changes

`HyperHttpClientInterface` now requires a `debug` method.

```cfscript
/**
 * Return a struct of information showing how the client will execute the HyperRequest.
 * This will be used by a developer to debug any differences between the generated
 * request values and the expected request values.
 *
 * @req     The HyperRequest to debug.
 *
 * @returns A struct of information detailing how the client would execute the HyperRequest.
 */
public struct function debug( required HyperRequest req );
```

## 4.0.3

* Do not prepend the base url when a full url is passed.
* Add `resolveUrls` and `encodeUrl` properties to the [memento](/7.4.0-1/making-requests/hyperrequest#getmemento).
* Correctly set the `encodeUrl` property when cloning a request.

## 4.0.2

Update README for builder `initWith` headers losing `Content-Type`.

## 4.0.1

Fix `HyperBuilder` example in the docs.

## 4.0.0

Allow adding multiple query params with the same key.

### Breaking Changes

Previously, query params were stored as a struct.  Some APIs expect multiple values for the same query param name to be passed as separate arguments.  Hyper now stores the query params as an array and provides new methods for interacting with query params:

* [`getQueryParamByName`](/7.4.0-1/making-requests/hyperrequest#getqueryparambyname)
* [`getAllQueryParamsByName`](/7.4.0-1/making-requests/hyperrequest#getallqueryparamsbyname)
* [`withQueryParams`](/7.4.0-1/making-requests/hyperrequest#withqueryparams)
* [`appendQueryParam`](/7.4.0-1/making-requests/hyperrequest#appendqueryparam)
* [`appendQueryParams`](/7.4.0-1/making-requests/hyperrequest#appendqueryparams)
* [`hasQueryParam`](/7.4.0-1/making-requests/hyperrequest#hasqueryparam)

The following methods still exist, but now interact with arrays of query param structs instead of a simple struct.

* [`getQueryParams`](/7.4.0-1/making-requests/hyperrequest#getqueryparams)
* [`setQueryParams`](/7.4.0-1/making-requests/hyperrequest#setqueryparams)

The following methods have been deprecated:

| Deprecated Method                                                      | Replacement Method                                                                 |
| ---------------------------------------------------------------------- | ---------------------------------------------------------------------------------- |
| [`getQueryParam`](/7.4.0-1/making-requests/hyperrequest#getqueryparam) | [`getQueryParamByName`](/7.4.0-1/making-requests/hyperrequest#getqueryparambyname) |

## 3.6.2

Convert array values correctly when sending form fields

## 3.6.1

Add a workaround for CommandBox not having the `box:asyncManager` injection DSL.

## 3.6.0

Add async requests using ColdBox's [AsyncManager](https://coldbox.ortusbooks.com/digging-deeper/promises-async-programming).

## 3.5.0

* Provide more useful error than cfhttp when [`throwOnErrors`](/7.4.0-1/making-requests/hyperrequest#throwerrors) is enabled.
* Provide mementos for [HyperRequest](/7.4.0-1/making-requests/hyperrequest#getmemento) and [HyperResponse](/7.4.0-1/making-requests/hyperresponse#getmemento) instances.
* Capture [statusText](/7.4.0-1/making-requests/hyperresponse#getstatustext) and provide a [status](/7.4.0-1/making-requests/hyperresponse#getstatus) convenience string.

## 3.4.2

Add MIT License file

## 3.4.1

Use `processState` over `announce` until CommandBox can update its `interceptorService`.

## 3.4.0

### HyperRequest

* Add [`forwardHeaders`](/7.4.0-1/making-requests/hyperrequest#forwardheaders) shortcut method.

### HyperResponse

* Allow for default values in [`getHeader`](/7.4.0-1/making-requests/hyperresponse#getheader).
* Add helper methods for checking for specific status codes:
  * [`isOk`](/7.4.0-1/making-requests/hyperresponse#isok)
  * [`isUnauthorized`](/7.4.0-1/making-requests/hyperresponse#isunauthorized)
  * [`isForbidden`](/7.4.0-1/making-requests/hyperresponse#isforbidden)
  * [`isNotFound`](/7.4.0-1/making-requests/hyperresponse#isnotfound)

## 3.3.0

Allowing [attaching](/7.4.0-1/making-requests/hyperrequest#attach) file uploads.

## 3.2.1

Support WireBox outside of ColdBox.

## 3.2.0

Include response data as detail in `DeserializeJsonException`.

## 3.1.0

* Add [`clone`](/7.4.0-1/making-requests/hyperrequest#clone) to quickly copy `HyperRequest` instances.
* Add interceptors and [local](/7.4.0-1/making-requests/hyperrequest#withrequestcallback) [callbacks](/7.4.0-1/making-requests/hyperrequest#withresponsecallback) for lifecycle events.

## 3.0.0

Add execution time to `HyperResponse` instances.

### Breaking Changes

Dropped support for ColdBox 5.

## 2.3.11

* Add support for [NTLM authentication](/7.4.0-1/making-requests/hyperrequest#withntlmauth).
* Include [`getFullURL`](/7.4.0-1/making-requests/hyperrequest#getfullurl) method in docs.

## 2.3.10

Fixed typo of `Bulider` to `Builder`.

## 2.3.9

Add [`withoutEncodingUrl`](/7.4.0-1/making-requests/hyperrequest#withoutencodingurl) flag.

## 2.3.8

Do not fail fast on cron job actions on CI.

## 2.3.7

Update fetch-depth for tests and release actions on CI.

## 2.3.6

Attempt to skip committing back changes on CI.

## 2.3.5

Add matrix and cron testing on CI.

## 2.3.4

Use better GitHub token on CI

## 2.3.1

Add workaround for `boolean` values in query strings.

## 2.3.0

Add [certificate](/7.4.0-1/making-requests/hyperrequest#withcertificateauth) auth.

## 2.2.1

Use the previous host for redirect if redirect does not include a full URL.

## 2.2.0

Add [`resolveUrls`](/7.4.0-1/making-requests/hyperrequest#setresolveurl) flag.

## 2.1.1

* Use OpenJDK instead of OracleJDK on CI.
* Store module in [ForgeBox Storage](https://commandbox.ortusbooks.com/5.6.0/developing-for-commandbox/commands).

## 2.1.0

Allow for pluggable [HTTP Clients](/7.4.0-1/customizing-hyper/custom-http-clients) that follow the `HyperHttpClientInterface`. (Clients do not need to use the `implements` keyword.)

## 2.0.2

Avoid double encoding using [`cfhttpparam`](https://cfdocs.org/cfhttpparam).

## 2.0.1

Remove Lucee 4.5 support from docs. (Support was dropped in [v2.0.0](#2.0.0))

## 2.0.0

* Do not include [`username`](/7.4.0-1/making-requests/hyperrequest#setusername) and [`password`](/7.4.0-1/making-requests/hyperrequest#setpassword) unless they have values.
* Add `adobe@2018` support to CI builds.

### Breaking Changes

Dropped support for `lucee@4.5`.

## 1.15.0

Add [`throwOnError`](/7.4.0-1/making-requests/hyperrequest#throwerrors) flag.

## 1.14.5

Use `504 Gateway Timeout` for incomplete responses.

## 1.14.4

Include equal signs in query param values.

## 1.14.0 – 1.0.0

### New Features

* Add [`when`](/7.4.0-1/making-requests/hyperrequest#when) helper to execute conditions without breaking chaining.
* Add [`clear`](/7.4.0-1/making-requests/hyperrequest#clear) method to reset HyperRequest instances.
* Add configurable [`timeout`](/7.4.0-1/making-requests/hyperrequest#settimeout).

### Bug Fixes

* Fix for Lucee 4 compatibility on `LinkedHashMaps` and `keyArray`.
* Preserve case in header names.
* Preserve case for query parameters.
* Serialize both params from the url and set on the `HyperRequest` instance.
* Default to `UTF-8` charset if none is present in the response.
* Fix withHeaders and withQueryParams for Lucee compatibility.
* Only map HyperBuilder as a singleton in WireBox

### Other

* Migrate to [coldbox-modules](https://github.com/coldbox-modules) organization on GitHub.
* Update `box.json` description.
* Enable [CommandBox Semantic Release](https://forgebox.io/view/commandbox-semantic-release) on CI.


# Upgrade Guide

## Upgrading from v6 to v7

### CFHttp HTTP Client

This client now returns more accurate status codes for `502 Bad Gateway` and `408 Request Timeout` responses.

If you were previously checking specifically for `504` status codes for bad hosts, you need to now either check for `502` status codes or use a more general method, like [`isServerError`](/7.4.0-1/making-requests/hyperresponse#isservererror) or [`isError`](/7.4.0-1/making-requests/hyperresponse#iserror).

If you were previously checking specifically for `504` status codes or [`isServerError`](/7.4.0-1/making-requests/hyperresponse#isservererror) for timed out requests, you need to now either check for `408` status codes, [`isClientError`](/7.4.0-1/making-requests/hyperresponse#isclienterror), or the more general [`isError`](/7.4.0-1/making-requests/hyperresponse#iserror).

## Upgrading from v5 to v6

* The default `Content-Type` header has been removed. You must set this [manually](/7.4.0-1/making-requests/hyperrequest#setcontenttype) or use a format helper, such as [`asJson`](/7.4.0-1/making-requests/hyperrequest#asjson).
* Dropped support for Adobe 2016.

## Upgrading from v4 to v5

`HyperHttpClientInterface` now requires a `debug` method.

```cfscript
/**
 * Return a struct of information showing how the client will execute the HyperRequest.
 * This will be used by a developer to debug any differences between the generated
 * request values and the expected request values.
 *
 * @req     The HyperRequest to debug.
 *
 * @returns A struct of information detailing how the client would execute the HyperRequest.
 */
public struct function debug( required HyperRequest req );
```

## Upgrading from v3 to v4

Previously, query params were stored as a struct.  Some APIs expect multiple values for the same query param name to be passed as separate arguments.  Hyper now stores the query params as an array and provides new methods for interacting with query params:

* [`getQueryParamByName`](/7.4.0-1/making-requests/hyperrequest#getqueryparambyname)
* [`getAllQueryParamsByName`](/7.4.0-1/making-requests/hyperrequest#getallqueryparamsbyname)
* [`withQueryParams`](/7.4.0-1/making-requests/hyperrequest#withqueryparams)
* [`appendQueryParam`](/7.4.0-1/making-requests/hyperrequest#appendqueryparam)
* [`appendQueryParams`](/7.4.0-1/making-requests/hyperrequest#appendqueryparams)
* [`hasQueryParam`](/7.4.0-1/making-requests/hyperrequest#hasqueryparam)

The following methods still exist, but now interact with arrays of query param structs instead of a simple struct.

* [`getQueryParams`](/7.4.0-1/making-requests/hyperrequest#getqueryparams)
* [`setQueryParams`](/7.4.0-1/making-requests/hyperrequest#setqueryparams)

The following methods have been deprecated:

| Deprecated Method                                                      | Replacement Method                                                                 |
| ---------------------------------------------------------------------- | ---------------------------------------------------------------------------------- |
| [`getQueryParam`](/7.4.0-1/making-requests/hyperrequest#getqueryparam) | [`getQueryParamByName`](/7.4.0-1/making-requests/hyperrequest#getqueryparambyname) |

## Upgrading from v2 to v3

Dropped support for ColdBox 5.

## Upgrading from v1 to v2

Dropped support for Lucee 4.5.


# Requirements

Hyper runs on Adobe ColdFusion 2018+ and Lucee 5+.

ColdBox is not required, but mappings are provided for ColdBox users automatically.


# Installation

Hyper is most easily installed via ForgeBox and CommandBox.

```sh
box install hyper
```

If you install Hyper in a non-ColdBox application, make sure to create a mapping in your `Application.cfc`

```cfscript
this.mappings[ "/hyper" ] = expandPath( "/modules/hyper" );
```


# HyperBuilder

A `HyperBuilder` is a singleton factory component that will give you a new [`HyperRequest`](/7.4.0-1/making-requests/hyperrequest) any time you call the `new` method.  It will also create a new [`HyperRequest`](/7.4.0-1/making-requests/hyperrequest) any time you call a method on `HyperBuilder` that exists on [`HyperRequest`](/7.4.0-1/making-requests/hyperrequest).

`HyperBuilder` is the component you want to inject into your singleton components, like handlers or services.  It will ensure you get a fresh [`HyperRequest`](/7.4.0-1/making-requests/hyperrequest) instance on each invocation.  This is important since reusing the same [`HyperRequest`](/7.4.0-1/making-requests/hyperrequest) instance will likely produce unintended results.

You can inject a `HyperBuilder` into your application using the `HyperBuilder@hyper` id.

```cfscript
component {
    
    property name="hyper" inject="HyperBuilder@hyper";

    function index( event, rc, prc ) {
        var reqA = hyper.new();
        // reqA is a new HyperRequest instance.
        
        var reqB = hyper.setUrl( "https://swapi.dev/api/people" );
        // reqB is a new HyperRequest instance with the url set.
    }

}
```

If you are not using ColdBox, you can create a `HyperBuilder` manually:

```cfscript
component {

    function init() {
        variables.hyper = new hyper.models.HyperBuilder();
    }

}
```

Additionally, you can register `HyperBuilder` instances as custom HTTP Clients.

{% content-ref url="/pages/sc1pmftTrug5lkmdOWQS" %}
[Custom HTTP Clients](/7.4.0-1/customizing-hyper/custom-http-clients)
{% endcontent-ref %}

Finally, you can enable faking of requests from any `HyperBuilder` instance.

{% content-ref url="/pages/fDs68ouvcjilusPgzOdw" %}
[Faking Requests](/7.4.0-1/testing/faking-requests)
{% endcontent-ref %}


# HyperRequest

Though the [`HyperBuilder`](/7.4.0-1/making-requests/hyperbuilder) is the component you will most likely inject, `HyperRequest` is the component will you interact with the most. `HyperRequest` provides a fluent interface to configure your HTTP call.

```cfscript
hyper.get( "https//api.github.com/users" );

hyper.setMethod( "PUT" )
    .withHeaders( { "Authorization" = "Bearer #token#" } )
    .setUrl( "https://jsonplaceholder.typicode.com/posts/1" )
    .setBody( {
        title: "New Title"
    } )
    .send();
```

## Defaults

The following are default properties for a `HyperRequest`:

```json
{
    "method": "GET"
    "resolveUrls": false,
    "encodeUrl": true,
    "timeout": 10, // in seconds
    "maximumRedirects": "*", // follow redirects indefinitely
    "bodyFormat": "json",
    "throwOnError": false,
    "headers": { "User-Agent": "HyperCFML/#versionNumber#" }
}
```

## Executing Requests

### `get`

Execute a `GET` request and return a [`HyperResponse`](/7.4.0-1/making-requests/hyperresponse).

| Name        | Type   | Required | Default | Description                                                    |
| ----------- | ------ | -------- | ------- | -------------------------------------------------------------- |
| url         | string | false    | null    | An optional URL to set for the request.                        |
| queryParams | struct | false    | null    | An optional struct of query parameters to set for the request. |

**Return**: [`HyperResponse`](/7.4.0-1/making-requests/hyperresponse)

### `getAsync`

Execute a `GET` request asynchronously. Returns a [ColdBox Future](https://coldbox.ortusbooks.com/digging-deeper/promises-async-programming) that returns a [`HyperResponse`](/7.4.0-1/making-requests/hyperresponse).

<table><thead><tr><th width="162">Name</th><th>Type</th><th>Required</th><th>Default</th><th>Description</th></tr></thead><tbody><tr><td>url</td><td>string</td><td>false</td><td>null</td><td>An optional URL to set for the request.</td></tr><tr><td>queryParams</td><td>struct</td><td>false</td><td>null</td><td>An optional struct of query parameters to set for the request.</td></tr></tbody></table>

**Return**: [`Future`](https://coldbox.ortusbooks.com/digging-deeper/promises-async-programming)`<`[`HyperResponse`](/7.4.0-1/making-requests/hyperresponse)`>`

### `post`

Execute a `POST` request and return a [`HyperResponse`](/7.4.0-1/making-requests/hyperresponse).

| Name | Type   | Required | Default | Description                              |
| ---- | ------ | -------- | ------- | ---------------------------------------- |
| url  | string | false    | null    | An optional URL to set for the request.  |
| body | struct | false    | null    | An optional body to set for the request. |

**Return**: [`HyperResponse`](/7.4.0-1/making-requests/hyperresponse)

### `postAsync`

Execute a `POST` request asynchronously. Returns a [ColdBox Future](https://coldbox.ortusbooks.com/digging-deeper/promises-async-programming) that returns a [`HyperResponse`](/7.4.0-1/making-requests/hyperresponse).

| Name | Type   | Required | Default | Description                              |
| ---- | ------ | -------- | ------- | ---------------------------------------- |
| url  | string | false    | null    | An optional URL to set for the request.  |
| body | struct | false    | null    | An optional body to set for the request. |

**Return**: [`Future`](https://coldbox.ortusbooks.com/digging-deeper/promises-async-programming)`<`[`HyperResponse`](/7.4.0-1/making-requests/hyperresponse)`>`

### `put`

Execute a `PUT` request and return a [`HyperResponse`](/7.4.0-1/making-requests/hyperresponse).

| Name | Type   | Required | Default | Description                              |
| ---- | ------ | -------- | ------- | ---------------------------------------- |
| url  | string | false    | null    | An optional URL to set for the request.  |
| body | struct | false    | null    | An optional body to set for the request. |

**Return**: [`HyperResponse`](/7.4.0-1/making-requests/hyperresponse)

### `putAsync`

Execute a `PUT` request asynchronously. Returns a [ColdBox Future](https://coldbox.ortusbooks.com/digging-deeper/promises-async-programming) that returns a [`HyperResponse`](/7.4.0-1/making-requests/hyperresponse).

| Name | Type   | Required | Default | Description                              |
| ---- | ------ | -------- | ------- | ---------------------------------------- |
| url  | string | false    | null    | An optional URL to set for the request.  |
| body | struct | false    | null    | An optional body to set for the request. |

**Return**: [`Future`](https://coldbox.ortusbooks.com/digging-deeper/promises-async-programming)`<`[`HyperResponse`](/7.4.0-1/making-requests/hyperresponse)`>`

### `patch`

Execute a `PATCH` request and return a [`HyperResponse`](/7.4.0-1/making-requests/hyperresponse).

| Name | Type   | Required | Default | Description                              |
| ---- | ------ | -------- | ------- | ---------------------------------------- |
| url  | string | false    | null    | An optional URL to set for the request.  |
| body | struct | false    | null    | An optional body to set for the request. |

**Return**: [`HyperResponse`](/7.4.0-1/making-requests/hyperresponse)

### `patchAsync`

Execute a `PATCH` request asynchronously. Returns a [ColdBox Future](https://coldbox.ortusbooks.com/digging-deeper/promises-async-programming) that returns a [`HyperResponse`](/7.4.0-1/making-requests/hyperresponse).

| Name | Type   | Required | Default | Description                              |
| ---- | ------ | -------- | ------- | ---------------------------------------- |
| url  | string | false    | null    | An optional URL to set for the request.  |
| body | struct | false    | null    | An optional body to set for the request. |

**Return**: [`Future`](https://coldbox.ortusbooks.com/digging-deeper/promises-async-programming)`<`[`HyperResponse`](/7.4.0-1/making-requests/hyperresponse)`>`

### `delete`

Execute a `DELETE` request and return a [`HyperResponse`](/7.4.0-1/making-requests/hyperresponse).

| Name | Type   | Required | Default | Description                              |
| ---- | ------ | -------- | ------- | ---------------------------------------- |
| url  | string | false    | null    | An optional URL to set for the request.  |
| body | struct | false    | null    | An optional body to set for the request. |

**Return**: [`HyperResponse`](/7.4.0-1/making-requests/hyperresponse)

### `deleteAsync`

Execute a `DELETE` request asynchronously. Returns a [ColdBox Future](https://coldbox.ortusbooks.com/digging-deeper/promises-async-programming) that returns a [`HyperResponse`](/7.4.0-1/making-requests/hyperresponse).

| Name | Type   | Required | Default | Description                              |
| ---- | ------ | -------- | ------- | ---------------------------------------- |
| url  | string | false    | null    | An optional URL to set for the request.  |
| body | struct | false    | null    | An optional body to set for the request. |

**Return**: [`Future`](https://coldbox.ortusbooks.com/digging-deeper/promises-async-programming)`<`[`HyperResponse`](/7.4.0-1/making-requests/hyperresponse)`>`

### `head`

Execute a `HEAD` request and return a [`HyperResponse`](/7.4.0-1/making-requests/hyperresponse).

| Name        | Type   | Required | Default | Description                                                    |
| ----------- | ------ | -------- | ------- | -------------------------------------------------------------- |
| url         | string | false    | null    | An optional URL to set for the request.                        |
| queryParams | struct | false    | null    | An optional struct of query parameters to set for the request. |

**Return**: [`HyperResponse`](/7.4.0-1/making-requests/hyperresponse)

### `headAsync`

Execute a `HEAD` request asynchronously. Returns a [ColdBox Future](https://coldbox.ortusbooks.com/digging-deeper/promises-async-programming) that returns a [`HyperResponse`](/7.4.0-1/making-requests/hyperresponse).

| Name        | Type   | Required | Default | Description                                                    |
| ----------- | ------ | -------- | ------- | -------------------------------------------------------------- |
| url         | string | false    | null    | An optional URL to set for the request.                        |
| queryParams | struct | false    | null    | An optional struct of query parameters to set for the request. |

**Return**: [`Future`](https://coldbox.ortusbooks.com/digging-deeper/promises-async-programming)`<`[`HyperResponse`](/7.4.0-1/making-requests/hyperresponse)`>`

### `options`

Execute an `OPTIONS` request and return a [`HyperResponse`](/7.4.0-1/making-requests/hyperresponse).

| Name        | Type   | Required | Default | Description                                                    |
| ----------- | ------ | -------- | ------- | -------------------------------------------------------------- |
| url         | string | false    | null    | An optional URL to set for the request.                        |
| queryParams | struct | false    | null    | An optional struct of query parameters to set for the request. |

**Return**: [`HyperResponse`](/7.4.0-1/making-requests/hyperresponse)

### `optionsAsync`

Execute an `OPTIONS` request asynchronously. Returns a [ColdBox Future](https://coldbox.ortusbooks.com/digging-deeper/promises-async-programming) that returns a [`HyperResponse`](/7.4.0-1/making-requests/hyperresponse).

| Name        | Type   | Required | Default | Description                                                    |
| ----------- | ------ | -------- | ------- | -------------------------------------------------------------- |
| url         | string | false    | null    | An optional URL to set for the request.                        |
| queryParams | struct | false    | null    | An optional struct of query parameters to set for the request. |

**Return**: [`Future`](https://coldbox.ortusbooks.com/digging-deeper/promises-async-programming)`<`[`HyperResponse`](/7.4.0-1/making-requests/hyperresponse)`>`

### `send`

Send the HTTP request and return a [`HyperResponse`](/7.4.0-1/making-requests/hyperresponse).

| Name         | Type | Required | Default | Description |
| ------------ | ---- | -------- | ------- | ----------- |
| No arguments |      |          |         |             |

**Return**: [`HyperResponse`](/7.4.0-1/making-requests/hyperresponse)

### `sendAsync`

Send the HTTP request asynchronously and return a [ColdBox Future](https://coldbox.ortusbooks.com/digging-deeper/promises-async-programming) that will resolve to a [`HyperResponse`](/7.4.0-1/making-requests/hyperresponse).

| Name         | Type | Required | Default | Description |
| ------------ | ---- | -------- | ------- | ----------- |
| No arguments |      |          |         |             |

**Return**: [`Future`](https://coldbox.ortusbooks.com/digging-deeper/promises-async-programming)`<`[`HyperResponse`](/7.4.0-1/making-requests/hyperresponse)`>`

## Building Requests

### `getRequestId`

Gets the unique request ID representing this request.

| Name         | Type | Required | Default | Description |
| ------------ | ---- | -------- | ------- | ----------- |
| No arguments |      |          |         |             |

**Return**: `String`

### `getFullURL`

Gets the full URL for the request.

| Name            | Type    | Required | Default | Description                                            |
| --------------- | ------- | -------- | ------- | ------------------------------------------------------ |
| withQueryString | boolean | false    | false   | Includes the configured query string with the full URL |

**Return**: `String`

### `getBaseURL`

Gets the base URL for the request. The base URL is combined with the URL when making the request.

| Name         | Type | Required | Default | Description |
| ------------ | ---- | -------- | ------- | ----------- |
| No arguments |      |          |         |             |

**Return**: `String`

### `setBaseURL`

Sets the base URL for the request. The base URL is combined with the URL when making the request.

| Name  | Type   | Required | Default | Description                                                   |
| ----- | ------ | -------- | ------- | ------------------------------------------------------------- |
| value | string | true     |         | The base URL for the request, e.g. `https://api.github.com/`. |

**Return**: `HyperRequest`

### `getURL`

Gets the URL for the request.

| Name         | Type | Required | Default | Description |
| ------------ | ---- | -------- | ------- | ----------- |
| No arguments |      |          |         |             |

**Return**: `String`

### `setURL`

Sets the URL for the request.

| Name  | Type   | Required | Default | Description                                                                                                     |
| ----- | ------ | -------- | ------- | --------------------------------------------------------------------------------------------------------------- |
| value | string | true     |         | The URL for the request. It can either be a full url or a URI resource for use with the baseURL. e.g. `/repos`. |

**Return**: `HyperRequest`

### `setResolveURL`

Sets the resolveURL parameter for the request.

| Name  | Type    | Required | Default | Description                                                                    |
| ----- | ------- | -------- | ------- | ------------------------------------------------------------------------------ |
| value | boolean | false    | false   | Resolves URLs in the response body to absolute URLs, including the port number |

**Return**: `HyperRequest`

### `getMethod`

Gets the HTTP method for the request.

| Name         | Type | Required | Default | Description |
| ------------ | ---- | -------- | ------- | ----------- |
| No arguments |      |          |         |             |

**Return**: `String`

### `setMethod`

Sets the HTTP method for the request.

| Name  | Type   | Required | Default | Description                      |
| ----- | ------ | -------- | ------- | -------------------------------- |
| value | string | true     |         | The HTTP method for the request. |

**Return**: `HyperRequest`

### `withBasicAuth`

Sets the username and password for HTTP Basic Auth.

| Name     | Type   | Required | Default | Description                      |
| -------- | ------ | -------- | ------- | -------------------------------- |
| username | string | true     |         | The username for the basic auth. |
| password | string | true     |         | The password for the basic auth. |

**Return**: `HyperRequest`

### `withCertificateAuth`

Sets the username and password for HTTP Basic Auth.

| Name            | Type   | Required | Default | Description                                              |
| --------------- | ------ | -------- | ------- | -------------------------------------------------------- |
| certificatePath | string | true     |         | The mapped path to the certificate used to authenticate. |
| password        | string | false    |         | The optional password used to decrypt the certificate.   |

**Return**: `HyperRequest`

### `withNTLMAuth`

Sets the username, password, domain and workstation for NTLM Auth.

| Name        | Type   | Required | Default | Description                        |
| ----------- | ------ | -------- | ------- | ---------------------------------- |
| username    | string | true     |         | The username for the NTLM auth.    |
| password    | string | true     |         | The password for the NTLM auth.    |
| domain      | string | true     |         | The domain for the NTLM auth.      |
| workstation | string | true     |         | The workstation for the NTLM auth. |

Workstation can be obtained with `createObject('java','java.net.InetAddress').getLocalHost().getHostName()`

**Return**: `HyperRequest`

### `withRequestCallback`

Schedules a callback to be ran when executing the request.

| Name     | Type     | Required | Default | Description                                     |
| -------- | -------- | -------- | ------- | ----------------------------------------------- |
| callback | function | true     |         | The callback to run when executing the request. |

**Return**: `HyperRequest`

### `withResponseCallback`

Schedules a callback to be ran when receiving the response.

| Name     | Type     | Required | Default | Description                                      |
| -------- | -------- | -------- | ------- | ------------------------------------------------ |
| callback | function | true     |         | The callback to run when receiving the response. |

**Return**: `HyperRequest`

### `getUsername`

Gets the username for the request.

| Name         | Type | Required | Default | Description |
| ------------ | ---- | -------- | ------- | ----------- |
| No arguments |      |          |         |             |

**Return**: `String`

### `setUsername`

Sets the username for the request.

| Name  | Type   | Required | Default | Description                   |
| ----- | ------ | -------- | ------- | ----------------------------- |
| value | string | true     |         | The username for the request. |

**Return**: `HyperRequest`

### `getPassword`

Gets the password for the request.

| Name         | Type | Required | Default | Description |
| ------------ | ---- | -------- | ------- | ----------- |
| No arguments |      |          |         |             |

**Return**: `String`

### `setPassword`

Sets the password for the request.

| Name  | Type   | Required | Default | Description                   |
| ----- | ------ | -------- | ------- | ----------------------------- |
| value | string | true     |         | The password for the request. |

**Return**: `HyperRequest`

### `getTimeout`

Gets the timeout for the request, in seconds.

| Name         | Type | Required | Default | Description |
| ------------ | ---- | -------- | ------- | ----------- |
| No arguments |      |          |         |             |

**Return**: `numeric`

### `setTimeout`

Sets the timeout for the request, in seconds.

| Name  | Type   | Required | Default | Description                              |
| ----- | ------ | -------- | ------- | ---------------------------------------- |
| value | string | true     |         | The timeout for the request, in seconds. |

**Return**: `HyperRequest`

### `withoutRedirecting`

A convenience method to not follow any redirects.

| Name         | Type | Required | Default | Description |
| ------------ | ---- | -------- | ------- | ----------- |
| No arguments |      |          |         |             |

**Return**: `HyperRequest`

### `withoutEncodingUrl`

A convenience method to not encode the url.

{% hint style="warning" %}
**WARNING**: Not supported on Adobe engines.
{% endhint %}

| Name         | Type | Required | Default | Description |
| ------------ | ---- | -------- | ------- | ----------- |
| No arguments |      |          |         |             |

**Return**: `HyperRequest`

### `getMaximumRedirects`

Gets the maximum number of redirects to follow.

| Name         | Type | Required | Default | Description |
| ------------ | ---- | -------- | ------- | ----------- |
| No arguments |      |          |         |             |

**Return**: `numeric | String`

### `setMaximumRedirects`

Sets the maximum number of redirects to follow. A value of `*` will follow redirects infinitely.

| Name  | Type | Required | Default | Description                                |
| ----- | ---- | -------- | ------- | ------------------------------------------ |
| value | any  | true     |         | The maximum number of redirects to follow. |

**Return**: `HyperRequest`

### `getBody`

Gets the body for the request.

| Name         | Type | Required | Default | Description |
| ------------ | ---- | -------- | ------- | ----------- |
| No arguments |      |          |         |             |

**Return**: `any`

### `setBody`

Sets the body for the request. Complex values will be serialized before sending the request.

| Name  | Type | Required | Default | Description               |
| ----- | ---- | -------- | ------- | ------------------------- |
| value | any  | true     |         | The body for the request. |

**Return**: `HyperRequest`

### `hasBody`

Checks if the request has a body.

| Name         | Type | Required | Default | Description |
| ------------ | ---- | -------- | ------- | ----------- |
| No arguments |      |          |         |             |

**Return**: `boolean`

### `getBodyFormat`

Gets the body format for the request.

| Name         | Type | Required | Default | Description |
| ------------ | ---- | -------- | ------- | ----------- |
| No arguments |      |          |         |             |

**Return**: `String`

### `setBodyFormat`

Sets the body format for the request. Recognized values are `formFields`, `json`, or `xml`. It is highly recommended to use `asFormFields`, `asJson`, or `asXML` instead.  If you set this value to a non-recognized value, the body will be passed along as-is to the body of the HTTP request.

| Name  | Type | Required | Default | Description                      |
| ----- | ---- | -------- | ------- | -------------------------------- |
| value | any  | true     |         | The body format for the request. |

**Return**: `HyperRequest`

### `asJson`

A convenience method to set the body format and Content-Type to `json`.

| Name         | Type | Required | Default | Description |
| ------------ | ---- | -------- | ------- | ----------- |
| No arguments |      |          |         |             |

**Return**: `HyperRequest`

### `asFormFields`

A convenience method to set the body format and Content-Type to form fields.

| Name         | Type | Required | Default | Description |
| ------------ | ---- | -------- | ------- | ----------- |
| No arguments |      |          |         |             |

**Return**: `HyperRequest`

### `asXML`

A convenience method to set the body format and Content-Type to `xml`.

| Name         | Type | Required | Default | Description |
| ------------ | ---- | -------- | ------- | ----------- |
| No arguments |      |          |         |             |

**Return**: `HyperRequest`

### `asBinary`

A convenience method to set the body format to `binary` and Content-Type to `application/octet-stream`.

| Name         | Type | Required | Default | Description |
| ------------ | ---- | -------- | ------- | ----------- |
| No arguments |      |          |         |             |

**Return**: `HyperRequest`

### `getReferrer`

Gets the referrer for the request, if any.

| Name         | Type | Required | Default | Description |
| ------------ | ---- | -------- | ------- | ----------- |
| No arguments |      |          |         |             |

**Return**: `String`

### `getHeaders`

Gets the headers for the request.

| Name         | Type | Required | Default | Description |
| ------------ | ---- | -------- | ------- | ----------- |
| No arguments |      |          |         |             |

**Return**: `java.util.LinkedHashMap`

### `setHeaders`

Sets the headers for the request.

| Name  | Type   | Required | Default | Description                  |
| ----- | ------ | -------- | ------- | ---------------------------- |
| value | struct | true     |         | The headers for the request. |

**Return**: `HyperRequest`

### `setHeader`

Set a header for the request.

| Name  | Type   | Required | Default | Description              |
| ----- | ------ | -------- | ------- | ------------------------ |
| name  | string | true     |         | The name of the header.  |
| value | string | true     |         | The value of the header. |

**Return**: `HyperRequest`

### `withHeaders`

Add additional headers to the request.

| Name    | Type   | Required | Default | Description                                |
| ------- | ------ | -------- | ------- | ------------------------------------------ |
| headers | struct | true     |         | A struct of headers to add to the request. |

**Return**: `HyperRequest`

### `forwardHeaders`

Adds specified headers to the request if they exist. Usually used in conjunction with the current CFML request headers.

| Name    | Type   | Required | Default                               | Description                                                                           |
| ------- | ------ | -------- | ------------------------------------- | ------------------------------------------------------------------------------------- |
| names   | array  | true     |                                       | An array of header names to add to the request if they exist in the `headers` struct. |
| headers | struct | false    | `getHTTPRequestData( false ).headers` | A struct of headers to inspect.                                                       |

**Return**: `HyperRequest`

### `hasHeader`

Check if the request has a header with the given name.

| Name | Type   | Required | Default | Description                      |
| ---- | ------ | -------- | ------- | -------------------------------- |
| name | string | true     |         | The name of the header to check. |

**Return**: `boolean`

### `getCookies`

Gets the cookies for the request.

| Name         | Type | Required | Default | Description |
| ------------ | ---- | -------- | ------- | ----------- |
| No arguments |      |          |         |             |

**Return**: `struct<ordered>`

### `setCookies`

Sets the cookies for the request.

| Name  | Type   | Required | Default | Description                  |
| ----- | ------ | -------- | ------- | ---------------------------- |
| value | struct | true     |         | The headers for the request. |

**Return**: `HyperRequest`

### `setCookie`

Set a cookie for the request.

| Name  | Type   | Required | Default | Description              |
| ----- | ------ | -------- | ------- | ------------------------ |
| name  | string | true     |         | The name of the header.  |
| value | string | true     |         | The value of the header. |

**Return**: `HyperRequest`

### `withCookies`

Add additional cookies to the request.

| Name    | Type   | Required | Default | Description                                |
| ------- | ------ | -------- | ------- | ------------------------------------------ |
| cookies | struct | true     |         | A struct of headers to add to the request. |

**Return**: `HyperRequest`

### `withCredentials`

Sends all current cookies along with the request.

| Name         | Type | Required | Default | Description |
| ------------ | ---- | -------- | ------- | ----------- |
| No arguments |      |          |         |             |

**Return**: `HyperRequest`

### `hasCookie`

Check if the request has a cookie with the given name.

| Name | Type   | Required | Default | Description                      |
| ---- | ------ | -------- | ------- | -------------------------------- |
| name | string | true     |         | The name of the header to check. |

**Return**: `boolean`

### `setUserAgent`

A convenience method to set the [`User-Agent` header](https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/User-Agent).

| Name      | Type   | Required | Default | Description                          |
| --------- | ------ | -------- | ------- | ------------------------------------ |
| userAgent | string | true     |         | The User-Agent value for the request |

**Return**: `HyperRequest`

### `setContentType`

A convenience method to set the [`Content-Type` header](https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Content-Type).

| Name | Type   | Required | Default | Description                            |
| ---- | ------ | -------- | ------- | -------------------------------------- |
| type | string | true     |         | The Content-Type value for the request |

**Return**: `HyperRequest`

### `setAccept`

A convenience method to set the [`Accept` header](https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Accept).

| Name | Type   | Required | Default | Description                      |
| ---- | ------ | -------- | ------- | -------------------------------- |
| type | string | true     |         | The Accept value for the request |

**Return**: `HyperRequest`

### `getQueryParams`

Gets the query parameters for the request.

{% hint style="warning" %}
This method returns an array of param structs that is used under the hood by Hyper. You probably want to use [`getQueryParamByName`](#getqueryparambyname) or [`getAllQueryParamsByName`](#getallqueryparamsbyname) instead.
{% endhint %}

| Name         | Type | Required | Default | Description |
| ------------ | ---- | -------- | ------- | ----------- |
| No arguments |      |          |         |             |

**Return**: `array<struct<string, any>>`

### `setQueryParams`

Sets the query parameters for the request.

{% hint style="warning" %}
This method accepts an array of param structs that is used under the hood by Hyper. You probably want to use [`withQueryParams`](#withqueryparams) or [`appendQueryParams`](#appendqueryparams) instead.
{% endhint %}

If needed, param structs have two keys, `name` and `value`.

| Name  | Type  | Required | Default | Description                                                |
| ----- | ----- | -------- | ------- | ---------------------------------------------------------- |
| value | array | true     |         | The query parameters for the as an array of param structs. |

**Return**: `HyperRequest`

### `getQueryParam`

{% hint style="danger" %}
**DEPRECATED:** Use [`getQueryParamByName`](#getqueryparambyname)
{% endhint %}

Gets the first value for a certain query parameter. Returns an empty string if the query parameter does not exist.

| Name | Type   | Required | Default | Description                                                  |
| ---- | ------ | -------- | ------- | ------------------------------------------------------------ |
| name | string | true     |         | The name of the query parameter to retrieve the first value. |

**Return**: `any`

### `getQueryParamByName`

Gets the first value for a certian query parameter. Returns an empty string if the query parameter does not exist.

| Name | Type   | Required | Default | Description                                                  |
| ---- | ------ | -------- | ------- | ------------------------------------------------------------ |
| name | string | true     |         | The name of the query parameter to retrieve the first value. |

**Return**: `any`

### `getAllQueryParamsByName`

Get all the values for a certain query parameter. Returns an empty array if the query parameter does not exist.

| Name | Type   | Required | Default | Description                                                    |
| ---- | ------ | -------- | ------- | -------------------------------------------------------------- |
| name | string | true     |         | The name of the query parameter to retrieve all of its values. |

**Return**: `array<any>`

### `setQueryParam`

Set a query parameter for the request.

{% hint style="info" %}
**Note:** This removes all other query params with the same name.
{% endhint %}

| Name  | Type   | Required | Default | Description                       |
| ----- | ------ | -------- | ------- | --------------------------------- |
| name  | string | true     |         | The name of the query parameter.  |
| value | string | true     |         | The value of the query parameter. |

**Return**: `HyperRequest`

### `appendQueryParam`

Append a query parameter for the request.

| Name  | Type   | Required | Default | Description                       |
| ----- | ------ | -------- | ------- | --------------------------------- |
| name  | string | true     |         | The name of the query parameter.  |
| value | string | true     |         | The value of the query parameter. |

**Return**: `HyperRequest`

### `withQueryParams`

Add additional query parameters to the request.&#x20;

{% hint style="info" %}
**Note:** This will remove any values with duplicate keys prior to adding the new struct of params.
{% endhint %}

| Name        | Type   | Required | Default | Description                                         |
| ----------- | ------ | -------- | ------- | --------------------------------------------------- |
| queryParams | struct | true     |         | A struct of query parameters to add to the request. |

**Return**: `HyperRequest`

### `appendQueryParams`

Appends additional query parameters to the request.

| Name        | Type   | Required | Default | Description                                         |
| ----------- | ------ | -------- | ------- | --------------------------------------------------- |
| queryParams | struct | true     |         | A struct of query parameters to add to the request. |

**Return**: `HyperRequest`

### `hasQueryParam`

Check if the request has a query parameter with the given name.

| Name | Type   | Required | Default | Description                               |
| ---- | ------ | -------- | ------- | ----------------------------------------- |
| name | string | true     |         | The name of the query parameter to check. |

**Return**: `boolean`

### `attach`

Attaches a file to the Hyper request. Also sets the Content-Type as `multipart/form-data`. Multiple files can be attached by calling `attach` multiple times before calling a send method.

| Name     | Type   | Required | Default | Description                                       |
| -------- | ------ | -------- | ------- | ------------------------------------------------- |
| name     | string | true     |         | The name of the file being uploaded.              |
| path     | string | true     |         | The absolute path to the file to be uploaded.     |
| mimeType | string | false    |         | An optional mime type to associate with the file. |

**Return**: `HyperRequest`

### `setThrowOnError`

Sets the throw on error property for the request. If true, statuses in the 4xx and 5xx range will be turned in to exceptions.

| Name  | Type    | Required | Default | Description                           |
| ----- | ------- | -------- | ------- | ------------------------------------- |
| value | boolean | true     |         | The value of the throw on error flag. |

**Return**: `HyperRequest`

### `throwErrors`

A convenience method to throw on errors.

| Name         | Type | Required | Default | Description |
| ------------ | ---- | -------- | ------- | ----------- |
| No arguments |      |          |         |             |

**Return**: `HyperRequest`

### `allowErrors`

A convenience method to not throw on errors.

| Name         | Type | Required | Default | Description |
| ------------ | ---- | -------- | ------- | ----------- |
| No arguments |      |          |         |             |

**Return**: `HyperRequest`

### `clone`

Clones the current request into a new HyperRequest.

| Name         | Type | Required | Default | Description |
| ------------ | ---- | -------- | ------- | ----------- |
| No arguments |      |          |         |             |

**Return**: A new `HyperRequest` instance cloned from this one.

### `clear`

Clears the request of any set values, including defaults passed by the builder.

| Name         | Type | Required | Default | Description |
| ------------ | ---- | -------- | ------- | ----------- |
| No arguments |      |          |         |             |

**Return**: `HyperRequest`

### `when`

Helper to conditionally execute a callback for the `HyperRequest`. This method lets you use conditionals without breaking chaining.

| Name            | Type       | Required | Default | Description                                                                                            |
| --------------- | ---------- | -------- | ------- | ------------------------------------------------------------------------------------------------------ |
| condition       | `boolean`  | `true`   |         | The condition to check.                                                                                |
| successCallback | `function` | `true`   |         | The callback to execute if the condition is true. The callback is passed the `HyperRequest` instance.  |
| failureCallback | `function` | `false`  | `null`  | The callback to execute if the condition is false. The callback is passed the `HyperRequest` instance. |

**Return**: `HyperRequest`

### `retry`

Configures the request to retry failed requests.

| Name      | Type                         | Required | Default | Description                                                                                                                                                                                                                                                                                                                                                                                                                                |
| --------- | ---------------------------- | -------- | ------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------ |
| attempts  | `numeric` / `array<numeric>` | `true`   |         | Either the max number of retry attempts to make or an array containing retry delays between each attempt.  If a numeric value is passed in, the `delay` argument is required.                                                                                                                                                                                                                                                              |
| delay     | `numeric`                    | `false`  |         | The delay to use for each of the `attempts`. This argument is required if `attempts` is a numeric value.  If `attempts` is an array, this value is ignored.                                                                                                                                                                                                                                                                                |
| predicate | `function`                   | `false`  |         | <p>The predicate function to call to determine if a retry should be attempted.<br><br>This function is only called if there are configured retries available.<br><br>To retry a request, this function should return <code>true</code>.<br><br>It is passed the <code>response</code> and <code>request</code> as parameters.<br><br>Additionally, the <code>request</code> can be modified in this method for the next retry attempt.</p> |

**Return**: `HyperRequest`

### `getRetries`

Returns the current retry configuration which is an array of delay times.  A request that needs to be retried will be retried up to the amount of items in this array.  This array can be set using the `retry` method.

{% hint style="warning" %}
In most cases, you do not need to interact with this method directly.  Use the `retry` method instead.
{% endhint %}

| Name         | Type | Required | Default | Description |
| ------------ | ---- | -------- | ------- | ----------- |
| No arguments |      |          |         |             |

**Return**: `array<numeric>`

### `getCurrentRequestCount`

Returns the current request count.  Defaults to `1`. The only time this will increase is if `retries` have been configured for the request.

| Name         | Type | Required | Default | Description |
| ------------ | ---- | -------- | ------- | ----------- |
| No arguments |      |          |         |             |

**Return**: `numeric`

### `getRetryPredicate`

Returns the current callback function that is called to decide if a request should be retried.  This is only called if there are available retries left.

This callback is passed the response and the request as parameters.

A request will be retried if this function returns `true`.

In this function, the passed in request can be modified for the next retry.

{% hint style="warning" %}
In most cases, you do not need to interact with this method directly.  Use the `retry` method instead.
{% endhint %}

| Name         | Type | Required | Default | Description |
| ------------ | ---- | -------- | ------- | ----------- |
| No arguments |      |          |         |             |

**Return**: `numeric`

### `setProperties`

Quickly set many request properties using a struct. The key should be the name of one of the properties on the request, e.g. `url`, `headers`, `method`, `body`.

| Name       | Type   | Required | Default | Description                                                                                                                                   |
| ---------- | ------ | -------- | ------- | --------------------------------------------------------------------------------------------------------------------------------------------- |
| properties | struct | true     |         | A struct of properties to set. Each property name will be set on the request. Properties that don't exist on the request will throw an error. |

**Return**: `HyperRequest`

### `setHttpClient`

Sets the [HTTP Client](/7.4.0-1/customizing-hyper/custom-http-clients) to use for the request. The client should conform to the `HyperHttpClientInterface` (though it does not need to use the `implements` keyword).

| Name       | Type                       | Required | Default | Description                            |
| ---------- | -------------------------- | -------- | ------- | -------------------------------------- |
| httpClient | `HyperHttpClientInterface` | `true`   |         | The httpClient to use for the request. |

**Return**: `HyperRequest`

### `setInterceptorService`

Sets the [ColdBox Interceptor Service](https://coldbox.ortusbooks.com/the-basics/interceptors) to announce request and response interception points. A noop option is provided in the `init` for non-ColdBox usage.

| Name               | Type | Required | Default | Description                                     |
| ------------------ | ---- | -------- | ------- | ----------------------------------------------- |
| interceptorService | any  | `true`   |         | The interceptor service to use for the request. |

**Return**: `HyperRequest`

### `setAsyncManager`

Sets the [ColdBox AsyncManager](https://coldbox.ortusbooks.com/digging-deeper/promises-async-programming) to send requests asynchronously. A noop option is provided in the `init` for non-ColdBox usage.

| Name         | Type | Required | Default | Description                              |
| ------------ | ---- | -------- | ------- | ---------------------------------------- |
| asyncManager | any  | `true`   |         | The asyncManager to use for the request. |

**Return**: `HyperRequest`

### `getMemento`

Returns a struct representing this `HyperRequest`.

| Name         | Type | Required | Default | Description |
| ------------ | ---- | -------- | ------- | ----------- |
| No arguments |      |          |         |             |

**Return**:

```json
{
    "requestID"           : getRequestID(),
    "baseUrl"             : getBaseUrl(),
    "url"                 : getUrl(),
    "fullUrl"             : getFullUrl(),
    "method"              : getMethod(),
    "queryParams"         : getQueryParams(),
    "headers"             : getHeaders(),
    "cookies"             : getCookies(),
    "files"               : getFiles(),
    "bodyFormat"          : getBodyFormat(),
    "body"                : getBody(),
    "referrer"            : isNull( variables.referrer ) ? "" : variables.referrer,
    "throwOnError"        : getThrowOnError(),
    "timeout"             : getTimeout(),
    "maximumRedirects"    : getMaximumRedirects(),
    "authType"            : getAuthType(),
    "username"            : getUsername(),
    "password"            : getPassword(),
    "clientCert"          : isNull( variables.clientCert ) ? "" : variables.clientCert,
    "clientCertPassword"  : isNull( variables.clientCertPassword ) ? "" : variables.clientCertPassword,
    "domain"              : getDomain(),
    "workstation"         : getWorkstation(),
    "resolveUrls"         : getResolveUrls(),
    "encodeUrl"           : getEncodeUrl(),
    "retries"             : getRetries(),
    "currentRequestCount" : getCurrentRequestCount()
};
```

### `debug`

Creates a debug representation of the HTTP request for the current HTTP client.

{% hint style="danger" %}
**Throws**: `NoUrlException` when no URL is set.
{% endhint %}

| Name         | Type | Required | Default | Description |
| ------------ | ---- | -------- | ------- | ----------- |
| No arguments |      |          |         |             |

**Return**: Dependent on the configured HTTP Client.  See specific HTTP Client documentation for details.


# HyperResponse

The `HyperResponse` component is a read-only wrapper to easily grab different information about the response.

### `getResponseId`

Gets the unique response ID representing this response.

| Name         | Type | Required | Default | Description |
| ------------ | ---- | -------- | ------- | ----------- |
| No arguments |      |          |         |             |

**Return**: `String`

### `getStatusCode`

Gets the status code for the response.

| Name         | Type | Required | Default | Description |
| ------------ | ---- | -------- | ------- | ----------- |
| No arguments |      |          |         |             |

**Return**: `numeric`

### `getStatusText`

Gets the status text for the response.

| Name         | Type | Required | Default | Description |
| ------------ | ---- | -------- | ------- | ----------- |
| No arguments |      |          |         |             |

**Return**: `String`

### `getStatus`

Returns the status code and status text as a single string.

| Name         | Type | Required | Default | Description |
| ------------ | ---- | -------- | ------- | ----------- |
| No arguments |      |          |         |             |

**Return**: `String`

### `getData`

Gets the data for the response.

| Name         | Type | Required | Default | Description |
| ------------ | ---- | -------- | ------- | ----------- |
| No arguments |      |          |         |             |

**Return**: `String`

### `getRequestID`

Returns the id of the request to which this response is related.

| Name         | Type | Required | Default | Description |
| ------------ | ---- | -------- | ------- | ----------- |
| No arguments |      |          |         |             |

**Return**: `String`

### `getRequest`

Gets the [HyperRequest](/7.4.0-1/making-requests/hyperrequest) instance associated with this response.

| Name         | Type | Required | Default | Description |
| ------------ | ---- | -------- | ------- | ----------- |
| No arguments |      |          |         |             |

**Return**: [`HyperRequest`](/7.4.0-1/making-requests/hyperrequest)

### `getCharset`

Gets the charset value for the response.

| Name         | Type | Required | Default | Description |
| ------------ | ---- | -------- | ------- | ----------- |
| No arguments |      |          |         |             |

**Return**: `String`

### `getTimestamp`

Gets the timestamp for when this response was received.

| Name         | Type | Required | Default | Description |
| ------------ | ---- | -------- | ------- | ----------- |
| No arguments |      |          |         |             |

**Return**: `DateTime`

### `getExecutionTime`

Gets the execution time of the request, in milliseconds.

| Name         | Type | Required | Default | Description |
| ------------ | ---- | -------- | ------- | ----------- |
| No arguments |      |          |         |             |

**Return**: `numeric`

### `json`

Returns the data of the request as deserialized `JSON`.

{% hint style="danger" %}
**Throws**: `DeserializeJsonException` if the response is not `JSON`.
{% endhint %}

| Name         | Type | Required | Default | Description |
| ------------ | ---- | -------- | ------- | ----------- |
| No arguments |      |          |         |             |

**Return**: `any`

### `isSuccess`

Returns true if the request status code is considered successful.

| Name         | Type | Required | Default | Description |
| ------------ | ---- | -------- | ------- | ----------- |
| No arguments |      |          |         |             |

**Return**: `boolean`

### `isOK`

Returns true if the request status code is `200 OK`.

| Name         | Type | Required | Default | Description |
| ------------ | ---- | -------- | ------- | ----------- |
| No arguments |      |          |         |             |

**Return**: `boolean`

### `isCreated`

Returns true if the request status code is `201 Created`.

| Name         | Type | Required | Default | Description |
| ------------ | ---- | -------- | ------- | ----------- |
| No arguments |      |          |         |             |

**Return**: `boolean`

### `isRedirect`

Returns true if the request status code is considered a redirect.

| Name         | Type | Required | Default | Description |
| ------------ | ---- | -------- | ------- | ----------- |
| No arguments |      |          |         |             |

**Return**: `boolean`

### `isError`

Returns true if the request status code is considered either a client error (4xx status code) or a server error (5xx status code).

| Name         | Type | Required | Default | Description |
| ------------ | ---- | -------- | ------- | ----------- |
| No arguments |      |          |         |             |

**Return**: `boolean`

### `isClientError`

Returns true if the request status code is considered a client error (4xx status code).

| Name         | Type | Required | Default | Description |
| ------------ | ---- | -------- | ------- | ----------- |
| No arguments |      |          |         |             |

**Return**: `boolean`

### `isUnauthorized`

Returns true if the request status code is `401 Unauthorized`.

| Name         | Type | Required | Default | Description |
| ------------ | ---- | -------- | ------- | ----------- |
| No arguments |      |          |         |             |

**Return**: `boolean`

### `isForbidden`

Returns true if the request status code is `403 Forbidden`.

| Name         | Type | Required | Default | Description |
| ------------ | ---- | -------- | ------- | ----------- |
| No arguments |      |          |         |             |

**Return**: `boolean`

### `isNotFound`

Returns true if the request status code is `404 Not Found`.

| Name         | Type | Required | Default | Description |
| ------------ | ---- | -------- | ------- | ----------- |
| No arguments |      |          |         |             |

**Return**: `boolean`

### `isServerError`

Returns true if the request status code is considered a server error (5xx status code).

| Name         | Type | Required | Default | Description |
| ------------ | ---- | -------- | ------- | ----------- |
| No arguments |      |          |         |             |

**Return**: `boolean`

### `hasHeader`

Checks if a header exists in the response.

| Name | Type     | Required | Default | Description                      |
| ---- | -------- | -------- | ------- | -------------------------------- |
| name | `String` | `true`   |         | The name of the header to check. |

**Return**: `boolean`

### `getHeader`

Gets the value of a header from the response.

| Name         | Type     | Required | Default | Description                                       |
| ------------ | -------- | -------- | ------- | ------------------------------------------------- |
| name         | `String` | `true`   |         | The name of the header to retrieve.               |
| defaultValue | `any`    | `false`  | `""`    | The value to return if the header does not exist. |

**Return**: `any`

### `getCookies`

Caches the result of parsing the `Set-Cookie` header and returns it.

| Name         | Type | Required | Default | Description |
| ------------ | ---- | -------- | ------- | ----------- |
| No arguments |      |          |         |             |

**Return**: `struct`

### `persistCookies`

Parses and saves the cookies to the cookie scope.

| Name         | Type | Required | Default | Description |
| ------------ | ---- | -------- | ------- | ----------- |
| No arguments |      |          |         |             |

**Return**: `HyperResponse`

### `getMemento`

Gets a serializable representation of the response.

| Name         | Type | Required | Default | Description |
| ------------ | ---- | -------- | ------- | ----------- |
| No arguments |      |          |         |             |

**Return**:

```json
{
    "responseID"    : getResponseID(),
    "requestID"     : getRequestID(),
    "statusCode"    : getStatusCode(),
    "statusText"    : getStatusText(),
    "status"        : getStatus(),
    "data"          : getData(),
    "charset"       : getCharset(),
    "headers"       : getHeaders(),
    "timestamp"     : getTimestamp(),
    "executionTime" : getExecutionTime(),
    "cookies"       : getCookies()
}
```


# Hyper Clients

Hyper allows you to configure defaults for your requests as custom Hyper Clients. This is particularly useful for reducing boilerplate in your application.

Defaults are set on the `HyperBuilder` instance. The easiest way to do this is to configure it in WireBox. In an `afterAspectsLoad` method, you can get a reference to a `HyperBuilder`, configure it as you would for a request, and then call the `registerAs` method passing in your desired WireBox alias.

```cfscript
// config/WireBox.cfc
component {

   // ...
   
   function afterApsectsLoad() {
       injector.getInstance( "HyperBuilder@hyper" )
           .setBaseUrl( "https://swapi.dev/api" )
           .asJson()
           .registerAs( "StarWarsClient" );
   }

}
```

{% hint style="info" %}
Putting the registration code in `afterAspectsLoad` is required so Hyper can be loaded and available for injection.
{% endhint %}

Now, you can inject this pre-configured builder wherever you need in your application:

```js
component {

    property name="StarWarsClient" inject="StarWarsClient";

    function findUser( id ) {
        return variables.StarWarsClient.get( "/people/#id#" );
    }

}
```

You can alternatively create the clients by passing in the desired defaults to the `initWith` method of a WireBox mapping.  These arguments must match the [`HyperRequest` property names](#hyperrequest-property-names).

```js
// config/WireBox.cfc
component {

    function configure() {
        map( "StarWarsClient" )
            .to( "hyper.models.HyperBuilder" )
            .asSingleton()
            .initWith(
                baseUrl = "https://swapi.dev/api"
            );
    }

}
```

You can even create multiple clients using this approach:

```js
// config/WireBox.cfc
component {

    function configure() {
        // ...
    }

    function afterAspectsLoad() {
        injector.getInstance( "HyperBuilder@hyper" )
           .setBaseUrl( "https://swapi.dev/api" )
           .asJson()
           .registerAs( "StarWarsClient" );

       injector.getInstance( "HyperBuilder@hyper" )
           .setBaseUrl( "https://api.github.com" )
           .asJson()
           .withHeaders( {
               "Authorization": coldbox.getUtil().getSystemSetting( "GITHUB_TOKEN" )
           } )
           .registerAs( "GitHubClient" );
    }

}
```

You can also set or change the defaults by either passing the key / value pairs in to the `init` method or by calling the appropriate `HyperRequest` method on the `HyperBuilder.defaults` property.

```js
var hyper = new Hyper.models.HyperBuilder(
    baseUrl = "https://api.github.com"
);
hyper.defaults.withHeaders( { "Authorization" = token } );
```

#### HyperRequest property names

```cfscript
/**
* The httpClient to use for the request
*/
property name="httpClient";

/**
* The baseURL for the request.
* e.g. https://api.github.com/
*/
property name="baseUrl" default="";

/**
* The URL for the request.
* It can either be a full url
* or a URI resource for use with the baseURL.
* e.g. /repos
*/
property name="url" default="";

/**
* Setting this to true will change all relative urls in the document to absolute.
*/
property name="resolveUrls" default="false";

/**
* Setting this to false will not automatically encode the url passed.
* WARNING: Setting this to false is not supported on Adobe engines.
*/
property name="encodeUrl" default="true";

/**
* The HTTP method for the request.
*/
property name="method" default="GET";

/**
* The username for the request for basic auth.
*/
property name="username" default="";

/**
* The password for the request for basic auth.
*/
property name="password" default="";

/**
* Timeout, in seconds, for the request.
*/
property name="timeout" default="10";

/**
* The maximum number of redirects to follow.
* A value of `*` will follow redirects infinitely.
*/
property name="maximumRedirects" default="*";

/**
* The body to send with the request.
* How the body is serialized is
* determined by the bodyFormat.
*/
property name="body" default="";

/**
* The format to serialize the body.
* e.g. `json` or `formFields`
*/
property name="bodyFormat" default="json";

/**
* The referring response in the case of redirects.
*/
property name="referrer";

/**
* A struct of headers for the request.
*/
property name="headers";

/**
* A struct of query parameters for the request.
*/
property name="queryParams";

/**
* Flag to throw on a cfhttp error.
*/
property name="throwOnError" default="false";

/**
* The full path to a PKCS12 format file that contains the client certificate for the request.
*/
property name="clientCert";

/**
* 	Password used to decrypt the client certificate.
*/
property name="clientCertPassword";

/**
* The domain for the request for NTLM auth.
*/
property name="domain" default="";

/**
* The workstation for the request for NTLM auth.
*/
property name="workstation" default="";

/**
* The authType for the request
*/
property name="authType" default="BASIC";

/**
* An array of callback functions to call
* before firing off a request.
*/
property name="requestCallbacks" type="array";

/**
* An array of callback functions to call
* after receiving a response.
*/
property name="responseCallbacks" type="array";
```

If you need per-request or per-response manipulation of defaults, use the [`requestCallbacks`](/7.4.0-1/making-requests/hyperrequest#withrequestcallback) and [`responseCallbacks`](/7.4.0-1/making-requests/hyperrequest#withresponsecallback) hooks.

```cfscript
map( "ApiClient" )
    .to( "hyper.models.HyperBuilder" )
    .asSingleton()
    .initWith(
        baseUrl = getColdBox().getUtil().getSystemSetting( "API_URL" ),
        requestCallbacks = [
            // provide the current user's token for the request
            function( req ) {
                var auth = getWireBox().getInstance( "AuthenticationService@cbauth" );
                req.withHeaders( "Authorization", auth.user().getApiToken() );
            }
        ],
        responseCallbacks = [
            // map custom `error` property to an exception
            function ( res ) {
                if ( !res.isError() ) {
                    return;
                }
                
                var body = res.json();
                throw(
                    type = "ApiError",
                    message = body.error.message,
                    detail = body.error.code
                );
            }
        ]
    );
```


# Custom HTTP Clients

By default, Hyper makes HTTP requests using `cfhttp` under the hood.  This can be swapped out by any compatible HTTP client that follows the `HyperHttpClientInterface`.

```cfscript
/**
 * Responsible for executing the HyperRequest and mapping it to a HyperResponse
 */
interface displayname="HyperHttpClientInterface" {

	/**
	 * Execute the HyperRequest and map it to a HyperResponse.
	 *
	 * @req     The HyperRequest to execute.
	 *
	 * @returns A HyperResponse of the executed request.
	 */
	public HyperResponse function send( required HyperRequest req );

	/**
	 * Return a struct of information showing how the client will execute the HyperRequest.
	 * This will be used by a developer to debug any differences between the generated
	 * request values and the expected request values.
	 *
	 * @req     The HyperRequest to debug.
	 *
	 * @returns A struct of information detailing how the client would execute the HyperRequest.
	 */
	public struct function debug( required HyperRequest req );

}
```


# CfhttpHttpClient

### `debug`

Return a struct of information showing how the client will execute the [`HyperRequest`](/7.4.0-1/making-requests/hyperrequest). This will be used by a developer to debug any differences between the generated request values and the expected request values.

| Name | Type                                                    | Required | Default | Description                                                           |
| ---- | ------------------------------------------------------- | -------- | ------- | --------------------------------------------------------------------- |
| req  | [`HyperRequest`](/7.4.0-1/making-requests/hyperrequest) | `true`   |         | The [`HyperRequest`](/7.4.0-1/making-requests/hyperrequest) to debug. |

**Return**:

```json
{
    "attributes" : attrCollection,
    "body"       : {
        "headers" : cfhttpHeaders,
        "params"  : cfhttpParams,
        "files"   : cfhttpFiles,
        "body"    : cfhttpBody,
        "cookies" : cfhttpCookies
    }
}
```


# Faking Requests

Hyper has the ability to fake requests and return fake responses as a result.  This is perfect for [testing](https://testbox.ortusbooks.com/) scenarios where you don't actually want to make an HTTP request.

{% hint style="warning" %}
Non-ColdBox users will need to add a mapping to the [`Globber`](https://forgebox.io/view/globber) dependency included with Hyper.

```cfscript
// Application.cfc
component {
    this.mappings[ "/globber" ] = "/path/to/hyper" & "/modules/globber";
}
```

{% endhint %}

## Faking All Requests

Faking is enabled on a [`HyperBuilder`](/7.4.0-1/making-requests/hyperbuilder) instance, either the built-in one provided by Hyper or a [custom Hyper client](/7.4.0-1/customizing-hyper/custom-http-clients) you have created.

To enable faking requests, call the `fake` method:

```cfscript
var hyper = new Hyper.models.HyperBuilder();
hyper.fake();
```

After calling the `fake` method, all requests created by this `HyperBuilder` will be faked.  By default, they will return `200 OK` responses with empty bodies.

```cfscript
hyper.fake();
var res = hyper.get( "https://google.com" );
expect( res.getStatus() ).toBe( "200 OK" );
```

## Fake Configuration

When calling the `fake` method, you can provide a struct mapping URL patterns to response generator functions.

```cfscript
hyper.fake( {
    "https://google.com/*": function( newFakeResponse, req ) {
         return newFakeResponse( 404, "Not Found" );
    }
} );
```

The key is a URL pattern.  The pattern can be any valid glob. If the pattern is matched by the [`fullUrl`](/7.4.0-1/making-requests/hyperrequest#getfullurl) of the `HyperRequest`, then the response generator function will be called and the results returned.

A helper function, `newFakeResponse`, is provided as the first argument to the response generator function.  The current request is provided as the second argument.

## FakeHyperResponse

The resposne generator function must return a `FakeHyperResponse` instance.  A `FakeHyperResponse` instance acts similar to a normal `HyperResponse` except the properties are not read only.  Once you have an instance of your `FakeHyperResponse`, you can continue to set any properties you need.

```cfscript
hyper.fake( {
    "https://jsonplaceholder.typicode.com/posts": function( newFakeResponse, req ) {
         return newFakeResponse()
             .setStatusCode( 201 )
             .setStatusText( "Created" )
             .setData( serializeJSON( {
                 "id": 101,
                 "title": "foo",
                 "body": "bar",
                 "userId": 1
             } ) );
    }
} );
```

You can also pass the values to the `newFakeResponse` function, if you'd like.

```cfscript
hyper.fake( {
    "https://jsonplaceholder.typicode.com/posts": function( newFakeResponse, req ) {
         return newFakeResponse( 201, "Created", serializeJSON( {
             "id": 101,
             "title": "foo",
             "body": "bar",
             "userId": 1
         } ) );
    }
} );
```

### `newFakeResponse`

Creates a new `FakeHyperResponse` instance.

<table><thead><tr><th width="160">Name</th><th>Type</th><th>Required</th><th>Default</th><th>Description</th></tr></thead><tbody><tr><td>statusCode</td><td><code>numeric</code></td><td><code>false</code></td><td>200</td><td>The status code for the fake response.</td></tr><tr><td>statusText</td><td><code>string</code></td><td><code>false</code></td><td><code>"OK"</code></td><td>The status text for the fake response.</td></tr><tr><td>data</td><td><code>string</code></td><td><code>false</code></td><td><code>""</code></td><td>The data for the fake response.</td></tr><tr><td>headers</td><td><code>{ string: string }</code></td><td><code>false</code></td><td><code>{}</code></td><td>The headers for the fake response.</td></tr><tr><td>executionTime</td><td><code>numeric</code></td><td><code>false</code></td><td>0</td><td>The execution time for the fake response.</td></tr><tr><td>charset</td><td><code>string</code></td><td><code>false</code></td><td><code>"UTF-8"</code></td><td>The charset for the fake response.</td></tr><tr><td>timestamp</td><td><code>datetime</code></td><td><code>false</code></td><td><code>now()</code></td><td>The timestamp of the fake response.</td></tr></tbody></table>

**Return**: `FakeHyperResponse`

## Sequencing Fake Responses

In addition to returning a single `FakeHyperResponse` per pattern, you can return an array of `FakeHyperResponse` instances.  These will be returned in a sequence.

```cfscript
hyper.fake( {
    "https://jsonplaceholder.typicode.com/posts": function( newFakeResponse, req ) {
         return [
             newFakeResponse( 201, "Created", serializeJSON( {
                 "id": 101,
                 "title": "foo",
                 "body": "bar",
                 "userId": 1
             } ) ),
             newFakeResponse( 422, "Unprocessable Entity", "Duplicate title" )
         ];
    }
} );

var resA = hyper.post( "https://jsonplaceholder.typicode.com/posts", { /* ... */ } );
expect( resA.getStatus() ).toBe( "201 Created" );

var resB = hyper.post( "https://jsonplaceholder.typicode.com/posts", { /* ... */ } );
expect( resA.getStatus() ).toBe( "422 Unprocessable Entity" );
```

If you continue to make requests to the same pattern after the sequence has been exhausted, an exception will be thrown.

```cfscript
hyper.fake( {
    "https://jsonplaceholder.typicode.com/posts": function( newFakeResponse, req ) {
         return [
             newFakeResponse( 201, "Created", serializeJSON( {
                 "id": 101,
                 "title": "foo",
                 "body": "bar",
                 "userId": 1
             } ) ),
             newFakeResponse( 422, "Unprocessable Entity", "Duplicate title" )
         ];
    }
} );

var resA = hyper.post( "https://jsonplaceholder.typicode.com/posts", { /* ... */ } );
expect( resA.getStatus() ).toBe( "201 Created" );

var resB = hyper.post( "https://jsonplaceholder.typicode.com/posts", { /* ... */ } );
expect( resA.getStatus() ).toBe( "422 Unprocessable Entity" );

// THROWS a `HyperFakeSequenceExhausted` exception
var resC = hyper.post( "https://jsonplaceholder.typicode.com/posts", { /* ... */ } );
```

## Preventing Stray Requests

By default, Hyper returns a default `FakeHyperResponse` for every request that doesn't match one of your configured patterns.  You can instead cause Hyper to throw an exception if it encounters one of these stray requests by calling the `preventStrayRequests` method.

```cfscript
hyper.fake( {
    "https://google.com/*": function( newFakeResponse, req ) {
         return newFakeResponse( 404, "Not Found" );
    }
} ).preventStrayRequests();

// THROWS a `HyperFakeStrayRequest` exception
var res = hyper.get( "https://github.com" );
```

## Making Assertions

In addition to assertions made against the `FakeHyperResponse` instances returned, you can also make assertions using the `HyperBuilder` instance you faked.  These come in the form of methods on the `HyperBuilder` instance as well as custom TestBox Assertions.

### HyperBuilder Method Assertions

The following methods are available to make assertions in your tests about the requests that were sent.

#### getFakeRequestCount

Returns the number of fake requests that have been made.

| Name         | Type | Required | Default | Description |
| ------------ | ---- | -------- | ------- | ----------- |
| No arguments |      |          |         |             |

**Return**: `numeric`

#### wasRequestSent

Returns whether a request has been made that matches the `predicate`. Each request that has been made is passed to the `predicate` in order. If the `predicate` returns `true`, the request is considered a match and `true` is returned. If no request passes the `predicate`, `false` is returned.

| Name      | Type       | Required | Default | Description                                                                                            |
| --------- | ---------- | -------- | ------- | ------------------------------------------------------------------------------------------------------ |
| predicate | `function` | `true`   |         | A callback function that returns true if the request matches the criteria and returns false otherwise. |

**Return**: `boolean`

### Custom TestBox Assertions

You can register [custom TestBox assertions](https://testbox.ortusbooks.com/in-depth/expectations/custom-matchers) provided by Hyper for more readable tests and test failure messages.

You must [register](https://testbox.ortusbooks.com/in-depth/expectations/custom-matchers#cfc-matchers) these assertions before using them.

```cfscript
component extends="testbox.system.BaseSpec" {

    function beforeAll() {
        addMatchers( "hyper.models.TestBoxMatchers" )
    }
    
    function run() {
        // ...
    }

}
```

The following custom assertions are provided:

#### toHaveSentRequest

This takes in the `HyperBuilder` instance as the actual and a predicate function as the expected. The predicate function is passed to the `HyperBuilder` instance's `wasRequestSent` method.

```cfscript
hyper.fake();

hyper.get( "https://google.com" );

expect( hyper ).toHaveSentRequest( function( req ) {
    return req.getFullUrl( "https://google.com" );
} );

expect( hyper ).notToHaveSentRequest( function( req ) {
    return req.getFullUrl( "https://github.com" );
} );
```

#### toHaveSentCount

This takes in the `HyperBuilder` instance as the actual and an integer number of requests that should have been sent.

```cfscript
hyper.fake();

hyper.get( "https://google.com" );

expect( hyper ).toHaveSentCount( 1 );
expect( hyper ).notToHaveSentCount( 2 );
```

#### toHaveSentNothing

This takes in the `HyperBuilder` instance as the actual and no other parameters.

```cfscript
hyper.fake();

expect( hyper ).toHaveSentNothing();

hyper.get( "https://google.com" );

expect( hyper ).notToHaveSentNothing();
```

## Resetting the Builder

To reset the sent request counts and sequences but keep the fake configuration, use the `resetFakes` method:

```javascript
hyper.fake();

hyper.get( "https://google.com" );

expect( hyper ).toHaveSentCount( 1 );

hyper.resetFakes();

expect( hyper ).toHaveSentNothing();
```

To reset the `HyperBuilder` instance to normal operation call the `clearFakes` method:

```cfscript
hyper.fake();

hyper.get( "https://google.com" );

hyper.clearFakes();
```

{% hint style="info" %}
These are useful methods to call in an [`afterEach`](https://testbox.ortusbooks.com/in-depth/life-cycle-methods/bdd#aftereach-body-data) block in TestBox to make sure you are only faking requests when you want to.
{% endhint %}


# Introduction

## A CFML HTTP Builder

### Inspiration

Hyper was built after coding several API SDK's for various platforms — [S3SDK](https://github.com/coldbox-modules/s3sdk), [cbstripe](https://github.com/coldbox-modules/cbox-stripe), and [cbgithub](https://github.com/elpete/cbgithub), to name a few. We noticed that we spent a lot of time setting up the plumbing for the requests and a wrapper around `cfhttp`. Each implementation was mostly the same but slightly different. It was additionally frustrating because we really only needed to tweak a few values, usually just the `Authorization` header. It would be nice to create an HTTP client pre-configured for each of these SDK's. It seemed the perfect fit for a module.

### The problem it solves

Hyper exists to provide a fluent builder experience for HTTP requests and responses. It also provides a powerful way to create clients, i.e. Builder objects with pre-configured defaults like a base URL or certain headers.


# What's New?

## 8.0.2

Removed unused API docs build in the CI process.

## 8.0.1

* Ensure backwards compatibility with ColdBox versions before 6.
* Various tests and CI updates.

## 8.0.0

v8.0.0 was released as a mistake in the build process. By the time it was realized, other people had already started using it, so removing it would cause even more issues.  So, it's staying around, even without any changes at all.

## 7.5.3

Certify for BoxLang

## 7.5.2

Add ability to exclude keys from [`HyperRequest`](/8.0.0/making-requests/hyperrequest#getmemento) and [`HyperResponse`](/8.0.0/making-requests/hyperresponse#getmemento) mementos.

## 7.5.1

Updated misspelled and missing docblocks.

## 7.5.0

### Request available in \`onHyperResponse\` interception point.

Although this was already available by calling `response.getRequest()`, the request is now available as the second parameter of the [`onHyperResponse` interceptor](/8.0.0/customizing-hyper/interceptors#onhyperresponse).

## 7.4.0

### asBinary

Added a [convenience method](/8.0.0/making-requests/hyperrequest#asbinary) to set the `bodyFormat` to `binary` and the `Content-Type` to `application/octet-stream`.

## 7.3.0

### Retrying Failed Requests

You can now configure a `HyperRequest` to automatically retry failed requests.  [See the `HyperRequest` docs for details.](/8.0.0/making-requests/hyperrequest#retry)

### Default User-Agent

Hyper now sends a default User-Agent of `HyperCFML/#versionNumber#`.

### Reset Fake Request Counts and Sequences

Hyper can now reset the fake request counts and sequences without losing the fake configuration using the [`resetFakes`](/8.0.0/testing/faking-requests#resetting-the-builder) method.

## 7.2.0

### Cookies

Hyper can now [send cookies with a request](/8.0.0/making-requests/hyperrequest#withcookies) and [parse the returned cookies from a response](/8.0.0/making-requests/hyperresponse#getcookies). See the [HyperRequest](/8.0.0/making-requests/hyperrequest) and [HyperResponse](/8.0.0/making-requests/hyperresponse) docs for details.

## 7.1.0

### Fake Requests

Hyper now has the ability to fake requests and return fake responses as a result.  This is perfect for testing scenarios where you don't actually want to make an HTTP request.

{% content-ref url="/pages/fDs68ouvcjilusPgzOdw" %}
[Faking Requests](/8.0.0/testing/faking-requests)
{% endcontent-ref %}

### Custom Hyper Clients

It is now more straightforward to register a [custom Hyper client](/8.0.0/customizing-hyper/custom-http-clients).  Inside your `config/WireBox.cfc` in an `afterAspectsLoad` method, you can get a reference to a `HyperBuilder`, configure it as you would for a request, and then call the `registerAs` method passing in your desired WireBox alias.

```cfscript
// config/WireBox.cfc
component {

   // ...
   
   function afterApsectsLoad() {
       injector.getInstance( "HyperBuilder@hyper" )
           .setBaseUrl( "https://api.github.com" )
           .asJson()
           .withHeaders( {
               "Authorization": coldbox.getUtil().getSystemSetting( "GITHUB_TOKEN" )
           } )
           .registerAs( "GitHubClient" );
   }

}
```

This is a welcome improvement as the `init` arguments do not exactly match the method names.  Also, for defaults like `requestCallbacks`, `responseCallbacks`, or even `queryParams`, passing in arrays of functions or arrays or structs is not as straightforward as calling the related methods.  Now, you can use the Hyper methods you are familiar with when registering your custom Hyper clients.

{% hint style="info" %}
Putting the registration code in `afterAspectsLoad` is required so Hyper can be loaded and available for injection.
{% endhint %}

## 7.0.0

### CFHttp HTTP Client

This client now returns more accurate status codes for `502 Bad Gateway` and `408 Request Timeout` responses.

Previously, these responses were returned as `504 Gateway Timeout` responses. Hyper now normalizes the responses from the different CFML engines into a consistent response. `502 Bad Gateway` is returned instead of `504 Gateway Timeout` for invalid hosts. `408 Request Timeout` is returned if the request takes longer than the configured [`timeout`](/8.0.0/making-requests/hyperrequest#settimeout) value.

### Breaking Changes

If you were previously checking specifically for `504` status codes for bad hosts, you need to now either check for `502` status codes or use a more general method, like [`isServerError`](/8.0.0/making-requests/hyperresponse#isservererror) or [`isError`](/8.0.0/making-requests/hyperresponse#iserror).

If you were previously checking specifically for `504` status codes or [`isServerError`](/8.0.0/making-requests/hyperresponse#isservererror) for timed out requests, you need to now either check for `408` status codes, [`isClientError`](/8.0.0/making-requests/hyperresponse#isclienterror), or the more general [`isError`](/8.0.0/making-requests/hyperresponse#iserror).

## 6.1.0

Add [`head`](/8.0.0/making-requests/hyperrequest#head) and [`options`](/8.0.0/making-requests/hyperrequest#options) shortcut methods.

## 6.0.0

* Add `xml` support and an `asXML` method to set the body format and `Content-Type` header.
* Add `adobe@2023` to testing matrix.

### Breaking Changes

* Remove default `Content-Type` header. You must set this [manually](/8.0.0/making-requests/hyperrequest#setcontenttype) or use a format helper, such as [`asJson`](/8.0.0/making-requests/hyperrequest#asjson).
* Dropped `adobe@2016` support.

## 5.0.1

Correctly handle cases when the `body` is a string and format is `JSON`.

## 5.0.0

Add a `debug` method to see what the HTTP client generates.

### Breaking Changes

`HyperHttpClientInterface` now requires a `debug` method.

```cfscript
/**
 * Return a struct of information showing how the client will execute the HyperRequest.
 * This will be used by a developer to debug any differences between the generated
 * request values and the expected request values.
 *
 * @req     The HyperRequest to debug.
 *
 * @returns A struct of information detailing how the client would execute the HyperRequest.
 */
public struct function debug( required HyperRequest req );
```

## 4.0.3

* Do not prepend the base url when a full url is passed.
* Add `resolveUrls` and `encodeUrl` properties to the [memento](/8.0.0/making-requests/hyperrequest#getmemento).
* Correctly set the `encodeUrl` property when cloning a request.

## 4.0.2

Update README for builder `initWith` headers losing `Content-Type`.

## 4.0.1

Fix `HyperBuilder` example in the docs.

## 4.0.0

Allow adding multiple query params with the same key.

### Breaking Changes

Previously, query params were stored as a struct.  Some APIs expect multiple values for the same query param name to be passed as separate arguments.  Hyper now stores the query params as an array and provides new methods for interacting with query params:

* [`getQueryParamByName`](/8.0.0/making-requests/hyperrequest#getqueryparambyname)
* [`getAllQueryParamsByName`](/8.0.0/making-requests/hyperrequest#getallqueryparamsbyname)
* [`withQueryParams`](/8.0.0/making-requests/hyperrequest#withqueryparams)
* [`appendQueryParam`](/8.0.0/making-requests/hyperrequest#appendqueryparam)
* [`appendQueryParams`](/8.0.0/making-requests/hyperrequest#appendqueryparams)
* [`hasQueryParam`](/8.0.0/making-requests/hyperrequest#hasqueryparam)

The following methods still exist, but now interact with arrays of query param structs instead of a simple struct.

* [`getQueryParams`](/8.0.0/making-requests/hyperrequest#getqueryparams)
* [`setQueryParams`](/8.0.0/making-requests/hyperrequest#setqueryparams)

The following methods have been deprecated:

| Deprecated Method                                                    | Replacement Method                                                               |
| -------------------------------------------------------------------- | -------------------------------------------------------------------------------- |
| [`getQueryParam`](/8.0.0/making-requests/hyperrequest#getqueryparam) | [`getQueryParamByName`](/8.0.0/making-requests/hyperrequest#getqueryparambyname) |

## 3.6.2

Convert array values correctly when sending form fields

## 3.6.1

Add a workaround for CommandBox not having the `box:asyncManager` injection DSL.

## 3.6.0

Add async requests using ColdBox's [AsyncManager](https://coldbox.ortusbooks.com/digging-deeper/promises-async-programming).

## 3.5.0

* Provide more useful error than cfhttp when [`throwOnErrors`](/8.0.0/making-requests/hyperrequest#throwerrors) is enabled.
* Provide mementos for [HyperRequest](/8.0.0/making-requests/hyperrequest#getmemento) and [HyperResponse](/8.0.0/making-requests/hyperresponse#getmemento) instances.
* Capture [statusText](/8.0.0/making-requests/hyperresponse#getstatustext) and provide a [status](/8.0.0/making-requests/hyperresponse#getstatus) convenience string.

## 3.4.2

Add MIT License file

## 3.4.1

Use `processState` over `announce` until CommandBox can update its `interceptorService`.

## 3.4.0

### HyperRequest

* Add [`forwardHeaders`](/8.0.0/making-requests/hyperrequest#forwardheaders) shortcut method.

### HyperResponse

* Allow for default values in [`getHeader`](/8.0.0/making-requests/hyperresponse#getheader).
* Add helper methods for checking for specific status codes:
  * [`isOk`](/8.0.0/making-requests/hyperresponse#isok)
  * [`isUnauthorized`](/8.0.0/making-requests/hyperresponse#isunauthorized)
  * [`isForbidden`](/8.0.0/making-requests/hyperresponse#isforbidden)
  * [`isNotFound`](/8.0.0/making-requests/hyperresponse#isnotfound)

## 3.3.0

Allowing [attaching](/8.0.0/making-requests/hyperrequest#attach) file uploads.

## 3.2.1

Support WireBox outside of ColdBox.

## 3.2.0

Include response data as detail in `DeserializeJsonException`.

## 3.1.0

* Add [`clone`](/8.0.0/making-requests/hyperrequest#clone) to quickly copy `HyperRequest` instances.
* Add interceptors and [local](/8.0.0/making-requests/hyperrequest#withrequestcallback) [callbacks](/8.0.0/making-requests/hyperrequest#withresponsecallback) for lifecycle events.

## 3.0.0

Add execution time to `HyperResponse` instances.

### Breaking Changes

Dropped support for ColdBox 5.

## 2.3.11

* Add support for [NTLM authentication](/8.0.0/making-requests/hyperrequest#withntlmauth).
* Include [`getFullURL`](/8.0.0/making-requests/hyperrequest#getfullurl) method in docs.

## 2.3.10

Fixed typo of `Bulider` to `Builder`.

## 2.3.9

Add [`withoutEncodingUrl`](/8.0.0/making-requests/hyperrequest#withoutencodingurl) flag.

## 2.3.8

Do not fail fast on cron job actions on CI.

## 2.3.7

Update fetch-depth for tests and release actions on CI.

## 2.3.6

Attempt to skip committing back changes on CI.

## 2.3.5

Add matrix and cron testing on CI.

## 2.3.4

Use better GitHub token on CI

## 2.3.1

Add workaround for `boolean` values in query strings.

## 2.3.0

Add [certificate](/8.0.0/making-requests/hyperrequest#withcertificateauth) auth.

## 2.2.1

Use the previous host for redirect if redirect does not include a full URL.

## 2.2.0

Add [`resolveUrls`](/8.0.0/making-requests/hyperrequest#setresolveurl) flag.

## 2.1.1

* Use OpenJDK instead of OracleJDK on CI.
* Store module in [ForgeBox Storage](https://commandbox.ortusbooks.com/5.6.0/developing-for-commandbox/commands).

## 2.1.0

Allow for pluggable [HTTP Clients](/8.0.0/customizing-hyper/custom-http-clients) that follow the `HyperHttpClientInterface`. (Clients do not need to use the `implements` keyword.)

## 2.0.2

Avoid double encoding using [`cfhttpparam`](https://cfdocs.org/cfhttpparam).

## 2.0.1

Remove Lucee 4.5 support from docs. (Support was dropped in [v2.0.0](#2.0.0))

## 2.0.0

* Do not include [`username`](/8.0.0/making-requests/hyperrequest#setusername) and [`password`](/8.0.0/making-requests/hyperrequest#setpassword) unless they have values.
* Add `adobe@2018` support to CI builds.

### Breaking Changes

Dropped support for `lucee@4.5`.

## 1.15.0

Add [`throwOnError`](/8.0.0/making-requests/hyperrequest#throwerrors) flag.

## 1.14.5

Use `504 Gateway Timeout` for incomplete responses.

## 1.14.4

Include equal signs in query param values.

## 1.14.0 – 1.0.0

### New Features

* Add [`when`](/8.0.0/making-requests/hyperrequest#when) helper to execute conditions without breaking chaining.
* Add [`clear`](/8.0.0/making-requests/hyperrequest#clear) method to reset HyperRequest instances.
* Add configurable [`timeout`](/8.0.0/making-requests/hyperrequest#settimeout).

### Bug Fixes

* Fix for Lucee 4 compatibility on `LinkedHashMaps` and `keyArray`.
* Preserve case in header names.
* Preserve case for query parameters.
* Serialize both params from the url and set on the `HyperRequest` instance.
* Default to `UTF-8` charset if none is present in the response.
* Fix withHeaders and withQueryParams for Lucee compatibility.
* Only map HyperBuilder as a singleton in WireBox

### Other

* Migrate to [coldbox-modules](https://github.com/coldbox-modules) organization on GitHub.
* Update `box.json` description.
* Enable [CommandBox Semantic Release](https://forgebox.io/view/commandbox-semantic-release) on CI.


# Upgrade Guide

## Upgrading from v7 to v8

This will be your easiest upgrade ever — there's nothing to do!

v8.0.0 was released as a mistake in the build process. By the time it was realized, other people had already started using it, so removing it would cause even more issues.  So, it's staying around, even without any changes at all.

## Upgrading from v6 to v7

### CFHttp HTTP Client

This client now returns more accurate status codes for `502 Bad Gateway` and `408 Request Timeout` responses.

If you were previously checking specifically for `504` status codes for bad hosts, you need to now either check for `502` status codes or use a more general method, like [`isServerError`](/8.0.0/making-requests/hyperresponse#isservererror) or [`isError`](/8.0.0/making-requests/hyperresponse#iserror).

If you were previously checking specifically for `504` status codes or [`isServerError`](/8.0.0/making-requests/hyperresponse#isservererror) for timed out requests, you need to now either check for `408` status codes, [`isClientError`](/8.0.0/making-requests/hyperresponse#isclienterror), or the more general [`isError`](/8.0.0/making-requests/hyperresponse#iserror).

## Upgrading from v5 to v6

* The default `Content-Type` header has been removed. You must set this [manually](/8.0.0/making-requests/hyperrequest#setcontenttype) or use a format helper, such as [`asJson`](/8.0.0/making-requests/hyperrequest#asjson).
* Dropped support for Adobe 2016.

## Upgrading from v4 to v5

`HyperHttpClientInterface` now requires a `debug` method.

```cfscript
/**
 * Return a struct of information showing how the client will execute the HyperRequest.
 * This will be used by a developer to debug any differences between the generated
 * request values and the expected request values.
 *
 * @req     The HyperRequest to debug.
 *
 * @returns A struct of information detailing how the client would execute the HyperRequest.
 */
public struct function debug( required HyperRequest req );
```

## Upgrading from v3 to v4

Previously, query params were stored as a struct.  Some APIs expect multiple values for the same query param name to be passed as separate arguments.  Hyper now stores the query params as an array and provides new methods for interacting with query params:

* [`getQueryParamByName`](/8.0.0/making-requests/hyperrequest#getqueryparambyname)
* [`getAllQueryParamsByName`](/8.0.0/making-requests/hyperrequest#getallqueryparamsbyname)
* [`withQueryParams`](/8.0.0/making-requests/hyperrequest#withqueryparams)
* [`appendQueryParam`](/8.0.0/making-requests/hyperrequest#appendqueryparam)
* [`appendQueryParams`](/8.0.0/making-requests/hyperrequest#appendqueryparams)
* [`hasQueryParam`](/8.0.0/making-requests/hyperrequest#hasqueryparam)

The following methods still exist, but now interact with arrays of query param structs instead of a simple struct.

* [`getQueryParams`](/8.0.0/making-requests/hyperrequest#getqueryparams)
* [`setQueryParams`](/8.0.0/making-requests/hyperrequest#setqueryparams)

The following methods have been deprecated:

| Deprecated Method                                                    | Replacement Method                                                               |
| -------------------------------------------------------------------- | -------------------------------------------------------------------------------- |
| [`getQueryParam`](/8.0.0/making-requests/hyperrequest#getqueryparam) | [`getQueryParamByName`](/8.0.0/making-requests/hyperrequest#getqueryparambyname) |

## Upgrading from v2 to v3

Dropped support for ColdBox 5.

## Upgrading from v1 to v2

Dropped support for Lucee 4.5.


# Requirements

Hyper runs on Adobe ColdFusion 2018+ and Lucee 5+.

ColdBox is not required, but mappings are provided for ColdBox users automatically.


# Installation

Hyper is most easily installed via ForgeBox and CommandBox.

```sh
box install hyper
```

If you install Hyper in a non-ColdBox application, make sure to create a mapping in your `Application.cfc`

```cfscript
this.mappings[ "/hyper" ] = expandPath( "/modules/hyper" );
```


# HyperBuilder

A `HyperBuilder` is a singleton factory component that will give you a new [`HyperRequest`](/8.0.0/making-requests/hyperrequest) any time you call the `new` method.  It will also create a new [`HyperRequest`](/8.0.0/making-requests/hyperrequest) any time you call a method on `HyperBuilder` that exists on [`HyperRequest`](/8.0.0/making-requests/hyperrequest).

`HyperBuilder` is the component you want to inject into your singleton components, like handlers or services.  It will ensure you get a fresh [`HyperRequest`](/8.0.0/making-requests/hyperrequest) instance on each invocation.  This is important since reusing the same [`HyperRequest`](/8.0.0/making-requests/hyperrequest) instance will likely produce unintended results.

You can inject a `HyperBuilder` into your application using the `HyperBuilder@hyper` id.

```cfscript
component {
    
    property name="hyper" inject="HyperBuilder@hyper";

    function index( event, rc, prc ) {
        var reqA = hyper.new();
        // reqA is a new HyperRequest instance.
        
        var reqB = hyper.setUrl( "https://swapi.dev/api/people" );
        // reqB is a new HyperRequest instance with the url set.
    }

}
```

If you are not using ColdBox, you can create a `HyperBuilder` manually:

```cfscript
component {

    function init() {
        variables.hyper = new hyper.models.HyperBuilder();
    }

}
```

Additionally, you can register `HyperBuilder` instances as custom HTTP Clients.

{% content-ref url="/pages/sc1pmftTrug5lkmdOWQS" %}
[Custom HTTP Clients](/8.0.0/customizing-hyper/custom-http-clients)
{% endcontent-ref %}

Finally, you can enable faking of requests from any `HyperBuilder` instance.

{% content-ref url="/pages/fDs68ouvcjilusPgzOdw" %}
[Faking Requests](/8.0.0/testing/faking-requests)
{% endcontent-ref %}


# HyperRequest

Though the [`HyperBuilder`](/8.0.0/making-requests/hyperbuilder) is the component you will most likely inject, `HyperRequest` is the component will you interact with the most. `HyperRequest` provides a fluent interface to configure your HTTP call.

```cfscript
hyper.get( "https//api.github.com/users" );

hyper.setMethod( "PUT" )
    .withHeaders( { "Authorization" = "Bearer #token#" } )
    .setUrl( "https://jsonplaceholder.typicode.com/posts/1" )
    .setBody( {
        title: "New Title"
    } )
    .send();
```

## Defaults

The following are default properties for a `HyperRequest`:

```json
{
    "method": "GET"
    "resolveUrls": false,
    "encodeUrl": true,
    "timeout": 10, // in seconds
    "maximumRedirects": "*", // follow redirects indefinitely
    "bodyFormat": "json",
    "throwOnError": false,
    "headers": { "User-Agent": "HyperCFML/#versionNumber#" }
}
```

## Executing Requests

### `get`

Execute a `GET` request and return a [`HyperResponse`](/8.0.0/making-requests/hyperresponse).

| Name        | Type   | Required | Default | Description                                                    |
| ----------- | ------ | -------- | ------- | -------------------------------------------------------------- |
| url         | string | false    | null    | An optional URL to set for the request.                        |
| queryParams | struct | false    | null    | An optional struct of query parameters to set for the request. |

**Return**: [`HyperResponse`](/8.0.0/making-requests/hyperresponse)

### `getAsync`

Execute a `GET` request asynchronously. Returns a [ColdBox Future](https://coldbox.ortusbooks.com/digging-deeper/promises-async-programming) that returns a [`HyperResponse`](/8.0.0/making-requests/hyperresponse).

<table><thead><tr><th width="162">Name</th><th>Type</th><th>Required</th><th>Default</th><th>Description</th></tr></thead><tbody><tr><td>url</td><td>string</td><td>false</td><td>null</td><td>An optional URL to set for the request.</td></tr><tr><td>queryParams</td><td>struct</td><td>false</td><td>null</td><td>An optional struct of query parameters to set for the request.</td></tr></tbody></table>

**Return**: [`Future`](https://coldbox.ortusbooks.com/digging-deeper/promises-async-programming)`<`[`HyperResponse`](/8.0.0/making-requests/hyperresponse)`>`

### `post`

Execute a `POST` request and return a [`HyperResponse`](/8.0.0/making-requests/hyperresponse).

| Name | Type   | Required | Default | Description                              |
| ---- | ------ | -------- | ------- | ---------------------------------------- |
| url  | string | false    | null    | An optional URL to set for the request.  |
| body | struct | false    | null    | An optional body to set for the request. |

**Return**: [`HyperResponse`](/8.0.0/making-requests/hyperresponse)

### `postAsync`

Execute a `POST` request asynchronously. Returns a [ColdBox Future](https://coldbox.ortusbooks.com/digging-deeper/promises-async-programming) that returns a [`HyperResponse`](/8.0.0/making-requests/hyperresponse).

| Name | Type   | Required | Default | Description                              |
| ---- | ------ | -------- | ------- | ---------------------------------------- |
| url  | string | false    | null    | An optional URL to set for the request.  |
| body | struct | false    | null    | An optional body to set for the request. |

**Return**: [`Future`](https://coldbox.ortusbooks.com/digging-deeper/promises-async-programming)`<`[`HyperResponse`](/8.0.0/making-requests/hyperresponse)`>`

### `put`

Execute a `PUT` request and return a [`HyperResponse`](/8.0.0/making-requests/hyperresponse).

| Name | Type   | Required | Default | Description                              |
| ---- | ------ | -------- | ------- | ---------------------------------------- |
| url  | string | false    | null    | An optional URL to set for the request.  |
| body | struct | false    | null    | An optional body to set for the request. |

**Return**: [`HyperResponse`](/8.0.0/making-requests/hyperresponse)

### `putAsync`

Execute a `PUT` request asynchronously. Returns a [ColdBox Future](https://coldbox.ortusbooks.com/digging-deeper/promises-async-programming) that returns a [`HyperResponse`](/8.0.0/making-requests/hyperresponse).

| Name | Type   | Required | Default | Description                              |
| ---- | ------ | -------- | ------- | ---------------------------------------- |
| url  | string | false    | null    | An optional URL to set for the request.  |
| body | struct | false    | null    | An optional body to set for the request. |

**Return**: [`Future`](https://coldbox.ortusbooks.com/digging-deeper/promises-async-programming)`<`[`HyperResponse`](/8.0.0/making-requests/hyperresponse)`>`

### `patch`

Execute a `PATCH` request and return a [`HyperResponse`](/8.0.0/making-requests/hyperresponse).

| Name | Type   | Required | Default | Description                              |
| ---- | ------ | -------- | ------- | ---------------------------------------- |
| url  | string | false    | null    | An optional URL to set for the request.  |
| body | struct | false    | null    | An optional body to set for the request. |

**Return**: [`HyperResponse`](/8.0.0/making-requests/hyperresponse)

### `patchAsync`

Execute a `PATCH` request asynchronously. Returns a [ColdBox Future](https://coldbox.ortusbooks.com/digging-deeper/promises-async-programming) that returns a [`HyperResponse`](/8.0.0/making-requests/hyperresponse).

| Name | Type   | Required | Default | Description                              |
| ---- | ------ | -------- | ------- | ---------------------------------------- |
| url  | string | false    | null    | An optional URL to set for the request.  |
| body | struct | false    | null    | An optional body to set for the request. |

**Return**: [`Future`](https://coldbox.ortusbooks.com/digging-deeper/promises-async-programming)`<`[`HyperResponse`](/8.0.0/making-requests/hyperresponse)`>`

### `delete`

Execute a `DELETE` request and return a [`HyperResponse`](/8.0.0/making-requests/hyperresponse).

| Name | Type   | Required | Default | Description                              |
| ---- | ------ | -------- | ------- | ---------------------------------------- |
| url  | string | false    | null    | An optional URL to set for the request.  |
| body | struct | false    | null    | An optional body to set for the request. |

**Return**: [`HyperResponse`](/8.0.0/making-requests/hyperresponse)

### `deleteAsync`

Execute a `DELETE` request asynchronously. Returns a [ColdBox Future](https://coldbox.ortusbooks.com/digging-deeper/promises-async-programming) that returns a [`HyperResponse`](/8.0.0/making-requests/hyperresponse).

| Name | Type   | Required | Default | Description                              |
| ---- | ------ | -------- | ------- | ---------------------------------------- |
| url  | string | false    | null    | An optional URL to set for the request.  |
| body | struct | false    | null    | An optional body to set for the request. |

**Return**: [`Future`](https://coldbox.ortusbooks.com/digging-deeper/promises-async-programming)`<`[`HyperResponse`](/8.0.0/making-requests/hyperresponse)`>`

### `head`

Execute a `HEAD` request and return a [`HyperResponse`](/8.0.0/making-requests/hyperresponse).

| Name        | Type   | Required | Default | Description                                                    |
| ----------- | ------ | -------- | ------- | -------------------------------------------------------------- |
| url         | string | false    | null    | An optional URL to set for the request.                        |
| queryParams | struct | false    | null    | An optional struct of query parameters to set for the request. |

**Return**: [`HyperResponse`](/8.0.0/making-requests/hyperresponse)

### `headAsync`

Execute a `HEAD` request asynchronously. Returns a [ColdBox Future](https://coldbox.ortusbooks.com/digging-deeper/promises-async-programming) that returns a [`HyperResponse`](/8.0.0/making-requests/hyperresponse).

| Name        | Type   | Required | Default | Description                                                    |
| ----------- | ------ | -------- | ------- | -------------------------------------------------------------- |
| url         | string | false    | null    | An optional URL to set for the request.                        |
| queryParams | struct | false    | null    | An optional struct of query parameters to set for the request. |

**Return**: [`Future`](https://coldbox.ortusbooks.com/digging-deeper/promises-async-programming)`<`[`HyperResponse`](/8.0.0/making-requests/hyperresponse)`>`

### `options`

Execute an `OPTIONS` request and return a [`HyperResponse`](/8.0.0/making-requests/hyperresponse).

| Name        | Type   | Required | Default | Description                                                    |
| ----------- | ------ | -------- | ------- | -------------------------------------------------------------- |
| url         | string | false    | null    | An optional URL to set for the request.                        |
| queryParams | struct | false    | null    | An optional struct of query parameters to set for the request. |

**Return**: [`HyperResponse`](/8.0.0/making-requests/hyperresponse)

### `optionsAsync`

Execute an `OPTIONS` request asynchronously. Returns a [ColdBox Future](https://coldbox.ortusbooks.com/digging-deeper/promises-async-programming) that returns a [`HyperResponse`](/8.0.0/making-requests/hyperresponse).

| Name        | Type   | Required | Default | Description                                                    |
| ----------- | ------ | -------- | ------- | -------------------------------------------------------------- |
| url         | string | false    | null    | An optional URL to set for the request.                        |
| queryParams | struct | false    | null    | An optional struct of query parameters to set for the request. |

**Return**: [`Future`](https://coldbox.ortusbooks.com/digging-deeper/promises-async-programming)`<`[`HyperResponse`](/8.0.0/making-requests/hyperresponse)`>`

### `send`

Send the HTTP request and return a [`HyperResponse`](/8.0.0/making-requests/hyperresponse).

| Name         | Type | Required | Default | Description |
| ------------ | ---- | -------- | ------- | ----------- |
| No arguments |      |          |         |             |

**Return**: [`HyperResponse`](/8.0.0/making-requests/hyperresponse)

### `sendAsync`

Send the HTTP request asynchronously and return a [ColdBox Future](https://coldbox.ortusbooks.com/digging-deeper/promises-async-programming) that will resolve to a [`HyperResponse`](/8.0.0/making-requests/hyperresponse).

| Name         | Type | Required | Default | Description |
| ------------ | ---- | -------- | ------- | ----------- |
| No arguments |      |          |         |             |

**Return**: [`Future`](https://coldbox.ortusbooks.com/digging-deeper/promises-async-programming)`<`[`HyperResponse`](/8.0.0/making-requests/hyperresponse)`>`

## Building Requests

### `getRequestId`

Gets the unique request ID representing this request.

| Name         | Type | Required | Default | Description |
| ------------ | ---- | -------- | ------- | ----------- |
| No arguments |      |          |         |             |

**Return**: `String`

### `getFullURL`

Gets the full URL for the request.

| Name            | Type    | Required | Default | Description                                            |
| --------------- | ------- | -------- | ------- | ------------------------------------------------------ |
| withQueryString | boolean | false    | false   | Includes the configured query string with the full URL |

**Return**: `String`

### `getBaseURL`

Gets the base URL for the request. The base URL is combined with the URL when making the request.

| Name         | Type | Required | Default | Description |
| ------------ | ---- | -------- | ------- | ----------- |
| No arguments |      |          |         |             |

**Return**: `String`

### `setBaseURL`

Sets the base URL for the request. The base URL is combined with the URL when making the request.

| Name  | Type   | Required | Default | Description                                                   |
| ----- | ------ | -------- | ------- | ------------------------------------------------------------- |
| value | string | true     |         | The base URL for the request, e.g. `https://api.github.com/`. |

**Return**: `HyperRequest`

### `getURL`

Gets the URL for the request.

| Name         | Type | Required | Default | Description |
| ------------ | ---- | -------- | ------- | ----------- |
| No arguments |      |          |         |             |

**Return**: `String`

### `setURL`

Sets the URL for the request.

| Name  | Type   | Required | Default | Description                                                                                                     |
| ----- | ------ | -------- | ------- | --------------------------------------------------------------------------------------------------------------- |
| value | string | true     |         | The URL for the request. It can either be a full url or a URI resource for use with the baseURL. e.g. `/repos`. |

**Return**: `HyperRequest`

### `setResolveURL`

Sets the resolveURL parameter for the request.

| Name  | Type    | Required | Default | Description                                                                    |
| ----- | ------- | -------- | ------- | ------------------------------------------------------------------------------ |
| value | boolean | false    | false   | Resolves URLs in the response body to absolute URLs, including the port number |

**Return**: `HyperRequest`

### `getMethod`

Gets the HTTP method for the request.

| Name         | Type | Required | Default | Description |
| ------------ | ---- | -------- | ------- | ----------- |
| No arguments |      |          |         |             |

**Return**: `String`

### `setMethod`

Sets the HTTP method for the request.

| Name  | Type   | Required | Default | Description                      |
| ----- | ------ | -------- | ------- | -------------------------------- |
| value | string | true     |         | The HTTP method for the request. |

**Return**: `HyperRequest`

### `withBasicAuth`

Sets the username and password for HTTP Basic Auth.

| Name     | Type   | Required | Default | Description                      |
| -------- | ------ | -------- | ------- | -------------------------------- |
| username | string | true     |         | The username for the basic auth. |
| password | string | true     |         | The password for the basic auth. |

**Return**: `HyperRequest`

### `withCertificateAuth`

Sets the username and password for HTTP Basic Auth.

| Name            | Type   | Required | Default | Description                                              |
| --------------- | ------ | -------- | ------- | -------------------------------------------------------- |
| certificatePath | string | true     |         | The mapped path to the certificate used to authenticate. |
| password        | string | false    |         | The optional password used to decrypt the certificate.   |

**Return**: `HyperRequest`

### `withNTLMAuth`

Sets the username, password, domain and workstation for NTLM Auth.

| Name        | Type   | Required | Default | Description                        |
| ----------- | ------ | -------- | ------- | ---------------------------------- |
| username    | string | true     |         | The username for the NTLM auth.    |
| password    | string | true     |         | The password for the NTLM auth.    |
| domain      | string | true     |         | The domain for the NTLM auth.      |
| workstation | string | true     |         | The workstation for the NTLM auth. |

Workstation can be obtained with `createObject('java','java.net.InetAddress').getLocalHost().getHostName()`

**Return**: `HyperRequest`

### `withRequestCallback`

Schedules a callback to be ran when executing the request.

| Name     | Type     | Required | Default | Description                                     |
| -------- | -------- | -------- | ------- | ----------------------------------------------- |
| callback | function | true     |         | The callback to run when executing the request. |

**Return**: `HyperRequest`

### `withResponseCallback`

Schedules a callback to be ran when receiving the response.

| Name     | Type     | Required | Default | Description                                      |
| -------- | -------- | -------- | ------- | ------------------------------------------------ |
| callback | function | true     |         | The callback to run when receiving the response. |

**Return**: `HyperRequest`

### `getUsername`

Gets the username for the request.

| Name         | Type | Required | Default | Description |
| ------------ | ---- | -------- | ------- | ----------- |
| No arguments |      |          |         |             |

**Return**: `String`

### `setUsername`

Sets the username for the request.

| Name  | Type   | Required | Default | Description                   |
| ----- | ------ | -------- | ------- | ----------------------------- |
| value | string | true     |         | The username for the request. |

**Return**: `HyperRequest`

### `getPassword`

Gets the password for the request.

| Name         | Type | Required | Default | Description |
| ------------ | ---- | -------- | ------- | ----------- |
| No arguments |      |          |         |             |

**Return**: `String`

### `setPassword`

Sets the password for the request.

| Name  | Type   | Required | Default | Description                   |
| ----- | ------ | -------- | ------- | ----------------------------- |
| value | string | true     |         | The password for the request. |

**Return**: `HyperRequest`

### `getTimeout`

Gets the timeout for the request, in seconds.

| Name         | Type | Required | Default | Description |
| ------------ | ---- | -------- | ------- | ----------- |
| No arguments |      |          |         |             |

**Return**: `numeric`

### `setTimeout`

Sets the timeout for the request, in seconds.

| Name  | Type   | Required | Default | Description                              |
| ----- | ------ | -------- | ------- | ---------------------------------------- |
| value | string | true     |         | The timeout for the request, in seconds. |

**Return**: `HyperRequest`

### `withoutRedirecting`

A convenience method to not follow any redirects.

| Name         | Type | Required | Default | Description |
| ------------ | ---- | -------- | ------- | ----------- |
| No arguments |      |          |         |             |

**Return**: `HyperRequest`

### `withoutEncodingUrl`

A convenience method to not encode the url.

{% hint style="warning" %}
**WARNING**: Not supported on Adobe engines.
{% endhint %}

| Name         | Type | Required | Default | Description |
| ------------ | ---- | -------- | ------- | ----------- |
| No arguments |      |          |         |             |

**Return**: `HyperRequest`

### `getMaximumRedirects`

Gets the maximum number of redirects to follow.

| Name         | Type | Required | Default | Description |
| ------------ | ---- | -------- | ------- | ----------- |
| No arguments |      |          |         |             |

**Return**: `numeric | String`

### `setMaximumRedirects`

Sets the maximum number of redirects to follow. A value of `*` will follow redirects infinitely.

| Name  | Type | Required | Default | Description                                |
| ----- | ---- | -------- | ------- | ------------------------------------------ |
| value | any  | true     |         | The maximum number of redirects to follow. |

**Return**: `HyperRequest`

### `getBody`

Gets the body for the request.

| Name         | Type | Required | Default | Description |
| ------------ | ---- | -------- | ------- | ----------- |
| No arguments |      |          |         |             |

**Return**: `any`

### `setBody`

Sets the body for the request. Complex values will be serialized before sending the request.

| Name  | Type | Required | Default | Description               |
| ----- | ---- | -------- | ------- | ------------------------- |
| value | any  | true     |         | The body for the request. |

**Return**: `HyperRequest`

### `hasBody`

Checks if the request has a body.

| Name         | Type | Required | Default | Description |
| ------------ | ---- | -------- | ------- | ----------- |
| No arguments |      |          |         |             |

**Return**: `boolean`

### `getBodyFormat`

Gets the body format for the request.

| Name         | Type | Required | Default | Description |
| ------------ | ---- | -------- | ------- | ----------- |
| No arguments |      |          |         |             |

**Return**: `String`

### `setBodyFormat`

Sets the body format for the request. Recognized values are `formFields`, `json`, or `xml`. It is highly recommended to use `asFormFields`, `asJson`, or `asXML` instead.  If you set this value to a non-recognized value, the body will be passed along as-is to the body of the HTTP request.

| Name  | Type | Required | Default | Description                      |
| ----- | ---- | -------- | ------- | -------------------------------- |
| value | any  | true     |         | The body format for the request. |

**Return**: `HyperRequest`

### `asJson`

A convenience method to set the body format and Content-Type to `json`.

| Name         | Type | Required | Default | Description |
| ------------ | ---- | -------- | ------- | ----------- |
| No arguments |      |          |         |             |

**Return**: `HyperRequest`

### `asFormFields`

A convenience method to set the body format and Content-Type to form fields.

| Name         | Type | Required | Default | Description |
| ------------ | ---- | -------- | ------- | ----------- |
| No arguments |      |          |         |             |

**Return**: `HyperRequest`

### `asXML`

A convenience method to set the body format and Content-Type to `xml`.

| Name         | Type | Required | Default | Description |
| ------------ | ---- | -------- | ------- | ----------- |
| No arguments |      |          |         |             |

**Return**: `HyperRequest`

### `asBinary`

A convenience method to set the body format to `binary` and Content-Type to `application/octet-stream`.

| Name         | Type | Required | Default | Description |
| ------------ | ---- | -------- | ------- | ----------- |
| No arguments |      |          |         |             |

**Return**: `HyperRequest`

### `getReferrer`

Gets the referrer for the request, if any.

| Name         | Type | Required | Default | Description |
| ------------ | ---- | -------- | ------- | ----------- |
| No arguments |      |          |         |             |

**Return**: `String`

### `getHeaders`

Gets the headers for the request.

| Name         | Type | Required | Default | Description |
| ------------ | ---- | -------- | ------- | ----------- |
| No arguments |      |          |         |             |

**Return**: `java.util.LinkedHashMap`

### `setHeaders`

Sets the headers for the request.

| Name  | Type   | Required | Default | Description                  |
| ----- | ------ | -------- | ------- | ---------------------------- |
| value | struct | true     |         | The headers for the request. |

**Return**: `HyperRequest`

### `setHeader`

Set a header for the request.

| Name  | Type   | Required | Default | Description              |
| ----- | ------ | -------- | ------- | ------------------------ |
| name  | string | true     |         | The name of the header.  |
| value | string | true     |         | The value of the header. |

**Return**: `HyperRequest`

### `withHeaders`

Add additional headers to the request.

| Name    | Type   | Required | Default | Description                                |
| ------- | ------ | -------- | ------- | ------------------------------------------ |
| headers | struct | true     |         | A struct of headers to add to the request. |

**Return**: `HyperRequest`

### `forwardHeaders`

Adds specified headers to the request if they exist. Usually used in conjunction with the current CFML request headers.

| Name    | Type   | Required | Default                               | Description                                                                           |
| ------- | ------ | -------- | ------------------------------------- | ------------------------------------------------------------------------------------- |
| names   | array  | true     |                                       | An array of header names to add to the request if they exist in the `headers` struct. |
| headers | struct | false    | `getHTTPRequestData( false ).headers` | A struct of headers to inspect.                                                       |

**Return**: `HyperRequest`

### `hasHeader`

Check if the request has a header with the given name.

| Name | Type   | Required | Default | Description                      |
| ---- | ------ | -------- | ------- | -------------------------------- |
| name | string | true     |         | The name of the header to check. |

**Return**: `boolean`

### `getCookies`

Gets the cookies for the request.

| Name         | Type | Required | Default | Description |
| ------------ | ---- | -------- | ------- | ----------- |
| No arguments |      |          |         |             |

**Return**: `struct<ordered>`

### `setCookies`

Sets the cookies for the request.

| Name  | Type   | Required | Default | Description                  |
| ----- | ------ | -------- | ------- | ---------------------------- |
| value | struct | true     |         | The headers for the request. |

**Return**: `HyperRequest`

### `setCookie`

Set a cookie for the request.

| Name  | Type   | Required | Default | Description              |
| ----- | ------ | -------- | ------- | ------------------------ |
| name  | string | true     |         | The name of the header.  |
| value | string | true     |         | The value of the header. |

**Return**: `HyperRequest`

### `withCookies`

Add additional cookies to the request.

| Name    | Type   | Required | Default | Description                                |
| ------- | ------ | -------- | ------- | ------------------------------------------ |
| cookies | struct | true     |         | A struct of headers to add to the request. |

**Return**: `HyperRequest`

### `withCredentials`

Sends all current cookies along with the request.

| Name         | Type | Required | Default | Description |
| ------------ | ---- | -------- | ------- | ----------- |
| No arguments |      |          |         |             |

**Return**: `HyperRequest`

### `hasCookie`

Check if the request has a cookie with the given name.

| Name | Type   | Required | Default | Description                      |
| ---- | ------ | -------- | ------- | -------------------------------- |
| name | string | true     |         | The name of the header to check. |

**Return**: `boolean`

### `setUserAgent`

A convenience method to set the [`User-Agent` header](https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/User-Agent).

| Name      | Type   | Required | Default | Description                          |
| --------- | ------ | -------- | ------- | ------------------------------------ |
| userAgent | string | true     |         | The User-Agent value for the request |

**Return**: `HyperRequest`

### `setContentType`

A convenience method to set the [`Content-Type` header](https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Content-Type).

| Name | Type   | Required | Default | Description                            |
| ---- | ------ | -------- | ------- | -------------------------------------- |
| type | string | true     |         | The Content-Type value for the request |

**Return**: `HyperRequest`

### `setAccept`

A convenience method to set the [`Accept` header](https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Accept).

| Name | Type   | Required | Default | Description                      |
| ---- | ------ | -------- | ------- | -------------------------------- |
| type | string | true     |         | The Accept value for the request |

**Return**: `HyperRequest`

### `getQueryParams`

Gets the query parameters for the request.

{% hint style="warning" %}
This method returns an array of param structs that is used under the hood by Hyper. You probably want to use [`getQueryParamByName`](#getqueryparambyname) or [`getAllQueryParamsByName`](#getallqueryparamsbyname) instead.
{% endhint %}

| Name         | Type | Required | Default | Description |
| ------------ | ---- | -------- | ------- | ----------- |
| No arguments |      |          |         |             |

**Return**: `array<struct<string, any>>`

### `setQueryParams`

Sets the query parameters for the request.

{% hint style="warning" %}
This method accepts an array of param structs that is used under the hood by Hyper. You probably want to use [`withQueryParams`](#withqueryparams) or [`appendQueryParams`](#appendqueryparams) instead.
{% endhint %}

If needed, param structs have two keys, `name` and `value`.

| Name  | Type  | Required | Default | Description                                                |
| ----- | ----- | -------- | ------- | ---------------------------------------------------------- |
| value | array | true     |         | The query parameters for the as an array of param structs. |

**Return**: `HyperRequest`

### `getQueryParam`

{% hint style="danger" %}
**DEPRECATED:** Use [`getQueryParamByName`](#getqueryparambyname)
{% endhint %}

Gets the first value for a certain query parameter. Returns an empty string if the query parameter does not exist.

| Name | Type   | Required | Default | Description                                                  |
| ---- | ------ | -------- | ------- | ------------------------------------------------------------ |
| name | string | true     |         | The name of the query parameter to retrieve the first value. |

**Return**: `any`

### `getQueryParamByName`

Gets the first value for a certian query parameter. Returns an empty string if the query parameter does not exist.

| Name | Type   | Required | Default | Description                                                  |
| ---- | ------ | -------- | ------- | ------------------------------------------------------------ |
| name | string | true     |         | The name of the query parameter to retrieve the first value. |

**Return**: `any`

### `getAllQueryParamsByName`

Get all the values for a certain query parameter. Returns an empty array if the query parameter does not exist.

| Name | Type   | Required | Default | Description                                                    |
| ---- | ------ | -------- | ------- | -------------------------------------------------------------- |
| name | string | true     |         | The name of the query parameter to retrieve all of its values. |

**Return**: `array<any>`

### `setQueryParam`

Set a query parameter for the request.

{% hint style="info" %}
**Note:** This removes all other query params with the same name.
{% endhint %}

| Name  | Type   | Required | Default | Description                       |
| ----- | ------ | -------- | ------- | --------------------------------- |
| name  | string | true     |         | The name of the query parameter.  |
| value | string | true     |         | The value of the query parameter. |

**Return**: `HyperRequest`

### `appendQueryParam`

Append a query parameter for the request.

| Name  | Type   | Required | Default | Description                       |
| ----- | ------ | -------- | ------- | --------------------------------- |
| name  | string | true     |         | The name of the query parameter.  |
| value | string | true     |         | The value of the query parameter. |

**Return**: `HyperRequest`

### `withQueryParams`

Add additional query parameters to the request.&#x20;

{% hint style="info" %}
**Note:** This will remove any values with duplicate keys prior to adding the new struct of params.
{% endhint %}

| Name        | Type   | Required | Default | Description                                         |
| ----------- | ------ | -------- | ------- | --------------------------------------------------- |
| queryParams | struct | true     |         | A struct of query parameters to add to the request. |

**Return**: `HyperRequest`

### `appendQueryParams`

Appends additional query parameters to the request.

| Name        | Type   | Required | Default | Description                                         |
| ----------- | ------ | -------- | ------- | --------------------------------------------------- |
| queryParams | struct | true     |         | A struct of query parameters to add to the request. |

**Return**: `HyperRequest`

### `hasQueryParam`

Check if the request has a query parameter with the given name.

| Name | Type   | Required | Default | Description                               |
| ---- | ------ | -------- | ------- | ----------------------------------------- |
| name | string | true     |         | The name of the query parameter to check. |

**Return**: `boolean`

### `attach`

Attaches a file to the Hyper request. Also sets the Content-Type as `multipart/form-data`. Multiple files can be attached by calling `attach` multiple times before calling a send method.

| Name     | Type   | Required | Default | Description                                       |
| -------- | ------ | -------- | ------- | ------------------------------------------------- |
| name     | string | true     |         | The name of the file being uploaded.              |
| path     | string | true     |         | The absolute path to the file to be uploaded.     |
| mimeType | string | false    |         | An optional mime type to associate with the file. |

**Return**: `HyperRequest`

### `setThrowOnError`

Sets the throw on error property for the request. If true, statuses in the 4xx and 5xx range will be turned in to exceptions.

| Name  | Type    | Required | Default | Description                           |
| ----- | ------- | -------- | ------- | ------------------------------------- |
| value | boolean | true     |         | The value of the throw on error flag. |

**Return**: `HyperRequest`

### `throwErrors`

A convenience method to throw on errors.

| Name         | Type | Required | Default | Description |
| ------------ | ---- | -------- | ------- | ----------- |
| No arguments |      |          |         |             |

**Return**: `HyperRequest`

### `allowErrors`

A convenience method to not throw on errors.

| Name         | Type | Required | Default | Description |
| ------------ | ---- | -------- | ------- | ----------- |
| No arguments |      |          |         |             |

**Return**: `HyperRequest`

### `clone`

Clones the current request into a new HyperRequest.

| Name         | Type | Required | Default | Description |
| ------------ | ---- | -------- | ------- | ----------- |
| No arguments |      |          |         |             |

**Return**: A new `HyperRequest` instance cloned from this one.

### `clear`

Clears the request of any set values, including defaults passed by the builder.

| Name         | Type | Required | Default | Description |
| ------------ | ---- | -------- | ------- | ----------- |
| No arguments |      |          |         |             |

**Return**: `HyperRequest`

### `when`

Helper to conditionally execute a callback for the `HyperRequest`. This method lets you use conditionals without breaking chaining.

| Name            | Type       | Required | Default | Description                                                                                            |
| --------------- | ---------- | -------- | ------- | ------------------------------------------------------------------------------------------------------ |
| condition       | `boolean`  | `true`   |         | The condition to check.                                                                                |
| successCallback | `function` | `true`   |         | The callback to execute if the condition is true. The callback is passed the `HyperRequest` instance.  |
| failureCallback | `function` | `false`  | `null`  | The callback to execute if the condition is false. The callback is passed the `HyperRequest` instance. |

**Return**: `HyperRequest`

### `retry`

Configures the request to retry failed requests.

| Name      | Type                         | Required | Default | Description                                                                                                                                                                                                                                                                                                                                                                                                                                |
| --------- | ---------------------------- | -------- | ------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------ |
| attempts  | `numeric` / `array<numeric>` | `true`   |         | Either the max number of retry attempts to make or an array containing retry delays between each attempt.  If a numeric value is passed in, the `delay` argument is required.                                                                                                                                                                                                                                                              |
| delay     | `numeric`                    | `false`  |         | The delay to use for each of the `attempts`. This argument is required if `attempts` is a numeric value.  If `attempts` is an array, this value is ignored.                                                                                                                                                                                                                                                                                |
| predicate | `function`                   | `false`  |         | <p>The predicate function to call to determine if a retry should be attempted.<br><br>This function is only called if there are configured retries available.<br><br>To retry a request, this function should return <code>true</code>.<br><br>It is passed the <code>response</code> and <code>request</code> as parameters.<br><br>Additionally, the <code>request</code> can be modified in this method for the next retry attempt.</p> |

**Return**: `HyperRequest`

### `getRetries`

Returns the current retry configuration which is an array of delay times.  A request that needs to be retried will be retried up to the amount of items in this array.  This array can be set using the `retry` method.

{% hint style="warning" %}
In most cases, you do not need to interact with this method directly.  Use the `retry` method instead.
{% endhint %}

| Name         | Type | Required | Default | Description |
| ------------ | ---- | -------- | ------- | ----------- |
| No arguments |      |          |         |             |

**Return**: `array<numeric>`

### `getCurrentRequestCount`

Returns the current request count.  Defaults to `1`. The only time this will increase is if `retries` have been configured for the request.

| Name         | Type | Required | Default | Description |
| ------------ | ---- | -------- | ------- | ----------- |
| No arguments |      |          |         |             |

**Return**: `numeric`

### `getRetryPredicate`

Returns the current callback function that is called to decide if a request should be retried.  This is only called if there are available retries left.

This callback is passed the response and the request as parameters.

A request will be retried if this function returns `true`.

In this function, the passed in request can be modified for the next retry.

{% hint style="warning" %}
In most cases, you do not need to interact with this method directly.  Use the `retry` method instead.
{% endhint %}

| Name         | Type | Required | Default | Description |
| ------------ | ---- | -------- | ------- | ----------- |
| No arguments |      |          |         |             |

**Return**: `numeric`

### `setProperties`

Quickly set many request properties using a struct. The key should be the name of one of the properties on the request, e.g. `url`, `headers`, `method`, `body`.

| Name       | Type   | Required | Default | Description                                                                                                                                   |
| ---------- | ------ | -------- | ------- | --------------------------------------------------------------------------------------------------------------------------------------------- |
| properties | struct | true     |         | A struct of properties to set. Each property name will be set on the request. Properties that don't exist on the request will throw an error. |

**Return**: `HyperRequest`

### `setHttpClient`

Sets the [HTTP Client](/8.0.0/customizing-hyper/custom-http-clients) to use for the request. The client should conform to the `HyperHttpClientInterface` (though it does not need to use the `implements` keyword).

| Name       | Type                       | Required | Default | Description                            |
| ---------- | -------------------------- | -------- | ------- | -------------------------------------- |
| httpClient | `HyperHttpClientInterface` | `true`   |         | The httpClient to use for the request. |

**Return**: `HyperRequest`

### `setInterceptorService`

Sets the [ColdBox Interceptor Service](https://coldbox.ortusbooks.com/the-basics/interceptors) to announce request and response interception points. A noop option is provided in the `init` for non-ColdBox usage.

| Name               | Type | Required | Default | Description                                     |
| ------------------ | ---- | -------- | ------- | ----------------------------------------------- |
| interceptorService | any  | `true`   |         | The interceptor service to use for the request. |

**Return**: `HyperRequest`

### `setAsyncManager`

Sets the [ColdBox AsyncManager](https://coldbox.ortusbooks.com/digging-deeper/promises-async-programming) to send requests asynchronously. A noop option is provided in the `init` for non-ColdBox usage.

| Name         | Type | Required | Default | Description                              |
| ------------ | ---- | -------- | ------- | ---------------------------------------- |
| asyncManager | any  | `true`   |         | The asyncManager to use for the request. |

**Return**: `HyperRequest`

### `getMemento`

Returns a struct representing this `HyperRequest`.

| Name     | Type    | Required | Default | Description                                            |
| -------- | ------- | -------- | ------- | ------------------------------------------------------ |
| excludes | `array` | `false`  | `[]`    | An array of keys to exclude from the returned memento. |

**Return**:

```json
{
    "requestID"           : getRequestID(),
    "baseUrl"             : getBaseUrl(),
    "url"                 : getUrl(),
    "fullUrl"             : getFullUrl(),
    "method"              : getMethod(),
    "queryParams"         : getQueryParams(),
    "headers"             : getHeaders(),
    "cookies"             : getCookies(),
    "files"               : getFiles(),
    "bodyFormat"          : getBodyFormat(),
    "body"                : getBody(),
    "referrer"            : isNull( variables.referrer ) ? "" : variables.referrer,
    "throwOnError"        : getThrowOnError(),
    "timeout"             : getTimeout(),
    "maximumRedirects"    : getMaximumRedirects(),
    "authType"            : getAuthType(),
    "username"            : getUsername(),
    "password"            : getPassword(),
    "clientCert"          : isNull( variables.clientCert ) ? "" : variables.clientCert,
    "clientCertPassword"  : isNull( variables.clientCertPassword ) ? "" : variables.clientCertPassword,
    "domain"              : getDomain(),
    "workstation"         : getWorkstation(),
    "resolveUrls"         : getResolveUrls(),
    "encodeUrl"           : getEncodeUrl(),
    "retries"             : getRetries(),
    "currentRequestCount" : getCurrentRequestCount()
};
```

### `debug`

Creates a debug representation of the HTTP request for the current HTTP client.

{% hint style="danger" %}
**Throws**: `NoUrlException` when no URL is set.
{% endhint %}

| Name         | Type | Required | Default | Description |
| ------------ | ---- | -------- | ------- | ----------- |
| No arguments |      |          |         |             |

**Return**: Dependent on the configured HTTP Client.  See specific HTTP Client documentation for details.


# HyperResponse

The `HyperResponse` component is a read-only wrapper to easily grab different information about the response.

### `getResponseId`

Gets the unique response ID representing this response.

| Name         | Type | Required | Default | Description |
| ------------ | ---- | -------- | ------- | ----------- |
| No arguments |      |          |         |             |

**Return**: `String`

### `getStatusCode`

Gets the status code for the response.

| Name         | Type | Required | Default | Description |
| ------------ | ---- | -------- | ------- | ----------- |
| No arguments |      |          |         |             |

**Return**: `numeric`

### `getStatusText`

Gets the status text for the response.

| Name         | Type | Required | Default | Description |
| ------------ | ---- | -------- | ------- | ----------- |
| No arguments |      |          |         |             |

**Return**: `String`

### `getStatus`

Returns the status code and status text as a single string.

| Name         | Type | Required | Default | Description |
| ------------ | ---- | -------- | ------- | ----------- |
| No arguments |      |          |         |             |

**Return**: `String`

### `getData`

Gets the data for the response.

| Name         | Type | Required | Default | Description |
| ------------ | ---- | -------- | ------- | ----------- |
| No arguments |      |          |         |             |

**Return**: `String`

### `getRequestID`

Returns the id of the request to which this response is related.

| Name         | Type | Required | Default | Description |
| ------------ | ---- | -------- | ------- | ----------- |
| No arguments |      |          |         |             |

**Return**: `String`

### `getRequest`

Gets the [HyperRequest](/8.0.0/making-requests/hyperrequest) instance associated with this response.

| Name         | Type | Required | Default | Description |
| ------------ | ---- | -------- | ------- | ----------- |
| No arguments |      |          |         |             |

**Return**: [`HyperRequest`](/8.0.0/making-requests/hyperrequest)

### `getCharset`

Gets the charset value for the response.

| Name         | Type | Required | Default | Description |
| ------------ | ---- | -------- | ------- | ----------- |
| No arguments |      |          |         |             |

**Return**: `String`

### `getTimestamp`

Gets the timestamp for when this response was received.

| Name         | Type | Required | Default | Description |
| ------------ | ---- | -------- | ------- | ----------- |
| No arguments |      |          |         |             |

**Return**: `DateTime`

### `getExecutionTime`

Gets the execution time of the request, in milliseconds.

| Name         | Type | Required | Default | Description |
| ------------ | ---- | -------- | ------- | ----------- |
| No arguments |      |          |         |             |

**Return**: `numeric`

### `json`

Returns the data of the request as deserialized `JSON`.

{% hint style="danger" %}
**Throws**: `DeserializeJsonException` if the response is not `JSON`.
{% endhint %}

| Name         | Type | Required | Default | Description |
| ------------ | ---- | -------- | ------- | ----------- |
| No arguments |      |          |         |             |

**Return**: `any`

### `isSuccess`

Returns true if the request status code is considered successful.

| Name         | Type | Required | Default | Description |
| ------------ | ---- | -------- | ------- | ----------- |
| No arguments |      |          |         |             |

**Return**: `boolean`

### `isOK`

Returns true if the request status code is `200 OK`.

| Name         | Type | Required | Default | Description |
| ------------ | ---- | -------- | ------- | ----------- |
| No arguments |      |          |         |             |

**Return**: `boolean`

### `isCreated`

Returns true if the request status code is `201 Created`.

| Name         | Type | Required | Default | Description |
| ------------ | ---- | -------- | ------- | ----------- |
| No arguments |      |          |         |             |

**Return**: `boolean`

### `isRedirect`

Returns true if the request status code is considered a redirect.

| Name         | Type | Required | Default | Description |
| ------------ | ---- | -------- | ------- | ----------- |
| No arguments |      |          |         |             |

**Return**: `boolean`

### `isError`

Returns true if the request status code is considered either a client error (4xx status code) or a server error (5xx status code).

| Name         | Type | Required | Default | Description |
| ------------ | ---- | -------- | ------- | ----------- |
| No arguments |      |          |         |             |

**Return**: `boolean`

### `isClientError`

Returns true if the request status code is considered a client error (4xx status code).

| Name         | Type | Required | Default | Description |
| ------------ | ---- | -------- | ------- | ----------- |
| No arguments |      |          |         |             |

**Return**: `boolean`

### `isUnauthorized`

Returns true if the request status code is `401 Unauthorized`.

| Name         | Type | Required | Default | Description |
| ------------ | ---- | -------- | ------- | ----------- |
| No arguments |      |          |         |             |

**Return**: `boolean`

### `isForbidden`

Returns true if the request status code is `403 Forbidden`.

| Name         | Type | Required | Default | Description |
| ------------ | ---- | -------- | ------- | ----------- |
| No arguments |      |          |         |             |

**Return**: `boolean`

### `isNotFound`

Returns true if the request status code is `404 Not Found`.

| Name         | Type | Required | Default | Description |
| ------------ | ---- | -------- | ------- | ----------- |
| No arguments |      |          |         |             |

**Return**: `boolean`

### `isServerError`

Returns true if the request status code is considered a server error (5xx status code).

| Name         | Type | Required | Default | Description |
| ------------ | ---- | -------- | ------- | ----------- |
| No arguments |      |          |         |             |

**Return**: `boolean`

### `hasHeader`

Checks if a header exists in the response.

| Name | Type     | Required | Default | Description                      |
| ---- | -------- | -------- | ------- | -------------------------------- |
| name | `String` | `true`   |         | The name of the header to check. |

**Return**: `boolean`

### `getHeader`

Gets the value of a header from the response.

| Name         | Type     | Required | Default | Description                                       |
| ------------ | -------- | -------- | ------- | ------------------------------------------------- |
| name         | `String` | `true`   |         | The name of the header to retrieve.               |
| defaultValue | `any`    | `false`  | `""`    | The value to return if the header does not exist. |

**Return**: `any`

### `getCookies`

Caches the result of parsing the `Set-Cookie` header and returns it.

| Name         | Type | Required | Default | Description |
| ------------ | ---- | -------- | ------- | ----------- |
| No arguments |      |          |         |             |

**Return**: `struct`

### `persistCookies`

Parses and saves the cookies to the cookie scope.

| Name         | Type | Required | Default | Description |
| ------------ | ---- | -------- | ------- | ----------- |
| No arguments |      |          |         |             |

**Return**: `HyperResponse`

### `getMemento`

Gets a serializable representation of the response.

| Name     | Type    | Required | Default | Description                                            |
| -------- | ------- | -------- | ------- | ------------------------------------------------------ |
| excludes | `array` | `false`  | `[]`    | An array of keys to exclude from the returned memento. |

**Return**:

```json
{
    "responseID"    : getResponseID(),
    "requestID"     : getRequestID(),
    "statusCode"    : getStatusCode(),
    "statusText"    : getStatusText(),
    "status"        : getStatus(),
    "data"          : getData(),
    "charset"       : getCharset(),
    "headers"       : getHeaders(),
    "timestamp"     : getTimestamp(),
    "executionTime" : getExecutionTime(),
    "cookies"       : getCookies()
}
```


# Hyper Clients

Hyper allows you to configure defaults for your requests as custom Hyper Clients. This is particularly useful for reducing boilerplate in your application.

Defaults are set on the `HyperBuilder` instance. The easiest way to do this is to configure it in WireBox. In an `afterAspectsLoad` method, you can get a reference to a `HyperBuilder`, configure it as you would for a request, and then call the `registerAs` method passing in your desired WireBox alias.

```cfscript
// config/WireBox.cfc
component {

   // ...
   
   function afterApsectsLoad() {
       injector.getInstance( "HyperBuilder@hyper" )
           .setBaseUrl( "https://swapi.dev/api" )
           .asJson()
           .registerAs( "StarWarsClient" );
   }

}
```

{% hint style="info" %}
Putting the registration code in `afterAspectsLoad` is required so Hyper can be loaded and available for injection.
{% endhint %}

Now, you can inject this pre-configured builder wherever you need in your application:

```js
component {

    property name="StarWarsClient" inject="StarWarsClient";

    function findUser( id ) {
        return variables.StarWarsClient.get( "/people/#id#" );
    }

}
```

You can alternatively create the clients by passing in the desired defaults to the `initWith` method of a WireBox mapping.  These arguments must match the [`HyperRequest` property names](#hyperrequest-property-names).

```js
// config/WireBox.cfc
component {

    function configure() {
        map( "StarWarsClient" )
            .to( "hyper.models.HyperBuilder" )
            .asSingleton()
            .initWith(
                baseUrl = "https://swapi.dev/api"
            );
    }

}
```

You can even create multiple clients using this approach:

```js
// config/WireBox.cfc
component {

    function configure() {
        // ...
    }

    function afterAspectsLoad() {
        injector.getInstance( "HyperBuilder@hyper" )
           .setBaseUrl( "https://swapi.dev/api" )
           .asJson()
           .registerAs( "StarWarsClient" );

       injector.getInstance( "HyperBuilder@hyper" )
           .setBaseUrl( "https://api.github.com" )
           .asJson()
           .withHeaders( {
               "Authorization": coldbox.getUtil().getSystemSetting( "GITHUB_TOKEN" )
           } )
           .registerAs( "GitHubClient" );
    }

}
```

You can also set or change the defaults by either passing the key / value pairs in to the `init` method or by calling the appropriate `HyperRequest` method on the `HyperBuilder.defaults` property.

```js
var hyper = new Hyper.models.HyperBuilder(
    baseUrl = "https://api.github.com"
);
hyper.defaults.withHeaders( { "Authorization" = token } );
```

#### HyperRequest property names

```cfscript
/**
* The httpClient to use for the request
*/
property name="httpClient";

/**
* The baseURL for the request.
* e.g. https://api.github.com/
*/
property name="baseUrl" default="";

/**
* The URL for the request.
* It can either be a full url
* or a URI resource for use with the baseURL.
* e.g. /repos
*/
property name="url" default="";

/**
* Setting this to true will change all relative urls in the document to absolute.
*/
property name="resolveUrls" default="false";

/**
* Setting this to false will not automatically encode the url passed.
* WARNING: Setting this to false is not supported on Adobe engines.
*/
property name="encodeUrl" default="true";

/**
* The HTTP method for the request.
*/
property name="method" default="GET";

/**
* The username for the request for basic auth.
*/
property name="username" default="";

/**
* The password for the request for basic auth.
*/
property name="password" default="";

/**
* Timeout, in seconds, for the request.
*/
property name="timeout" default="10";

/**
* The maximum number of redirects to follow.
* A value of `*` will follow redirects infinitely.
*/
property name="maximumRedirects" default="*";

/**
* The body to send with the request.
* How the body is serialized is
* determined by the bodyFormat.
*/
property name="body" default="";

/**
* The format to serialize the body.
* e.g. `json` or `formFields`
*/
property name="bodyFormat" default="json";

/**
* The referring response in the case of redirects.
*/
property name="referrer";

/**
* A struct of headers for the request.
*/
property name="headers";

/**
* A struct of query parameters for the request.
*/
property name="queryParams";

/**
* Flag to throw on a cfhttp error.
*/
property name="throwOnError" default="false";

/**
* The full path to a PKCS12 format file that contains the client certificate for the request.
*/
property name="clientCert";

/**
* 	Password used to decrypt the client certificate.
*/
property name="clientCertPassword";

/**
* The domain for the request for NTLM auth.
*/
property name="domain" default="";

/**
* The workstation for the request for NTLM auth.
*/
property name="workstation" default="";

/**
* The authType for the request
*/
property name="authType" default="BASIC";

/**
* An array of callback functions to call
* before firing off a request.
*/
property name="requestCallbacks" type="array";

/**
* An array of callback functions to call
* after receiving a response.
*/
property name="responseCallbacks" type="array";
```

If you need per-request or per-response manipulation of defaults, use the [`requestCallbacks`](/8.0.0/making-requests/hyperrequest#withrequestcallback) and [`responseCallbacks`](/8.0.0/making-requests/hyperrequest#withresponsecallback) hooks.

```cfscript
map( "ApiClient" )
    .to( "hyper.models.HyperBuilder" )
    .asSingleton()
    .initWith(
        baseUrl = getColdBox().getUtil().getSystemSetting( "API_URL" ),
        requestCallbacks = [
            // provide the current user's token for the request
            function( req ) {
                var auth = getWireBox().getInstance( "AuthenticationService@cbauth" );
                req.withHeaders( "Authorization", auth.user().getApiToken() );
            }
        ],
        responseCallbacks = [
            // map custom `error` property to an exception
            function ( res ) {
                if ( !res.isError() ) {
                    return;
                }
                
                var body = res.json();
                throw(
                    type = "ApiError",
                    message = body.error.message,
                    detail = body.error.code
                );
            }
        ]
    );
```


# Custom HTTP Clients

By default, Hyper makes HTTP requests using `cfhttp` under the hood.  This can be swapped out by any compatible HTTP client that follows the `HyperHttpClientInterface`.

```cfscript
/**
 * Responsible for executing the HyperRequest and mapping it to a HyperResponse
 */
interface displayname="HyperHttpClientInterface" {

	/**
	 * Execute the HyperRequest and map it to a HyperResponse.
	 *
	 * @req     The HyperRequest to execute.
	 *
	 * @returns A HyperResponse of the executed request.
	 */
	public HyperResponse function send( required HyperRequest req );

	/**
	 * Return a struct of information showing how the client will execute the HyperRequest.
	 * This will be used by a developer to debug any differences between the generated
	 * request values and the expected request values.
	 *
	 * @req     The HyperRequest to debug.
	 *
	 * @returns A struct of information detailing how the client would execute the HyperRequest.
	 */
	public struct function debug( required HyperRequest req );

}
```


# CfhttpHttpClient

### `debug`

Return a struct of information showing how the client will execute the [`HyperRequest`](/8.0.0/making-requests/hyperrequest). This will be used by a developer to debug any differences between the generated request values and the expected request values.

| Name | Type                                                  | Required | Default | Description                                                         |
| ---- | ----------------------------------------------------- | -------- | ------- | ------------------------------------------------------------------- |
| req  | [`HyperRequest`](/8.0.0/making-requests/hyperrequest) | `true`   |         | The [`HyperRequest`](/8.0.0/making-requests/hyperrequest) to debug. |

**Return**:

```json
{
    "attributes" : attrCollection,
    "body"       : {
        "headers" : cfhttpHeaders,
        "params"  : cfhttpParams,
        "files"   : cfhttpFiles,
        "body"    : cfhttpBody,
        "cookies" : cfhttpCookies
    }
}
```


# Interceptors

Hyper announces two [interception points through ColdBox](https://coldbox.ortusbooks.com/the-basics/interceptors): `onHyperRequest` and `onHyperResponse`.

### onHyperRequest

This interception point is announced before the request is sent.  It receives the `request` as the only parameter inside `data`.

### onHyperResponse

This interception point is announced after the response is received.  It receives the `response` and the `request` inside `data`.


# Faking Requests

Hyper has the ability to fake requests and return fake responses as a result.  This is perfect for [testing](https://testbox.ortusbooks.com/) scenarios where you don't actually want to make an HTTP request.

{% hint style="warning" %}
Non-ColdBox users will need to add a mapping to the [`Globber`](https://forgebox.io/view/globber) dependency included with Hyper.

```cfscript
// Application.cfc
component {
    this.mappings[ "/globber" ] = "/path/to/hyper" & "/modules/globber";
}
```

{% endhint %}

## Faking All Requests

Faking is enabled on a [`HyperBuilder`](/8.0.0/making-requests/hyperbuilder) instance, either the built-in one provided by Hyper or a [custom Hyper client](/8.0.0/customizing-hyper/custom-http-clients) you have created.

To enable faking requests, call the `fake` method:

```cfscript
var hyper = new Hyper.models.HyperBuilder();
hyper.fake();
```

After calling the `fake` method, all requests created by this `HyperBuilder` will be faked.  By default, they will return `200 OK` responses with empty bodies.

```cfscript
hyper.fake();
var res = hyper.get( "https://google.com" );
expect( res.getStatus() ).toBe( "200 OK" );
```

## Fake Configuration

When calling the `fake` method, you can provide a struct mapping URL patterns to response generator functions.

```cfscript
hyper.fake( {
    "https://google.com/*": function( newFakeResponse, req ) {
         return newFakeResponse( 404, "Not Found" );
    }
} );
```

The key is a URL pattern.  The pattern can be any valid glob. If the pattern is matched by the [`fullUrl`](/8.0.0/making-requests/hyperrequest#getfullurl) of the `HyperRequest`, then the response generator function will be called and the results returned.

A helper function, `newFakeResponse`, is provided as the first argument to the response generator function.  The current request is provided as the second argument.

## FakeHyperResponse

The resposne generator function must return a `FakeHyperResponse` instance.  A `FakeHyperResponse` instance acts similar to a normal `HyperResponse` except the properties are not read only.  Once you have an instance of your `FakeHyperResponse`, you can continue to set any properties you need.

```cfscript
hyper.fake( {
    "https://jsonplaceholder.typicode.com/posts": function( newFakeResponse, req ) {
         return newFakeResponse()
             .setStatusCode( 201 )
             .setStatusText( "Created" )
             .setData( serializeJSON( {
                 "id": 101,
                 "title": "foo",
                 "body": "bar",
                 "userId": 1
             } ) );
    }
} );
```

You can also pass the values to the `newFakeResponse` function, if you'd like.

```cfscript
hyper.fake( {
    "https://jsonplaceholder.typicode.com/posts": function( newFakeResponse, req ) {
         return newFakeResponse( 201, "Created", serializeJSON( {
             "id": 101,
             "title": "foo",
             "body": "bar",
             "userId": 1
         } ) );
    }
} );
```

### `newFakeResponse`

Creates a new `FakeHyperResponse` instance.

<table><thead><tr><th width="160">Name</th><th>Type</th><th>Required</th><th>Default</th><th>Description</th></tr></thead><tbody><tr><td>statusCode</td><td><code>numeric</code></td><td><code>false</code></td><td>200</td><td>The status code for the fake response.</td></tr><tr><td>statusText</td><td><code>string</code></td><td><code>false</code></td><td><code>"OK"</code></td><td>The status text for the fake response.</td></tr><tr><td>data</td><td><code>string</code></td><td><code>false</code></td><td><code>""</code></td><td>The data for the fake response.</td></tr><tr><td>headers</td><td><code>{ string: string }</code></td><td><code>false</code></td><td><code>{}</code></td><td>The headers for the fake response.</td></tr><tr><td>executionTime</td><td><code>numeric</code></td><td><code>false</code></td><td>0</td><td>The execution time for the fake response.</td></tr><tr><td>charset</td><td><code>string</code></td><td><code>false</code></td><td><code>"UTF-8"</code></td><td>The charset for the fake response.</td></tr><tr><td>timestamp</td><td><code>datetime</code></td><td><code>false</code></td><td><code>now()</code></td><td>The timestamp of the fake response.</td></tr></tbody></table>

**Return**: `FakeHyperResponse`

## Sequencing Fake Responses

In addition to returning a single `FakeHyperResponse` per pattern, you can return an array of `FakeHyperResponse` instances.  These will be returned in a sequence.

```cfscript
hyper.fake( {
    "https://jsonplaceholder.typicode.com/posts": function( newFakeResponse, req ) {
         return [
             newFakeResponse( 201, "Created", serializeJSON( {
                 "id": 101,
                 "title": "foo",
                 "body": "bar",
                 "userId": 1
             } ) ),
             newFakeResponse( 422, "Unprocessable Entity", "Duplicate title" )
         ];
    }
} );

var resA = hyper.post( "https://jsonplaceholder.typicode.com/posts", { /* ... */ } );
expect( resA.getStatus() ).toBe( "201 Created" );

var resB = hyper.post( "https://jsonplaceholder.typicode.com/posts", { /* ... */ } );
expect( resA.getStatus() ).toBe( "422 Unprocessable Entity" );
```

If you continue to make requests to the same pattern after the sequence has been exhausted, an exception will be thrown.

```cfscript
hyper.fake( {
    "https://jsonplaceholder.typicode.com/posts": function( newFakeResponse, req ) {
         return [
             newFakeResponse( 201, "Created", serializeJSON( {
                 "id": 101,
                 "title": "foo",
                 "body": "bar",
                 "userId": 1
             } ) ),
             newFakeResponse( 422, "Unprocessable Entity", "Duplicate title" )
         ];
    }
} );

var resA = hyper.post( "https://jsonplaceholder.typicode.com/posts", { /* ... */ } );
expect( resA.getStatus() ).toBe( "201 Created" );

var resB = hyper.post( "https://jsonplaceholder.typicode.com/posts", { /* ... */ } );
expect( resA.getStatus() ).toBe( "422 Unprocessable Entity" );

// THROWS a `HyperFakeSequenceExhausted` exception
var resC = hyper.post( "https://jsonplaceholder.typicode.com/posts", { /* ... */ } );
```

## Preventing Stray Requests

By default, Hyper returns a default `FakeHyperResponse` for every request that doesn't match one of your configured patterns.  You can instead cause Hyper to throw an exception if it encounters one of these stray requests by calling the `preventStrayRequests` method.

```cfscript
hyper.fake( {
    "https://google.com/*": function( newFakeResponse, req ) {
         return newFakeResponse( 404, "Not Found" );
    }
} ).preventStrayRequests();

// THROWS a `HyperFakeStrayRequest` exception
var res = hyper.get( "https://github.com" );
```

## Making Assertions

In addition to assertions made against the `FakeHyperResponse` instances returned, you can also make assertions using the `HyperBuilder` instance you faked.  These come in the form of methods on the `HyperBuilder` instance as well as custom TestBox Assertions.

### HyperBuilder Method Assertions

The following methods are available to make assertions in your tests about the requests that were sent.

#### getFakeRequestCount

Returns the number of fake requests that have been made.

| Name         | Type | Required | Default | Description |
| ------------ | ---- | -------- | ------- | ----------- |
| No arguments |      |          |         |             |

**Return**: `numeric`

#### wasRequestSent

Returns whether a request has been made that matches the `predicate`. Each request that has been made is passed to the `predicate` in order. If the `predicate` returns `true`, the request is considered a match and `true` is returned. If no request passes the `predicate`, `false` is returned.

| Name      | Type       | Required | Default | Description                                                                                            |
| --------- | ---------- | -------- | ------- | ------------------------------------------------------------------------------------------------------ |
| predicate | `function` | `true`   |         | A callback function that returns true if the request matches the criteria and returns false otherwise. |

**Return**: `boolean`

### Custom TestBox Assertions

You can register [custom TestBox assertions](https://testbox.ortusbooks.com/digging-deeper/expectations/custom-matchers) provided by Hyper for more readable tests and test failure messages.

You must [register](https://testbox.ortusbooks.com/digging-deeper/expectations/custom-matchers#class-matchers) these assertions before using them.

```cfscript
component extends="testbox.system.BaseSpec" {

    function beforeAll() {
        addMatchers( "hyper.models.TestBoxMatchers" )
    }
    
    function run() {
        // ...
    }

}
```

The following custom assertions are provided:

#### toHaveSentRequest

This takes in the `HyperBuilder` instance as the actual and a predicate function as the expected. The predicate function is passed to the `HyperBuilder` instance's `wasRequestSent` method.

```cfscript
hyper.fake();

hyper.get( "https://google.com" );

expect( hyper ).toHaveSentRequest( function( req ) {
    return req.getFullUrl() == "https://google.com";
} );

expect( hyper ).notToHaveSentRequest( function( req ) {
    return req.getFullUrl() == "https://github.com";
} );
```

#### toHaveSentCount

This takes in the `HyperBuilder` instance as the actual and an integer number of requests that should have been sent.

```cfscript
hyper.fake();

hyper.get( "https://google.com" );

expect( hyper ).toHaveSentCount( 1 );
expect( hyper ).notToHaveSentCount( 2 );
```

#### toHaveSentNothing

This takes in the `HyperBuilder` instance as the actual and no other parameters.

```cfscript
hyper.fake();

expect( hyper ).toHaveSentNothing();

hyper.get( "https://google.com" );

expect( hyper ).notToHaveSentNothing();
```

## Resetting the Builder

To reset the sent request counts and sequences but keep the fake configuration, use the `resetFakes` method:

```javascript
hyper.fake();

hyper.get( "https://google.com" );

expect( hyper ).toHaveSentCount( 1 );

hyper.resetFakes();

expect( hyper ).toHaveSentNothing();
```

To reset the `HyperBuilder` instance to normal operation call the `clearFakes` method:

```cfscript
hyper.fake();

hyper.get( "https://google.com" );

hyper.clearFakes();
```

{% hint style="info" %}
These are useful methods to call in an [`afterEach`](https://testbox.ortusbooks.com/in-depth/life-cycle-methods/bdd#aftereach-body-data) block in TestBox to make sure you are only faking requests when you want to.
{% endhint %}


# Introduction

## A CFML HTTP Builder

### Inspiration

Hyper was built after coding several API SDK's for various platforms — [S3SDK](https://github.com/coldbox-modules/s3sdk), [cbstripe](https://github.com/coldbox-modules/cbox-stripe), and [cbgithub](https://github.com/elpete/cbgithub), to name a few. We noticed that we spent a lot of time setting up the plumbing for the requests and a wrapper around `cfhttp`. Each implementation was mostly the same but slightly different. It was additionally frustrating because we really only needed to tweak a few values, usually just the `Authorization` header. It would be nice to create an HTTP client pre-configured for each of these SDK's. It seemed the perfect fit for a module.

### The problem it solves

Hyper exists to provide a fluent builder experience for HTTP requests and responses. It also provides a powerful way to create clients, i.e. Builder objects with pre-configured defaults like a base URL or certain headers.


# What's New?

## 8.1.0

Added support for configuring proxy server settings via the [`throughProxy`](/making-requests/hyperrequest#throughproxy) method.

## 8.0.2

Removed unused API docs build in the CI process.

## 8.0.1

* Ensure backwards compatibility with ColdBox versions before 6.
* Various tests and CI updates.

## 8.0.0

v8.0.0 was released as a mistake in the build process. By the time it was realized, other people had already started using it, so removing it would cause even more issues.  So, it's staying around, even without any changes at all.

## 7.5.3

Certify for BoxLang

## 7.5.2

Add ability to exclude keys from [`HyperRequest`](/making-requests/hyperrequest#getmemento) and [`HyperResponse`](/making-requests/hyperresponse#getmemento) mementos.

## 7.5.1

Updated misspelled and missing docblocks.

## 7.5.0

### Request available in \`onHyperResponse\` interception point.

Although this was already available by calling `response.getRequest()`, the request is now available as the second parameter of the [`onHyperResponse` interceptor](/customizing-hyper/interceptors#onhyperresponse).

## 7.4.0

### asBinary

Added a [convenience method](/making-requests/hyperrequest#asbinary) to set the `bodyFormat` to `binary` and the `Content-Type` to `application/octet-stream`.

## 7.3.0

### Retrying Failed Requests

You can now configure a `HyperRequest` to automatically retry failed requests.  [See the `HyperRequest` docs for details.](/making-requests/hyperrequest#retry)

### Default User-Agent

Hyper now sends a default User-Agent of `HyperCFML/#versionNumber#`.

### Reset Fake Request Counts and Sequences

Hyper can now reset the fake request counts and sequences without losing the fake configuration using the [`resetFakes`](/testing/faking-requests#resetting-the-builder) method.

## 7.2.0

### Cookies

Hyper can now [send cookies with a request](/making-requests/hyperrequest#withcookies) and [parse the returned cookies from a response](/making-requests/hyperresponse#getcookies). See the [HyperRequest](/making-requests/hyperrequest) and [HyperResponse](/making-requests/hyperresponse) docs for details.

## 7.1.0

### Fake Requests

Hyper now has the ability to fake requests and return fake responses as a result.  This is perfect for testing scenarios where you don't actually want to make an HTTP request.

{% content-ref url="/pages/fDs68ouvcjilusPgzOdw" %}
[Faking Requests](/testing/faking-requests)
{% endcontent-ref %}

### Custom Hyper Clients

It is now more straightforward to register a [custom Hyper client](/customizing-hyper/custom-http-clients).  Inside your `config/WireBox.cfc` in an `afterAspectsLoad` method, you can get a reference to a `HyperBuilder`, configure it as you would for a request, and then call the `registerAs` method passing in your desired WireBox alias.

```cfscript
// config/WireBox.cfc
component {

   // ...
   
   function afterApsectsLoad() {
       injector.getInstance( "HyperBuilder@hyper" )
           .setBaseUrl( "https://api.github.com" )
           .asJson()
           .withHeaders( {
               "Authorization": coldbox.getUtil().getSystemSetting( "GITHUB_TOKEN" )
           } )
           .registerAs( "GitHubClient" );
   }

}
```

This is a welcome improvement as the `init` arguments do not exactly match the method names.  Also, for defaults like `requestCallbacks`, `responseCallbacks`, or even `queryParams`, passing in arrays of functions or arrays or structs is not as straightforward as calling the related methods.  Now, you can use the Hyper methods you are familiar with when registering your custom Hyper clients.

{% hint style="info" %}
Putting the registration code in `afterAspectsLoad` is required so Hyper can be loaded and available for injection.
{% endhint %}

## 7.0.0

### CFHttp HTTP Client

This client now returns more accurate status codes for `502 Bad Gateway` and `408 Request Timeout` responses.

Previously, these responses were returned as `504 Gateway Timeout` responses. Hyper now normalizes the responses from the different CFML engines into a consistent response. `502 Bad Gateway` is returned instead of `504 Gateway Timeout` for invalid hosts. `408 Request Timeout` is returned if the request takes longer than the configured [`timeout`](/making-requests/hyperrequest#settimeout) value.

### Breaking Changes

If you were previously checking specifically for `504` status codes for bad hosts, you need to now either check for `502` status codes or use a more general method, like [`isServerError`](/making-requests/hyperresponse#isservererror) or [`isError`](/making-requests/hyperresponse#iserror).

If you were previously checking specifically for `504` status codes or [`isServerError`](/making-requests/hyperresponse#isservererror) for timed out requests, you need to now either check for `408` status codes, [`isClientError`](/making-requests/hyperresponse#isclienterror), or the more general [`isError`](/making-requests/hyperresponse#iserror).

## 6.1.0

Add [`head`](/making-requests/hyperrequest#head) and [`options`](/making-requests/hyperrequest#options) shortcut methods.

## 6.0.0

* Add `xml` support and an `asXML` method to set the body format and `Content-Type` header.
* Add `adobe@2023` to testing matrix.

### Breaking Changes

* Remove default `Content-Type` header. You must set this [manually](/making-requests/hyperrequest#setcontenttype) or use a format helper, such as [`asJson`](/making-requests/hyperrequest#asjson).
* Dropped `adobe@2016` support.

## 5.0.1

Correctly handle cases when the `body` is a string and format is `JSON`.

## 5.0.0

Add a `debug` method to see what the HTTP client generates.

### Breaking Changes

`HyperHttpClientInterface` now requires a `debug` method.

```cfscript
/**
 * Return a struct of information showing how the client will execute the HyperRequest.
 * This will be used by a developer to debug any differences between the generated
 * request values and the expected request values.
 *
 * @req     The HyperRequest to debug.
 *
 * @returns A struct of information detailing how the client would execute the HyperRequest.
 */
public struct function debug( required HyperRequest req );
```

## 4.0.3

* Do not prepend the base url when a full url is passed.
* Add `resolveUrls` and `encodeUrl` properties to the [memento](/making-requests/hyperrequest#getmemento).
* Correctly set the `encodeUrl` property when cloning a request.

## 4.0.2

Update README for builder `initWith` headers losing `Content-Type`.

## 4.0.1

Fix `HyperBuilder` example in the docs.

## 4.0.0

Allow adding multiple query params with the same key.

### Breaking Changes

Previously, query params were stored as a struct.  Some APIs expect multiple values for the same query param name to be passed as separate arguments.  Hyper now stores the query params as an array and provides new methods for interacting with query params:

* [`getQueryParamByName`](/making-requests/hyperrequest#getqueryparambyname)
* [`getAllQueryParamsByName`](/making-requests/hyperrequest#getallqueryparamsbyname)
* [`withQueryParams`](/making-requests/hyperrequest#withqueryparams)
* [`appendQueryParam`](/making-requests/hyperrequest#appendqueryparam)
* [`appendQueryParams`](/making-requests/hyperrequest#appendqueryparams)
* [`hasQueryParam`](/making-requests/hyperrequest#hasqueryparam)

The following methods still exist, but now interact with arrays of query param structs instead of a simple struct.

* [`getQueryParams`](/making-requests/hyperrequest#getqueryparams)
* [`setQueryParams`](/making-requests/hyperrequest#setqueryparams)

The following methods have been deprecated:

| Deprecated Method                                              | Replacement Method                                                         |
| -------------------------------------------------------------- | -------------------------------------------------------------------------- |
| [`getQueryParam`](/making-requests/hyperrequest#getqueryparam) | [`getQueryParamByName`](/making-requests/hyperrequest#getqueryparambyname) |

## 3.6.2

Convert array values correctly when sending form fields

## 3.6.1

Add a workaround for CommandBox not having the `box:asyncManager` injection DSL.

## 3.6.0

Add async requests using ColdBox's [AsyncManager](https://coldbox.ortusbooks.com/digging-deeper/promises-async-programming).

## 3.5.0

* Provide more useful error than cfhttp when [`throwOnErrors`](/making-requests/hyperrequest#throwerrors) is enabled.
* Provide mementos for [HyperRequest](/making-requests/hyperrequest#getmemento) and [HyperResponse](/making-requests/hyperresponse#getmemento) instances.
* Capture [statusText](/making-requests/hyperresponse#getstatustext) and provide a [status](/making-requests/hyperresponse#getstatus) convenience string.

## 3.4.2

Add MIT License file

## 3.4.1

Use `processState` over `announce` until CommandBox can update its `interceptorService`.

## 3.4.0

### HyperRequest

* Add [`forwardHeaders`](/making-requests/hyperrequest#forwardheaders) shortcut method.

### HyperResponse

* Allow for default values in [`getHeader`](/making-requests/hyperresponse#getheader).
* Add helper methods for checking for specific status codes:
  * [`isOk`](/making-requests/hyperresponse#isok)
  * [`isUnauthorized`](/making-requests/hyperresponse#isunauthorized)
  * [`isForbidden`](/making-requests/hyperresponse#isforbidden)
  * [`isNotFound`](/making-requests/hyperresponse#isnotfound)

## 3.3.0

Allowing [attaching](/making-requests/hyperrequest#attach) file uploads.

## 3.2.1

Support WireBox outside of ColdBox.

## 3.2.0

Include response data as detail in `DeserializeJsonException`.

## 3.1.0

* Add [`clone`](/making-requests/hyperrequest#clone) to quickly copy `HyperRequest` instances.
* Add interceptors and [local](/making-requests/hyperrequest#withrequestcallback) [callbacks](/making-requests/hyperrequest#withresponsecallback) for lifecycle events.

## 3.0.0

Add execution time to `HyperResponse` instances.

### Breaking Changes

Dropped support for ColdBox 5.

## 2.3.11

* Add support for [NTLM authentication](/making-requests/hyperrequest#withntlmauth).
* Include [`getFullURL`](/making-requests/hyperrequest#getfullurl) method in docs.

## 2.3.10

Fixed typo of `Bulider` to `Builder`.

## 2.3.9

Add [`withoutEncodingUrl`](/making-requests/hyperrequest#withoutencodingurl) flag.

## 2.3.8

Do not fail fast on cron job actions on CI.

## 2.3.7

Update fetch-depth for tests and release actions on CI.

## 2.3.6

Attempt to skip committing back changes on CI.

## 2.3.5

Add matrix and cron testing on CI.

## 2.3.4

Use better GitHub token on CI

## 2.3.1

Add workaround for `boolean` values in query strings.

## 2.3.0

Add [certificate](/making-requests/hyperrequest#withcertificateauth) auth.

## 2.2.1

Use the previous host for redirect if redirect does not include a full URL.

## 2.2.0

Add [`resolveUrls`](/making-requests/hyperrequest#setresolveurl) flag.

## 2.1.1

* Use OpenJDK instead of OracleJDK on CI.
* Store module in [ForgeBox Storage](https://commandbox.ortusbooks.com/5.6.0/developing-for-commandbox/commands).

## 2.1.0

Allow for pluggable [HTTP Clients](/customizing-hyper/custom-http-clients) that follow the `HyperHttpClientInterface`. (Clients do not need to use the `implements` keyword.)

## 2.0.2

Avoid double encoding using [`cfhttpparam`](https://cfdocs.org/cfhttpparam).

## 2.0.1

Remove Lucee 4.5 support from docs. (Support was dropped in [v2.0.0](#2.0.0))

## 2.0.0

* Do not include [`username`](/making-requests/hyperrequest#setusername) and [`password`](/making-requests/hyperrequest#setpassword) unless they have values.
* Add `adobe@2018` support to CI builds.

### Breaking Changes

Dropped support for `lucee@4.5`.

## 1.15.0

Add [`throwOnError`](/making-requests/hyperrequest#throwerrors) flag.

## 1.14.5

Use `504 Gateway Timeout` for incomplete responses.

## 1.14.4

Include equal signs in query param values.

## 1.14.0 – 1.0.0

### New Features

* Add [`when`](/making-requests/hyperrequest#when) helper to execute conditions without breaking chaining.
* Add [`clear`](/making-requests/hyperrequest#clear) method to reset HyperRequest instances.
* Add configurable [`timeout`](/making-requests/hyperrequest#settimeout).

### Bug Fixes

* Fix for Lucee 4 compatibility on `LinkedHashMaps` and `keyArray`.
* Preserve case in header names.
* Preserve case for query parameters.
* Serialize both params from the url and set on the `HyperRequest` instance.
* Default to `UTF-8` charset if none is present in the response.
* Fix withHeaders and withQueryParams for Lucee compatibility.
* Only map HyperBuilder as a singleton in WireBox

### Other

* Migrate to [coldbox-modules](https://github.com/coldbox-modules) organization on GitHub.
* Update `box.json` description.
* Enable [CommandBox Semantic Release](https://forgebox.io/view/commandbox-semantic-release) on CI.


# Upgrade Guide

## Upgrading from v7 to v8

This will be your easiest upgrade ever — there's nothing to do!

v8.0.0 was released as a mistake in the build process. By the time it was realized, other people had already started using it, so removing it would cause even more issues.  So, it's staying around, even without any changes at all.

## Upgrading from v6 to v7

### CFHttp HTTP Client

This client now returns more accurate status codes for `502 Bad Gateway` and `408 Request Timeout` responses.

If you were previously checking specifically for `504` status codes for bad hosts, you need to now either check for `502` status codes or use a more general method, like [`isServerError`](/making-requests/hyperresponse#isservererror) or [`isError`](/making-requests/hyperresponse#iserror).

If you were previously checking specifically for `504` status codes or [`isServerError`](/making-requests/hyperresponse#isservererror) for timed out requests, you need to now either check for `408` status codes, [`isClientError`](/making-requests/hyperresponse#isclienterror), or the more general [`isError`](/making-requests/hyperresponse#iserror).

## Upgrading from v5 to v6

* The default `Content-Type` header has been removed. You must set this [manually](/making-requests/hyperrequest#setcontenttype) or use a format helper, such as [`asJson`](/making-requests/hyperrequest#asjson).
* Dropped support for Adobe 2016.

## Upgrading from v4 to v5

`HyperHttpClientInterface` now requires a `debug` method.

```cfscript
/**
 * Return a struct of information showing how the client will execute the HyperRequest.
 * This will be used by a developer to debug any differences between the generated
 * request values and the expected request values.
 *
 * @req     The HyperRequest to debug.
 *
 * @returns A struct of information detailing how the client would execute the HyperRequest.
 */
public struct function debug( required HyperRequest req );
```

## Upgrading from v3 to v4

Previously, query params were stored as a struct.  Some APIs expect multiple values for the same query param name to be passed as separate arguments.  Hyper now stores the query params as an array and provides new methods for interacting with query params:

* [`getQueryParamByName`](/making-requests/hyperrequest#getqueryparambyname)
* [`getAllQueryParamsByName`](/making-requests/hyperrequest#getallqueryparamsbyname)
* [`withQueryParams`](/making-requests/hyperrequest#withqueryparams)
* [`appendQueryParam`](/making-requests/hyperrequest#appendqueryparam)
* [`appendQueryParams`](/making-requests/hyperrequest#appendqueryparams)
* [`hasQueryParam`](/making-requests/hyperrequest#hasqueryparam)

The following methods still exist, but now interact with arrays of query param structs instead of a simple struct.

* [`getQueryParams`](/making-requests/hyperrequest#getqueryparams)
* [`setQueryParams`](/making-requests/hyperrequest#setqueryparams)

The following methods have been deprecated:

| Deprecated Method                                              | Replacement Method                                                         |
| -------------------------------------------------------------- | -------------------------------------------------------------------------- |
| [`getQueryParam`](/making-requests/hyperrequest#getqueryparam) | [`getQueryParamByName`](/making-requests/hyperrequest#getqueryparambyname) |

## Upgrading from v2 to v3

Dropped support for ColdBox 5.

## Upgrading from v1 to v2

Dropped support for Lucee 4.5.


# Requirements

Hyper runs on Adobe ColdFusion 2018+ and Lucee 5+.

ColdBox is not required, but mappings are provided for ColdBox users automatically.


# Installation

Hyper is most easily installed via ForgeBox and CommandBox.

```sh
box install hyper
```

If you install Hyper in a non-ColdBox application, make sure to create a mapping in your `Application.cfc`

```cfscript
this.mappings[ "/hyper" ] = expandPath( "/modules/hyper" );
```


# HyperBuilder

A `HyperBuilder` is a singleton factory component that will give you a new [`HyperRequest`](/making-requests/hyperrequest) any time you call the `new` method.  It will also create a new [`HyperRequest`](/making-requests/hyperrequest) any time you call a method on `HyperBuilder` that exists on [`HyperRequest`](/making-requests/hyperrequest).

`HyperBuilder` is the component you want to inject into your singleton components, like handlers or services.  It will ensure you get a fresh [`HyperRequest`](/making-requests/hyperrequest) instance on each invocation.  This is important since reusing the same [`HyperRequest`](/making-requests/hyperrequest) instance will likely produce unintended results.

You can inject a `HyperBuilder` into your application using the `HyperBuilder@hyper` id.

```cfscript
component {
    
    property name="hyper" inject="HyperBuilder@hyper";

    function index( event, rc, prc ) {
        var reqA = hyper.new();
        // reqA is a new HyperRequest instance.
        
        var reqB = hyper.setUrl( "https://swapi.dev/api/people" );
        // reqB is a new HyperRequest instance with the url set.
    }

}
```

If you are not using ColdBox, you can create a `HyperBuilder` manually:

```cfscript
component {

    function init() {
        variables.hyper = new hyper.models.HyperBuilder();
    }

}
```

Additionally, you can register `HyperBuilder` instances as custom HTTP Clients.

{% content-ref url="/pages/sc1pmftTrug5lkmdOWQS" %}
[Custom HTTP Clients](/customizing-hyper/custom-http-clients)
{% endcontent-ref %}

Finally, you can enable faking of requests from any `HyperBuilder` instance.

{% content-ref url="/pages/fDs68ouvcjilusPgzOdw" %}
[Faking Requests](/testing/faking-requests)
{% endcontent-ref %}


# HyperRequest

Though the [`HyperBuilder`](/making-requests/hyperbuilder) is the component you will most likely inject, `HyperRequest` is the component will you interact with the most. `HyperRequest` provides a fluent interface to configure your HTTP call.

```cfscript
hyper.get( "https//api.github.com/users" );

hyper.setMethod( "PUT" )
    .withHeaders( { "Authorization" = "Bearer #token#" } )
    .setUrl( "https://jsonplaceholder.typicode.com/posts/1" )
    .setBody( {
        title: "New Title"
    } )
    .send();
```

## Defaults

The following are default properties for a `HyperRequest`:

```json
{
    "method": "GET"
    "resolveUrls": false,
    "encodeUrl": true,
    "timeout": 10, // in seconds
    "maximumRedirects": "*", // follow redirects indefinitely
    "bodyFormat": "json",
    "throwOnError": false,
    "headers": { "User-Agent": "HyperCFML/#versionNumber#" }
}
```

## Executing Requests

### `get`

Execute a `GET` request and return a [`HyperResponse`](/making-requests/hyperresponse).

| Name        | Type   | Required | Default | Description                                                    |
| ----------- | ------ | -------- | ------- | -------------------------------------------------------------- |
| url         | string | false    | null    | An optional URL to set for the request.                        |
| queryParams | struct | false    | null    | An optional struct of query parameters to set for the request. |

**Return**: [`HyperResponse`](/making-requests/hyperresponse)

### `getAsync`

Execute a `GET` request asynchronously. Returns a [ColdBox Future](https://coldbox.ortusbooks.com/digging-deeper/promises-async-programming) that returns a [`HyperResponse`](/making-requests/hyperresponse).

<table><thead><tr><th width="162">Name</th><th>Type</th><th>Required</th><th>Default</th><th>Description</th></tr></thead><tbody><tr><td>url</td><td>string</td><td>false</td><td>null</td><td>An optional URL to set for the request.</td></tr><tr><td>queryParams</td><td>struct</td><td>false</td><td>null</td><td>An optional struct of query parameters to set for the request.</td></tr></tbody></table>

**Return**: [`Future`](https://coldbox.ortusbooks.com/digging-deeper/promises-async-programming)`<`[`HyperResponse`](/making-requests/hyperresponse)`>`

### `post`

Execute a `POST` request and return a [`HyperResponse`](/making-requests/hyperresponse).

| Name | Type   | Required | Default | Description                              |
| ---- | ------ | -------- | ------- | ---------------------------------------- |
| url  | string | false    | null    | An optional URL to set for the request.  |
| body | struct | false    | null    | An optional body to set for the request. |

**Return**: [`HyperResponse`](/making-requests/hyperresponse)

### `postAsync`

Execute a `POST` request asynchronously. Returns a [ColdBox Future](https://coldbox.ortusbooks.com/digging-deeper/promises-async-programming) that returns a [`HyperResponse`](/making-requests/hyperresponse).

| Name | Type   | Required | Default | Description                              |
| ---- | ------ | -------- | ------- | ---------------------------------------- |
| url  | string | false    | null    | An optional URL to set for the request.  |
| body | struct | false    | null    | An optional body to set for the request. |

**Return**: [`Future`](https://coldbox.ortusbooks.com/digging-deeper/promises-async-programming)`<`[`HyperResponse`](/making-requests/hyperresponse)`>`

### `put`

Execute a `PUT` request and return a [`HyperResponse`](/making-requests/hyperresponse).

| Name | Type   | Required | Default | Description                              |
| ---- | ------ | -------- | ------- | ---------------------------------------- |
| url  | string | false    | null    | An optional URL to set for the request.  |
| body | struct | false    | null    | An optional body to set for the request. |

**Return**: [`HyperResponse`](/making-requests/hyperresponse)

### `putAsync`

Execute a `PUT` request asynchronously. Returns a [ColdBox Future](https://coldbox.ortusbooks.com/digging-deeper/promises-async-programming) that returns a [`HyperResponse`](/making-requests/hyperresponse).

| Name | Type   | Required | Default | Description                              |
| ---- | ------ | -------- | ------- | ---------------------------------------- |
| url  | string | false    | null    | An optional URL to set for the request.  |
| body | struct | false    | null    | An optional body to set for the request. |

**Return**: [`Future`](https://coldbox.ortusbooks.com/digging-deeper/promises-async-programming)`<`[`HyperResponse`](/making-requests/hyperresponse)`>`

### `patch`

Execute a `PATCH` request and return a [`HyperResponse`](/making-requests/hyperresponse).

| Name | Type   | Required | Default | Description                              |
| ---- | ------ | -------- | ------- | ---------------------------------------- |
| url  | string | false    | null    | An optional URL to set for the request.  |
| body | struct | false    | null    | An optional body to set for the request. |

**Return**: [`HyperResponse`](/making-requests/hyperresponse)

### `patchAsync`

Execute a `PATCH` request asynchronously. Returns a [ColdBox Future](https://coldbox.ortusbooks.com/digging-deeper/promises-async-programming) that returns a [`HyperResponse`](/making-requests/hyperresponse).

| Name | Type   | Required | Default | Description                              |
| ---- | ------ | -------- | ------- | ---------------------------------------- |
| url  | string | false    | null    | An optional URL to set for the request.  |
| body | struct | false    | null    | An optional body to set for the request. |

**Return**: [`Future`](https://coldbox.ortusbooks.com/digging-deeper/promises-async-programming)`<`[`HyperResponse`](/making-requests/hyperresponse)`>`

### `delete`

Execute a `DELETE` request and return a [`HyperResponse`](/making-requests/hyperresponse).

| Name | Type   | Required | Default | Description                              |
| ---- | ------ | -------- | ------- | ---------------------------------------- |
| url  | string | false    | null    | An optional URL to set for the request.  |
| body | struct | false    | null    | An optional body to set for the request. |

**Return**: [`HyperResponse`](/making-requests/hyperresponse)

### `deleteAsync`

Execute a `DELETE` request asynchronously. Returns a [ColdBox Future](https://coldbox.ortusbooks.com/digging-deeper/promises-async-programming) that returns a [`HyperResponse`](/making-requests/hyperresponse).

| Name | Type   | Required | Default | Description                              |
| ---- | ------ | -------- | ------- | ---------------------------------------- |
| url  | string | false    | null    | An optional URL to set for the request.  |
| body | struct | false    | null    | An optional body to set for the request. |

**Return**: [`Future`](https://coldbox.ortusbooks.com/digging-deeper/promises-async-programming)`<`[`HyperResponse`](/making-requests/hyperresponse)`>`

### `head`

Execute a `HEAD` request and return a [`HyperResponse`](/making-requests/hyperresponse).

| Name        | Type   | Required | Default | Description                                                    |
| ----------- | ------ | -------- | ------- | -------------------------------------------------------------- |
| url         | string | false    | null    | An optional URL to set for the request.                        |
| queryParams | struct | false    | null    | An optional struct of query parameters to set for the request. |

**Return**: [`HyperResponse`](/making-requests/hyperresponse)

### `headAsync`

Execute a `HEAD` request asynchronously. Returns a [ColdBox Future](https://coldbox.ortusbooks.com/digging-deeper/promises-async-programming) that returns a [`HyperResponse`](/making-requests/hyperresponse).

| Name        | Type   | Required | Default | Description                                                    |
| ----------- | ------ | -------- | ------- | -------------------------------------------------------------- |
| url         | string | false    | null    | An optional URL to set for the request.                        |
| queryParams | struct | false    | null    | An optional struct of query parameters to set for the request. |

**Return**: [`Future`](https://coldbox.ortusbooks.com/digging-deeper/promises-async-programming)`<`[`HyperResponse`](/making-requests/hyperresponse)`>`

### `options`

Execute an `OPTIONS` request and return a [`HyperResponse`](/making-requests/hyperresponse).

| Name        | Type   | Required | Default | Description                                                    |
| ----------- | ------ | -------- | ------- | -------------------------------------------------------------- |
| url         | string | false    | null    | An optional URL to set for the request.                        |
| queryParams | struct | false    | null    | An optional struct of query parameters to set for the request. |

**Return**: [`HyperResponse`](/making-requests/hyperresponse)

### `optionsAsync`

Execute an `OPTIONS` request asynchronously. Returns a [ColdBox Future](https://coldbox.ortusbooks.com/digging-deeper/promises-async-programming) that returns a [`HyperResponse`](/making-requests/hyperresponse).

| Name        | Type   | Required | Default | Description                                                    |
| ----------- | ------ | -------- | ------- | -------------------------------------------------------------- |
| url         | string | false    | null    | An optional URL to set for the request.                        |
| queryParams | struct | false    | null    | An optional struct of query parameters to set for the request. |

**Return**: [`Future`](https://coldbox.ortusbooks.com/digging-deeper/promises-async-programming)`<`[`HyperResponse`](/making-requests/hyperresponse)`>`

### `send`

Send the HTTP request and return a [`HyperResponse`](/making-requests/hyperresponse).

| Name         | Type | Required | Default | Description |
| ------------ | ---- | -------- | ------- | ----------- |
| No arguments |      |          |         |             |

**Return**: [`HyperResponse`](/making-requests/hyperresponse)

### `sendAsync`

Send the HTTP request asynchronously and return a [ColdBox Future](https://coldbox.ortusbooks.com/digging-deeper/promises-async-programming) that will resolve to a [`HyperResponse`](/making-requests/hyperresponse).

| Name         | Type | Required | Default | Description |
| ------------ | ---- | -------- | ------- | ----------- |
| No arguments |      |          |         |             |

**Return**: [`Future`](https://coldbox.ortusbooks.com/digging-deeper/promises-async-programming)`<`[`HyperResponse`](/making-requests/hyperresponse)`>`

## Building Requests

### `getRequestId`

Gets the unique request ID representing this request.

| Name         | Type | Required | Default | Description |
| ------------ | ---- | -------- | ------- | ----------- |
| No arguments |      |          |         |             |

**Return**: `String`

### `getFullURL`

Gets the full URL for the request.

| Name            | Type    | Required | Default | Description                                            |
| --------------- | ------- | -------- | ------- | ------------------------------------------------------ |
| withQueryString | boolean | false    | false   | Includes the configured query string with the full URL |

**Return**: `String`

### `getBaseURL`

Gets the base URL for the request. The base URL is combined with the URL when making the request.

| Name         | Type | Required | Default | Description |
| ------------ | ---- | -------- | ------- | ----------- |
| No arguments |      |          |         |             |

**Return**: `String`

### `setBaseURL`

Sets the base URL for the request. The base URL is combined with the URL when making the request.

| Name  | Type   | Required | Default | Description                                                   |
| ----- | ------ | -------- | ------- | ------------------------------------------------------------- |
| value | string | true     |         | The base URL for the request, e.g. `https://api.github.com/`. |

**Return**: `HyperRequest`

### `getURL`

Gets the URL for the request.

| Name         | Type | Required | Default | Description |
| ------------ | ---- | -------- | ------- | ----------- |
| No arguments |      |          |         |             |

**Return**: `String`

### `setURL`

Sets the URL for the request.

| Name  | Type   | Required | Default | Description                                                                                                     |
| ----- | ------ | -------- | ------- | --------------------------------------------------------------------------------------------------------------- |
| value | string | true     |         | The URL for the request. It can either be a full url or a URI resource for use with the baseURL. e.g. `/repos`. |

**Return**: `HyperRequest`

### `setResolveURL`

Sets the resolveURL parameter for the request.

| Name  | Type    | Required | Default | Description                                                                    |
| ----- | ------- | -------- | ------- | ------------------------------------------------------------------------------ |
| value | boolean | false    | false   | Resolves URLs in the response body to absolute URLs, including the port number |

**Return**: `HyperRequest`

### `getMethod`

Gets the HTTP method for the request.

| Name         | Type | Required | Default | Description |
| ------------ | ---- | -------- | ------- | ----------- |
| No arguments |      |          |         |             |

**Return**: `String`

### `setMethod`

Sets the HTTP method for the request.

| Name  | Type   | Required | Default | Description                      |
| ----- | ------ | -------- | ------- | -------------------------------- |
| value | string | true     |         | The HTTP method for the request. |

**Return**: `HyperRequest`

### `withBasicAuth`

Sets the username and password for HTTP Basic Auth.

| Name     | Type   | Required | Default | Description                      |
| -------- | ------ | -------- | ------- | -------------------------------- |
| username | string | true     |         | The username for the basic auth. |
| password | string | true     |         | The password for the basic auth. |

**Return**: `HyperRequest`

### `withCertificateAuth`

Sets the username and password for HTTP Basic Auth.

| Name            | Type   | Required | Default | Description                                              |
| --------------- | ------ | -------- | ------- | -------------------------------------------------------- |
| certificatePath | string | true     |         | The mapped path to the certificate used to authenticate. |
| password        | string | false    |         | The optional password used to decrypt the certificate.   |

**Return**: `HyperRequest`

### `withNTLMAuth`

Sets the username, password, domain and workstation for NTLM Auth.

| Name        | Type   | Required | Default | Description                        |
| ----------- | ------ | -------- | ------- | ---------------------------------- |
| username    | string | true     |         | The username for the NTLM auth.    |
| password    | string | true     |         | The password for the NTLM auth.    |
| domain      | string | true     |         | The domain for the NTLM auth.      |
| workstation | string | true     |         | The workstation for the NTLM auth. |

Workstation can be obtained with `createObject('java','java.net.InetAddress').getLocalHost().getHostName()`

**Return**: `HyperRequest`

### `throughProxy`

Sets the proxy settings for the request.

| Name          | Type    | Required | Default           | Description                                                      |
| ------------- | ------- | -------- | ----------------- | ---------------------------------------------------------------- |
| proxyHost     | string  | true     |                   | The proxy server host or IP address.                             |
| proxyPort     | numeric | false    | 80                | The proxy server port. Defaults to 80.                           |
| proxyUser     | string  | false    | "" (empty string) | The username for proxy authentication. Defaults to empty string. |
| proxyPassword | string  | false    | "" (empty string) | The password for proxy authentication. Defaults to empty string. |

**Return:** `HyperRequest`

### `withRequestCallback`

Schedules a callback to be ran when executing the request.

| Name     | Type     | Required | Default | Description                                     |
| -------- | -------- | -------- | ------- | ----------------------------------------------- |
| callback | function | true     |         | The callback to run when executing the request. |

**Return**: `HyperRequest`

### `withResponseCallback`

Schedules a callback to be ran when receiving the response.

| Name     | Type     | Required | Default | Description                                      |
| -------- | -------- | -------- | ------- | ------------------------------------------------ |
| callback | function | true     |         | The callback to run when receiving the response. |

**Return**: `HyperRequest`

### `getUsername`

Gets the username for the request.

| Name         | Type | Required | Default | Description |
| ------------ | ---- | -------- | ------- | ----------- |
| No arguments |      |          |         |             |

**Return**: `String`

### `setUsername`

Sets the username for the request.

| Name  | Type   | Required | Default | Description                   |
| ----- | ------ | -------- | ------- | ----------------------------- |
| value | string | true     |         | The username for the request. |

**Return**: `HyperRequest`

### `getPassword`

Gets the password for the request.

| Name         | Type | Required | Default | Description |
| ------------ | ---- | -------- | ------- | ----------- |
| No arguments |      |          |         |             |

**Return**: `String`

### `setPassword`

Sets the password for the request.

| Name  | Type   | Required | Default | Description                   |
| ----- | ------ | -------- | ------- | ----------------------------- |
| value | string | true     |         | The password for the request. |

**Return**: `HyperRequest`

### `getTimeout`

Gets the timeout for the request, in seconds.

| Name         | Type | Required | Default | Description |
| ------------ | ---- | -------- | ------- | ----------- |
| No arguments |      |          |         |             |

**Return**: `numeric`

### `setTimeout`

Sets the timeout for the request, in seconds.

| Name  | Type   | Required | Default | Description                              |
| ----- | ------ | -------- | ------- | ---------------------------------------- |
| value | string | true     |         | The timeout for the request, in seconds. |

**Return**: `HyperRequest`

### `withoutRedirecting`

A convenience method to not follow any redirects.

| Name         | Type | Required | Default | Description |
| ------------ | ---- | -------- | ------- | ----------- |
| No arguments |      |          |         |             |

**Return**: `HyperRequest`

### `withoutEncodingUrl`

A convenience method to not encode the url.

{% hint style="warning" %}
**WARNING**: Not supported on Adobe engines.
{% endhint %}

| Name         | Type | Required | Default | Description |
| ------------ | ---- | -------- | ------- | ----------- |
| No arguments |      |          |         |             |

**Return**: `HyperRequest`

### `getMaximumRedirects`

Gets the maximum number of redirects to follow.

| Name         | Type | Required | Default | Description |
| ------------ | ---- | -------- | ------- | ----------- |
| No arguments |      |          |         |             |

**Return**: `numeric | String`

### `setMaximumRedirects`

Sets the maximum number of redirects to follow. A value of `*` will follow redirects infinitely.

| Name  | Type | Required | Default | Description                                |
| ----- | ---- | -------- | ------- | ------------------------------------------ |
| value | any  | true     |         | The maximum number of redirects to follow. |

**Return**: `HyperRequest`

### `getBody`

Gets the body for the request.

| Name         | Type | Required | Default | Description |
| ------------ | ---- | -------- | ------- | ----------- |
| No arguments |      |          |         |             |

**Return**: `any`

### `setBody`

Sets the body for the request. Complex values will be serialized before sending the request.

| Name  | Type | Required | Default | Description               |
| ----- | ---- | -------- | ------- | ------------------------- |
| value | any  | true     |         | The body for the request. |

**Return**: `HyperRequest`

### `hasBody`

Checks if the request has a body.

| Name         | Type | Required | Default | Description |
| ------------ | ---- | -------- | ------- | ----------- |
| No arguments |      |          |         |             |

**Return**: `boolean`

### `getBodyFormat`

Gets the body format for the request.

| Name         | Type | Required | Default | Description |
| ------------ | ---- | -------- | ------- | ----------- |
| No arguments |      |          |         |             |

**Return**: `String`

### `setBodyFormat`

Sets the body format for the request. Recognized values are `formFields`, `json`, or `xml`. It is highly recommended to use `asFormFields`, `asJson`, or `asXML` instead.  If you set this value to a non-recognized value, the body will be passed along as-is to the body of the HTTP request.

| Name  | Type | Required | Default | Description                      |
| ----- | ---- | -------- | ------- | -------------------------------- |
| value | any  | true     |         | The body format for the request. |

**Return**: `HyperRequest`

### `asJson`

A convenience method to set the body format and Content-Type to `json`.

| Name         | Type | Required | Default | Description |
| ------------ | ---- | -------- | ------- | ----------- |
| No arguments |      |          |         |             |

**Return**: `HyperRequest`

### `asFormFields`

A convenience method to set the body format and Content-Type to form fields.

| Name         | Type | Required | Default | Description |
| ------------ | ---- | -------- | ------- | ----------- |
| No arguments |      |          |         |             |

**Return**: `HyperRequest`

### `asXML`

A convenience method to set the body format and Content-Type to `xml`.

| Name         | Type | Required | Default | Description |
| ------------ | ---- | -------- | ------- | ----------- |
| No arguments |      |          |         |             |

**Return**: `HyperRequest`

### `asBinary`

A convenience method to set the body format to `binary` and Content-Type to `application/octet-stream`.

| Name         | Type | Required | Default | Description |
| ------------ | ---- | -------- | ------- | ----------- |
| No arguments |      |          |         |             |

**Return**: `HyperRequest`

### `getReferrer`

Gets the referrer for the request, if any.

| Name         | Type | Required | Default | Description |
| ------------ | ---- | -------- | ------- | ----------- |
| No arguments |      |          |         |             |

**Return**: `String`

### `getHeaders`

Gets the headers for the request.

| Name         | Type | Required | Default | Description |
| ------------ | ---- | -------- | ------- | ----------- |
| No arguments |      |          |         |             |

**Return**: `java.util.LinkedHashMap`

### `setHeaders`

Sets the headers for the request.

| Name  | Type   | Required | Default | Description                  |
| ----- | ------ | -------- | ------- | ---------------------------- |
| value | struct | true     |         | The headers for the request. |

**Return**: `HyperRequest`

### `setHeader`

Set a header for the request.

| Name  | Type   | Required | Default | Description              |
| ----- | ------ | -------- | ------- | ------------------------ |
| name  | string | true     |         | The name of the header.  |
| value | string | true     |         | The value of the header. |

**Return**: `HyperRequest`

### `withHeaders`

Add additional headers to the request.

| Name    | Type   | Required | Default | Description                                |
| ------- | ------ | -------- | ------- | ------------------------------------------ |
| headers | struct | true     |         | A struct of headers to add to the request. |

**Return**: `HyperRequest`

### `forwardHeaders`

Adds specified headers to the request if they exist. Usually used in conjunction with the current CFML request headers.

| Name    | Type   | Required | Default                               | Description                                                                           |
| ------- | ------ | -------- | ------------------------------------- | ------------------------------------------------------------------------------------- |
| names   | array  | true     |                                       | An array of header names to add to the request if they exist in the `headers` struct. |
| headers | struct | false    | `getHTTPRequestData( false ).headers` | A struct of headers to inspect.                                                       |

**Return**: `HyperRequest`

### `hasHeader`

Check if the request has a header with the given name.

| Name | Type   | Required | Default | Description                      |
| ---- | ------ | -------- | ------- | -------------------------------- |
| name | string | true     |         | The name of the header to check. |

**Return**: `boolean`

### `getCookies`

Gets the cookies for the request.

| Name         | Type | Required | Default | Description |
| ------------ | ---- | -------- | ------- | ----------- |
| No arguments |      |          |         |             |

**Return**: `struct<ordered>`

### `setCookies`

Sets the cookies for the request.

| Name  | Type   | Required | Default | Description                  |
| ----- | ------ | -------- | ------- | ---------------------------- |
| value | struct | true     |         | The headers for the request. |

**Return**: `HyperRequest`

### `setCookie`

Set a cookie for the request.

| Name  | Type   | Required | Default | Description              |
| ----- | ------ | -------- | ------- | ------------------------ |
| name  | string | true     |         | The name of the header.  |
| value | string | true     |         | The value of the header. |

**Return**: `HyperRequest`

### `withCookies`

Add additional cookies to the request.

| Name    | Type   | Required | Default | Description                                |
| ------- | ------ | -------- | ------- | ------------------------------------------ |
| cookies | struct | true     |         | A struct of headers to add to the request. |

**Return**: `HyperRequest`

### `withCredentials`

Sends all current cookies along with the request.

| Name         | Type | Required | Default | Description |
| ------------ | ---- | -------- | ------- | ----------- |
| No arguments |      |          |         |             |

**Return**: `HyperRequest`

### `hasCookie`

Check if the request has a cookie with the given name.

| Name | Type   | Required | Default | Description                      |
| ---- | ------ | -------- | ------- | -------------------------------- |
| name | string | true     |         | The name of the header to check. |

**Return**: `boolean`

### `setUserAgent`

A convenience method to set the [`User-Agent` header](https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/User-Agent).

| Name      | Type   | Required | Default | Description                          |
| --------- | ------ | -------- | ------- | ------------------------------------ |
| userAgent | string | true     |         | The User-Agent value for the request |

**Return**: `HyperRequest`

### `setContentType`

A convenience method to set the [`Content-Type` header](https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Content-Type).

| Name | Type   | Required | Default | Description                            |
| ---- | ------ | -------- | ------- | -------------------------------------- |
| type | string | true     |         | The Content-Type value for the request |

**Return**: `HyperRequest`

### `setAccept`

A convenience method to set the [`Accept` header](https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Accept).

| Name | Type   | Required | Default | Description                      |
| ---- | ------ | -------- | ------- | -------------------------------- |
| type | string | true     |         | The Accept value for the request |

**Return**: `HyperRequest`

### `getQueryParams`

Gets the query parameters for the request.

{% hint style="warning" %}
This method returns an array of param structs that is used under the hood by Hyper. You probably want to use [`getQueryParamByName`](#getqueryparambyname) or [`getAllQueryParamsByName`](#getallqueryparamsbyname) instead.
{% endhint %}

| Name         | Type | Required | Default | Description |
| ------------ | ---- | -------- | ------- | ----------- |
| No arguments |      |          |         |             |

**Return**: `array<struct<string, any>>`

### `setQueryParams`

Sets the query parameters for the request.

{% hint style="warning" %}
This method accepts an array of param structs that is used under the hood by Hyper. You probably want to use [`withQueryParams`](#withqueryparams) or [`appendQueryParams`](#appendqueryparams) instead.
{% endhint %}

If needed, param structs have two keys, `name` and `value`.

| Name  | Type  | Required | Default | Description                                                |
| ----- | ----- | -------- | ------- | ---------------------------------------------------------- |
| value | array | true     |         | The query parameters for the as an array of param structs. |

**Return**: `HyperRequest`

### `getQueryParam`

{% hint style="danger" %}
**DEPRECATED:** Use [`getQueryParamByName`](#getqueryparambyname)
{% endhint %}

Gets the first value for a certain query parameter. Returns an empty string if the query parameter does not exist.

| Name | Type   | Required | Default | Description                                                  |
| ---- | ------ | -------- | ------- | ------------------------------------------------------------ |
| name | string | true     |         | The name of the query parameter to retrieve the first value. |

**Return**: `any`

### `getQueryParamByName`

Gets the first value for a certian query parameter. Returns an empty string if the query parameter does not exist.

| Name | Type   | Required | Default | Description                                                  |
| ---- | ------ | -------- | ------- | ------------------------------------------------------------ |
| name | string | true     |         | The name of the query parameter to retrieve the first value. |

**Return**: `any`

### `getAllQueryParamsByName`

Get all the values for a certain query parameter. Returns an empty array if the query parameter does not exist.

| Name | Type   | Required | Default | Description                                                    |
| ---- | ------ | -------- | ------- | -------------------------------------------------------------- |
| name | string | true     |         | The name of the query parameter to retrieve all of its values. |

**Return**: `array<any>`

### `setQueryParam`

Set a query parameter for the request.

{% hint style="info" %}
**Note:** This removes all other query params with the same name.
{% endhint %}

| Name  | Type   | Required | Default | Description                       |
| ----- | ------ | -------- | ------- | --------------------------------- |
| name  | string | true     |         | The name of the query parameter.  |
| value | string | true     |         | The value of the query parameter. |

**Return**: `HyperRequest`

### `appendQueryParam`

Append a query parameter for the request.

| Name  | Type   | Required | Default | Description                       |
| ----- | ------ | -------- | ------- | --------------------------------- |
| name  | string | true     |         | The name of the query parameter.  |
| value | string | true     |         | The value of the query parameter. |

**Return**: `HyperRequest`

### `withQueryParams`

Add additional query parameters to the request.&#x20;

{% hint style="info" %}
**Note:** This will remove any values with duplicate keys prior to adding the new struct of params.
{% endhint %}

| Name        | Type   | Required | Default | Description                                         |
| ----------- | ------ | -------- | ------- | --------------------------------------------------- |
| queryParams | struct | true     |         | A struct of query parameters to add to the request. |

**Return**: `HyperRequest`

### `appendQueryParams`

Appends additional query parameters to the request.

| Name        | Type   | Required | Default | Description                                         |
| ----------- | ------ | -------- | ------- | --------------------------------------------------- |
| queryParams | struct | true     |         | A struct of query parameters to add to the request. |

**Return**: `HyperRequest`

### `hasQueryParam`

Check if the request has a query parameter with the given name.

| Name | Type   | Required | Default | Description                               |
| ---- | ------ | -------- | ------- | ----------------------------------------- |
| name | string | true     |         | The name of the query parameter to check. |

**Return**: `boolean`

### `attach`

Attaches a file to the Hyper request. Also sets the Content-Type as `multipart/form-data`. Multiple files can be attached by calling `attach` multiple times before calling a send method.

| Name     | Type   | Required | Default | Description                                       |
| -------- | ------ | -------- | ------- | ------------------------------------------------- |
| name     | string | true     |         | The name of the file being uploaded.              |
| path     | string | true     |         | The absolute path to the file to be uploaded.     |
| mimeType | string | false    |         | An optional mime type to associate with the file. |

**Return**: `HyperRequest`

### `setThrowOnError`

Sets the throw on error property for the request. If true, statuses in the 4xx and 5xx range will be turned in to exceptions.

| Name  | Type    | Required | Default | Description                           |
| ----- | ------- | -------- | ------- | ------------------------------------- |
| value | boolean | true     |         | The value of the throw on error flag. |

**Return**: `HyperRequest`

### `throwErrors`

A convenience method to throw on errors.

| Name         | Type | Required | Default | Description |
| ------------ | ---- | -------- | ------- | ----------- |
| No arguments |      |          |         |             |

**Return**: `HyperRequest`

### `allowErrors`

A convenience method to not throw on errors.

| Name         | Type | Required | Default | Description |
| ------------ | ---- | -------- | ------- | ----------- |
| No arguments |      |          |         |             |

**Return**: `HyperRequest`

### `clone`

Clones the current request into a new HyperRequest.

| Name         | Type | Required | Default | Description |
| ------------ | ---- | -------- | ------- | ----------- |
| No arguments |      |          |         |             |

**Return**: A new `HyperRequest` instance cloned from this one.

### `clear`

Clears the request of any set values, including defaults passed by the builder.

| Name         | Type | Required | Default | Description |
| ------------ | ---- | -------- | ------- | ----------- |
| No arguments |      |          |         |             |

**Return**: `HyperRequest`

### `when`

Helper to conditionally execute a callback for the `HyperRequest`. This method lets you use conditionals without breaking chaining.

| Name            | Type       | Required | Default | Description                                                                                            |
| --------------- | ---------- | -------- | ------- | ------------------------------------------------------------------------------------------------------ |
| condition       | `boolean`  | `true`   |         | The condition to check.                                                                                |
| successCallback | `function` | `true`   |         | The callback to execute if the condition is true. The callback is passed the `HyperRequest` instance.  |
| failureCallback | `function` | `false`  | `null`  | The callback to execute if the condition is false. The callback is passed the `HyperRequest` instance. |

**Return**: `HyperRequest`

### `retry`

Configures the request to retry failed requests.

| Name      | Type                         | Required | Default | Description                                                                                                                                                                                                                                                                                                                                                                                                                                |
| --------- | ---------------------------- | -------- | ------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------ |
| attempts  | `numeric` / `array<numeric>` | `true`   |         | Either the max number of retry attempts to make or an array containing retry delays between each attempt.  If a numeric value is passed in, the `delay` argument is required.                                                                                                                                                                                                                                                              |
| delay     | `numeric`                    | `false`  |         | The delay to use for each of the `attempts`. This argument is required if `attempts` is a numeric value.  If `attempts` is an array, this value is ignored.                                                                                                                                                                                                                                                                                |
| predicate | `function`                   | `false`  |         | <p>The predicate function to call to determine if a retry should be attempted.<br><br>This function is only called if there are configured retries available.<br><br>To retry a request, this function should return <code>true</code>.<br><br>It is passed the <code>response</code> and <code>request</code> as parameters.<br><br>Additionally, the <code>request</code> can be modified in this method for the next retry attempt.</p> |

**Return**: `HyperRequest`

### `getRetries`

Returns the current retry configuration which is an array of delay times.  A request that needs to be retried will be retried up to the amount of items in this array.  This array can be set using the `retry` method.

{% hint style="warning" %}
In most cases, you do not need to interact with this method directly.  Use the `retry` method instead.
{% endhint %}

| Name         | Type | Required | Default | Description |
| ------------ | ---- | -------- | ------- | ----------- |
| No arguments |      |          |         |             |

**Return**: `array<numeric>`

### `getCurrentRequestCount`

Returns the current request count.  Defaults to `1`. The only time this will increase is if `retries` have been configured for the request.

| Name         | Type | Required | Default | Description |
| ------------ | ---- | -------- | ------- | ----------- |
| No arguments |      |          |         |             |

**Return**: `numeric`

### `getRetryPredicate`

Returns the current callback function that is called to decide if a request should be retried.  This is only called if there are available retries left.

This callback is passed the response and the request as parameters.

A request will be retried if this function returns `true`.

In this function, the passed in request can be modified for the next retry.

{% hint style="warning" %}
In most cases, you do not need to interact with this method directly.  Use the `retry` method instead.
{% endhint %}

| Name         | Type | Required | Default | Description |
| ------------ | ---- | -------- | ------- | ----------- |
| No arguments |      |          |         |             |

**Return**: `numeric`

### `setProperties`

Quickly set many request properties using a struct. The key should be the name of one of the properties on the request, e.g. `url`, `headers`, `method`, `body`.

| Name       | Type   | Required | Default | Description                                                                                                                                   |
| ---------- | ------ | -------- | ------- | --------------------------------------------------------------------------------------------------------------------------------------------- |
| properties | struct | true     |         | A struct of properties to set. Each property name will be set on the request. Properties that don't exist on the request will throw an error. |

**Return**: `HyperRequest`

### `setHttpClient`

Sets the [HTTP Client](/customizing-hyper/custom-http-clients) to use for the request. The client should conform to the `HyperHttpClientInterface` (though it does not need to use the `implements` keyword).

| Name       | Type                       | Required | Default | Description                            |
| ---------- | -------------------------- | -------- | ------- | -------------------------------------- |
| httpClient | `HyperHttpClientInterface` | `true`   |         | The httpClient to use for the request. |

**Return**: `HyperRequest`

### `setInterceptorService`

Sets the [ColdBox Interceptor Service](https://coldbox.ortusbooks.com/the-basics/interceptors) to announce request and response interception points. A noop option is provided in the `init` for non-ColdBox usage.

| Name               | Type | Required | Default | Description                                     |
| ------------------ | ---- | -------- | ------- | ----------------------------------------------- |
| interceptorService | any  | `true`   |         | The interceptor service to use for the request. |

**Return**: `HyperRequest`

### `setAsyncManager`

Sets the [ColdBox AsyncManager](https://coldbox.ortusbooks.com/digging-deeper/promises-async-programming) to send requests asynchronously. A noop option is provided in the `init` for non-ColdBox usage.

| Name         | Type | Required | Default | Description                              |
| ------------ | ---- | -------- | ------- | ---------------------------------------- |
| asyncManager | any  | `true`   |         | The asyncManager to use for the request. |

**Return**: `HyperRequest`

### `getMemento`

Returns a struct representing this `HyperRequest`.

| Name     | Type    | Required | Default | Description                                            |
| -------- | ------- | -------- | ------- | ------------------------------------------------------ |
| excludes | `array` | `false`  | `[]`    | An array of keys to exclude from the returned memento. |

**Return**:

```json
{
    "requestID"           : getRequestID(),
    "baseUrl"             : getBaseUrl(),
    "url"                 : getUrl(),
    "fullUrl"             : getFullUrl(),
    "method"              : getMethod(),
    "queryParams"         : getQueryParams(),
    "headers"             : getHeaders(),
    "cookies"             : getCookies(),
    "files"               : getFiles(),
    "bodyFormat"          : getBodyFormat(),
    "body"                : getBody(),
    "referrer"            : isNull( variables.referrer ) ? "" : variables.referrer,
    "throwOnError"        : getThrowOnError(),
    "timeout"             : getTimeout(),
    "maximumRedirects"    : getMaximumRedirects(),
    "authType"            : getAuthType(),
    "username"            : getUsername(),
    "password"            : getPassword(),
    "clientCert"          : isNull( variables.clientCert ) ? "" : variables.clientCert,
    "clientCertPassword"  : isNull( variables.clientCertPassword ) ? "" : variables.clientCertPassword,
    "domain"              : getDomain(),
    "workstation"         : getWorkstation(),
    "resolveUrls"         : getResolveUrls(),
    "encodeUrl"           : getEncodeUrl(),
    "retries"             : getRetries(),
    "currentRequestCount" : getCurrentRequestCount()
};
```

### `debug`

Creates a debug representation of the HTTP request for the current HTTP client.

{% hint style="danger" %}
**Throws**: `NoUrlException` when no URL is set.
{% endhint %}

| Name         | Type | Required | Default | Description |
| ------------ | ---- | -------- | ------- | ----------- |
| No arguments |      |          |         |             |

**Return**: Dependent on the configured HTTP Client.  See specific HTTP Client documentation for details.


# HyperResponse

The `HyperResponse` component is a read-only wrapper to easily grab different information about the response.

### `getResponseId`

Gets the unique response ID representing this response.

| Name         | Type | Required | Default | Description |
| ------------ | ---- | -------- | ------- | ----------- |
| No arguments |      |          |         |             |

**Return**: `String`

### `getStatusCode`

Gets the status code for the response.

| Name         | Type | Required | Default | Description |
| ------------ | ---- | -------- | ------- | ----------- |
| No arguments |      |          |         |             |

**Return**: `numeric`

### `getStatusText`

Gets the status text for the response.

| Name         | Type | Required | Default | Description |
| ------------ | ---- | -------- | ------- | ----------- |
| No arguments |      |          |         |             |

**Return**: `String`

### `getStatus`

Returns the status code and status text as a single string.

| Name         | Type | Required | Default | Description |
| ------------ | ---- | -------- | ------- | ----------- |
| No arguments |      |          |         |             |

**Return**: `String`

### `getData`

Gets the data for the response.

| Name         | Type | Required | Default | Description |
| ------------ | ---- | -------- | ------- | ----------- |
| No arguments |      |          |         |             |

**Return**: `String`

### `getRequestID`

Returns the id of the request to which this response is related.

| Name         | Type | Required | Default | Description |
| ------------ | ---- | -------- | ------- | ----------- |
| No arguments |      |          |         |             |

**Return**: `String`

### `getRequest`

Gets the [HyperRequest](/making-requests/hyperrequest) instance associated with this response.

| Name         | Type | Required | Default | Description |
| ------------ | ---- | -------- | ------- | ----------- |
| No arguments |      |          |         |             |

**Return**: [`HyperRequest`](/making-requests/hyperrequest)

### `getCharset`

Gets the charset value for the response.

| Name         | Type | Required | Default | Description |
| ------------ | ---- | -------- | ------- | ----------- |
| No arguments |      |          |         |             |

**Return**: `String`

### `getTimestamp`

Gets the timestamp for when this response was received.

| Name         | Type | Required | Default | Description |
| ------------ | ---- | -------- | ------- | ----------- |
| No arguments |      |          |         |             |

**Return**: `DateTime`

### `getExecutionTime`

Gets the execution time of the request, in milliseconds.

| Name         | Type | Required | Default | Description |
| ------------ | ---- | -------- | ------- | ----------- |
| No arguments |      |          |         |             |

**Return**: `numeric`

### `json`

Returns the data of the request as deserialized `JSON`.

{% hint style="danger" %}
**Throws**: `DeserializeJsonException` if the response is not `JSON`.
{% endhint %}

| Name         | Type | Required | Default | Description |
| ------------ | ---- | -------- | ------- | ----------- |
| No arguments |      |          |         |             |

**Return**: `any`

### `isSuccess`

Returns true if the request status code is considered successful.

| Name         | Type | Required | Default | Description |
| ------------ | ---- | -------- | ------- | ----------- |
| No arguments |      |          |         |             |

**Return**: `boolean`

### `isOK`

Returns true if the request status code is `200 OK`.

| Name         | Type | Required | Default | Description |
| ------------ | ---- | -------- | ------- | ----------- |
| No arguments |      |          |         |             |

**Return**: `boolean`

### `isCreated`

Returns true if the request status code is `201 Created`.

| Name         | Type | Required | Default | Description |
| ------------ | ---- | -------- | ------- | ----------- |
| No arguments |      |          |         |             |

**Return**: `boolean`

### `isRedirect`

Returns true if the request status code is considered a redirect.

| Name         | Type | Required | Default | Description |
| ------------ | ---- | -------- | ------- | ----------- |
| No arguments |      |          |         |             |

**Return**: `boolean`

### `isError`

Returns true if the request status code is considered either a client error (4xx status code) or a server error (5xx status code).

| Name         | Type | Required | Default | Description |
| ------------ | ---- | -------- | ------- | ----------- |
| No arguments |      |          |         |             |

**Return**: `boolean`

### `isClientError`

Returns true if the request status code is considered a client error (4xx status code).

| Name         | Type | Required | Default | Description |
| ------------ | ---- | -------- | ------- | ----------- |
| No arguments |      |          |         |             |

**Return**: `boolean`

### `isUnauthorized`

Returns true if the request status code is `401 Unauthorized`.

| Name         | Type | Required | Default | Description |
| ------------ | ---- | -------- | ------- | ----------- |
| No arguments |      |          |         |             |

**Return**: `boolean`

### `isForbidden`

Returns true if the request status code is `403 Forbidden`.

| Name         | Type | Required | Default | Description |
| ------------ | ---- | -------- | ------- | ----------- |
| No arguments |      |          |         |             |

**Return**: `boolean`

### `isNotFound`

Returns true if the request status code is `404 Not Found`.

| Name         | Type | Required | Default | Description |
| ------------ | ---- | -------- | ------- | ----------- |
| No arguments |      |          |         |             |

**Return**: `boolean`

### `isServerError`

Returns true if the request status code is considered a server error (5xx status code).

| Name         | Type | Required | Default | Description |
| ------------ | ---- | -------- | ------- | ----------- |
| No arguments |      |          |         |             |

**Return**: `boolean`

### `hasHeader`

Checks if a header exists in the response.

| Name | Type     | Required | Default | Description                      |
| ---- | -------- | -------- | ------- | -------------------------------- |
| name | `String` | `true`   |         | The name of the header to check. |

**Return**: `boolean`

### `getHeader`

Gets the value of a header from the response.

| Name         | Type     | Required | Default | Description                                       |
| ------------ | -------- | -------- | ------- | ------------------------------------------------- |
| name         | `String` | `true`   |         | The name of the header to retrieve.               |
| defaultValue | `any`    | `false`  | `""`    | The value to return if the header does not exist. |

**Return**: `any`

### `getCookies`

Caches the result of parsing the `Set-Cookie` header and returns it.

| Name         | Type | Required | Default | Description |
| ------------ | ---- | -------- | ------- | ----------- |
| No arguments |      |          |         |             |

**Return**: `struct`

### `persistCookies`

Parses and saves the cookies to the cookie scope.

| Name         | Type | Required | Default | Description |
| ------------ | ---- | -------- | ------- | ----------- |
| No arguments |      |          |         |             |

**Return**: `HyperResponse`

### `getMemento`

Gets a serializable representation of the response.

| Name     | Type    | Required | Default | Description                                            |
| -------- | ------- | -------- | ------- | ------------------------------------------------------ |
| excludes | `array` | `false`  | `[]`    | An array of keys to exclude from the returned memento. |

**Return**:

```json
{
    "responseID"    : getResponseID(),
    "requestID"     : getRequestID(),
    "statusCode"    : getStatusCode(),
    "statusText"    : getStatusText(),
    "status"        : getStatus(),
    "data"          : getData(),
    "charset"       : getCharset(),
    "headers"       : getHeaders(),
    "timestamp"     : getTimestamp(),
    "executionTime" : getExecutionTime(),
    "cookies"       : getCookies()
}
```


# Hyper Clients

Hyper allows you to configure defaults for your requests as custom Hyper Clients. This is particularly useful for reducing boilerplate in your application.

Defaults are set on the `HyperBuilder` instance. The easiest way to do this is to configure it in WireBox. In an `afterAspectsLoad` method, you can get a reference to a `HyperBuilder`, configure it as you would for a request, and then call the `registerAs` method passing in your desired WireBox alias.

```cfscript
// config/WireBox.cfc
component {

   // ...
   
   function afterApsectsLoad() {
       injector.getInstance( "HyperBuilder@hyper" )
           .setBaseUrl( "https://swapi.dev/api" )
           .asJson()
           .registerAs( "StarWarsClient" );
   }

}
```

{% hint style="info" %}
Putting the registration code in `afterAspectsLoad` is required so Hyper can be loaded and available for injection.
{% endhint %}

Now, you can inject this pre-configured builder wherever you need in your application:

```js
component {

    property name="StarWarsClient" inject="StarWarsClient";

    function findUser( id ) {
        return variables.StarWarsClient.get( "/people/#id#" );
    }

}
```

You can alternatively create the clients by passing in the desired defaults to the `initWith` method of a WireBox mapping.  These arguments must match the [`HyperRequest` property names](#hyperrequest-property-names).

```js
// config/WireBox.cfc
component {

    function configure() {
        map( "StarWarsClient" )
            .to( "hyper.models.HyperBuilder" )
            .asSingleton()
            .initWith(
                baseUrl = "https://swapi.dev/api"
            );
    }

}
```

You can even create multiple clients using this approach:

```js
// config/WireBox.cfc
component {

    function configure() {
        // ...
    }

    function afterAspectsLoad() {
        injector.getInstance( "HyperBuilder@hyper" )
           .setBaseUrl( "https://swapi.dev/api" )
           .asJson()
           .registerAs( "StarWarsClient" );

       injector.getInstance( "HyperBuilder@hyper" )
           .setBaseUrl( "https://api.github.com" )
           .asJson()
           .withHeaders( {
               "Authorization": coldbox.getUtil().getSystemSetting( "GITHUB_TOKEN" )
           } )
           .registerAs( "GitHubClient" );
    }

}
```

You can also set or change the defaults by either passing the key / value pairs in to the `init` method or by calling the appropriate `HyperRequest` method on the `HyperBuilder.defaults` property.

```js
var hyper = new Hyper.models.HyperBuilder(
    baseUrl = "https://api.github.com"
);
hyper.defaults.withHeaders( { "Authorization" = token } );
```

#### HyperRequest property names

```cfscript
/**
* The httpClient to use for the request
*/
property name="httpClient";

/**
* The baseURL for the request.
* e.g. https://api.github.com/
*/
property name="baseUrl" default="";

/**
* The URL for the request.
* It can either be a full url
* or a URI resource for use with the baseURL.
* e.g. /repos
*/
property name="url" default="";

/**
* Setting this to true will change all relative urls in the document to absolute.
*/
property name="resolveUrls" default="false";

/**
* Setting this to false will not automatically encode the url passed.
* WARNING: Setting this to false is not supported on Adobe engines.
*/
property name="encodeUrl" default="true";

/**
* The HTTP method for the request.
*/
property name="method" default="GET";

/**
* The username for the request for basic auth.
*/
property name="username" default="";

/**
* The password for the request for basic auth.
*/
property name="password" default="";

/**
* Timeout, in seconds, for the request.
*/
property name="timeout" default="10";

/**
* The maximum number of redirects to follow.
* A value of `*` will follow redirects infinitely.
*/
property name="maximumRedirects" default="*";

/**
* The body to send with the request.
* How the body is serialized is
* determined by the bodyFormat.
*/
property name="body" default="";

/**
* The format to serialize the body.
* e.g. `json` or `formFields`
*/
property name="bodyFormat" default="json";

/**
* The referring response in the case of redirects.
*/
property name="referrer";

/**
* A struct of headers for the request.
*/
property name="headers";

/**
* A struct of query parameters for the request.
*/
property name="queryParams";

/**
* Flag to throw on a cfhttp error.
*/
property name="throwOnError" default="false";

/**
* The full path to a PKCS12 format file that contains the client certificate for the request.
*/
property name="clientCert";

/**
* 	Password used to decrypt the client certificate.
*/
property name="clientCertPassword";

/**
* The domain for the request for NTLM auth.
*/
property name="domain" default="";

/**
* The workstation for the request for NTLM auth.
*/
property name="workstation" default="";

/**
* The authType for the request
*/
property name="authType" default="BASIC";

/**
* An array of callback functions to call
* before firing off a request.
*/
property name="requestCallbacks" type="array";

/**
* An array of callback functions to call
* after receiving a response.
*/
property name="responseCallbacks" type="array";
```

If you need per-request or per-response manipulation of defaults, use the [`requestCallbacks`](/making-requests/hyperrequest#withrequestcallback) and [`responseCallbacks`](/making-requests/hyperrequest#withresponsecallback) hooks.

```cfscript
map( "ApiClient" )
    .to( "hyper.models.HyperBuilder" )
    .asSingleton()
    .initWith(
        baseUrl = getColdBox().getUtil().getSystemSetting( "API_URL" ),
        requestCallbacks = [
            // provide the current user's token for the request
            function( req ) {
                var auth = getWireBox().getInstance( "AuthenticationService@cbauth" );
                req.withHeaders( "Authorization", auth.user().getApiToken() );
            }
        ],
        responseCallbacks = [
            // map custom `error` property to an exception
            function ( res ) {
                if ( !res.isError() ) {
                    return;
                }
                
                var body = res.json();
                throw(
                    type = "ApiError",
                    message = body.error.message,
                    detail = body.error.code
                );
            }
        ]
    );
```


# Custom HTTP Clients

By default, Hyper makes HTTP requests using `cfhttp` under the hood.  This can be swapped out by any compatible HTTP client that follows the `HyperHttpClientInterface`.

```cfscript
/**
 * Responsible for executing the HyperRequest and mapping it to a HyperResponse
 */
interface displayname="HyperHttpClientInterface" {

	/**
	 * Execute the HyperRequest and map it to a HyperResponse.
	 *
	 * @req     The HyperRequest to execute.
	 *
	 * @returns A HyperResponse of the executed request.
	 */
	public HyperResponse function send( required HyperRequest req );

	/**
	 * Return a struct of information showing how the client will execute the HyperRequest.
	 * This will be used by a developer to debug any differences between the generated
	 * request values and the expected request values.
	 *
	 * @req     The HyperRequest to debug.
	 *
	 * @returns A struct of information detailing how the client would execute the HyperRequest.
	 */
	public struct function debug( required HyperRequest req );

}
```


# CfhttpHttpClient

### `debug`

Return a struct of information showing how the client will execute the [`HyperRequest`](/making-requests/hyperrequest). This will be used by a developer to debug any differences between the generated request values and the expected request values.

| Name | Type                                            | Required | Default | Description                                                   |
| ---- | ----------------------------------------------- | -------- | ------- | ------------------------------------------------------------- |
| req  | [`HyperRequest`](/making-requests/hyperrequest) | `true`   |         | The [`HyperRequest`](/making-requests/hyperrequest) to debug. |

**Return**:

```json
{
    "attributes" : attrCollection,
    "body"       : {
        "headers" : cfhttpHeaders,
        "params"  : cfhttpParams,
        "files"   : cfhttpFiles,
        "body"    : cfhttpBody,
        "cookies" : cfhttpCookies
    }
}
```


# Interceptors

Hyper announces two [interception points through ColdBox](https://coldbox.ortusbooks.com/the-basics/interceptors): `onHyperRequest` and `onHyperResponse`.

### onHyperRequest

This interception point is announced before the request is sent.  It receives the `request` as the only parameter inside `data`.

### onHyperResponse

This interception point is announced after the response is received.  It receives the `response` and the `request` inside `data`.


# Faking Requests

Hyper has the ability to fake requests and return fake responses as a result.  This is perfect for [testing](https://testbox.ortusbooks.com/) scenarios where you don't actually want to make an HTTP request.

{% hint style="warning" %}
Non-ColdBox users will need to add a mapping to the [`Globber`](https://forgebox.io/view/globber) dependency included with Hyper.

```cfscript
// Application.cfc
component {
    this.mappings[ "/globber" ] = "/path/to/hyper" & "/modules/globber";
}
```

{% endhint %}

## Faking All Requests

Faking is enabled on a [`HyperBuilder`](/making-requests/hyperbuilder) instance, either the built-in one provided by Hyper or a [custom Hyper client](/customizing-hyper/custom-http-clients) you have created.

To enable faking requests, call the `fake` method:

```cfscript
var hyper = new Hyper.models.HyperBuilder();
hyper.fake();
```

After calling the `fake` method, all requests created by this `HyperBuilder` will be faked.  By default, they will return `200 OK` responses with empty bodies.

```cfscript
hyper.fake();
var res = hyper.get( "https://google.com" );
expect( res.getStatus() ).toBe( "200 OK" );
```

## Fake Configuration

When calling the `fake` method, you can provide a struct mapping URL patterns to response generator functions.

```cfscript
hyper.fake( {
    "https://google.com/*": function( newFakeResponse, req ) {
         return newFakeResponse( 404, "Not Found" );
    }
} );
```

The key is a URL pattern.  The pattern can be any valid glob. If the pattern is matched by the [`fullUrl`](/making-requests/hyperrequest#getfullurl) of the `HyperRequest`, then the response generator function will be called and the results returned.

A helper function, `newFakeResponse`, is provided as the first argument to the response generator function.  The current request is provided as the second argument.

## FakeHyperResponse

The resposne generator function must return a `FakeHyperResponse` instance.  A `FakeHyperResponse` instance acts similar to a normal `HyperResponse` except the properties are not read only.  Once you have an instance of your `FakeHyperResponse`, you can continue to set any properties you need.

```cfscript
hyper.fake( {
    "https://jsonplaceholder.typicode.com/posts": function( newFakeResponse, req ) {
         return newFakeResponse()
             .setStatusCode( 201 )
             .setStatusText( "Created" )
             .setData( serializeJSON( {
                 "id": 101,
                 "title": "foo",
                 "body": "bar",
                 "userId": 1
             } ) );
    }
} );
```

You can also pass the values to the `newFakeResponse` function, if you'd like.

```cfscript
hyper.fake( {
    "https://jsonplaceholder.typicode.com/posts": function( newFakeResponse, req ) {
         return newFakeResponse( 201, "Created", serializeJSON( {
             "id": 101,
             "title": "foo",
             "body": "bar",
             "userId": 1
         } ) );
    }
} );
```

### `newFakeResponse`

Creates a new `FakeHyperResponse` instance.

<table><thead><tr><th width="160">Name</th><th>Type</th><th>Required</th><th>Default</th><th>Description</th></tr></thead><tbody><tr><td>statusCode</td><td><code>numeric</code></td><td><code>false</code></td><td>200</td><td>The status code for the fake response.</td></tr><tr><td>statusText</td><td><code>string</code></td><td><code>false</code></td><td><code>"OK"</code></td><td>The status text for the fake response.</td></tr><tr><td>data</td><td><code>string</code></td><td><code>false</code></td><td><code>""</code></td><td>The data for the fake response.</td></tr><tr><td>headers</td><td><code>{ string: string }</code></td><td><code>false</code></td><td><code>{}</code></td><td>The headers for the fake response.</td></tr><tr><td>executionTime</td><td><code>numeric</code></td><td><code>false</code></td><td>0</td><td>The execution time for the fake response.</td></tr><tr><td>charset</td><td><code>string</code></td><td><code>false</code></td><td><code>"UTF-8"</code></td><td>The charset for the fake response.</td></tr><tr><td>timestamp</td><td><code>datetime</code></td><td><code>false</code></td><td><code>now()</code></td><td>The timestamp of the fake response.</td></tr></tbody></table>

**Return**: `FakeHyperResponse`

## Sequencing Fake Responses

In addition to returning a single `FakeHyperResponse` per pattern, you can return an array of `FakeHyperResponse` instances.  These will be returned in a sequence.

```cfscript
hyper.fake( {
    "https://jsonplaceholder.typicode.com/posts": function( newFakeResponse, req ) {
         return [
             newFakeResponse( 201, "Created", serializeJSON( {
                 "id": 101,
                 "title": "foo",
                 "body": "bar",
                 "userId": 1
             } ) ),
             newFakeResponse( 422, "Unprocessable Entity", "Duplicate title" )
         ];
    }
} );

var resA = hyper.post( "https://jsonplaceholder.typicode.com/posts", { /* ... */ } );
expect( resA.getStatus() ).toBe( "201 Created" );

var resB = hyper.post( "https://jsonplaceholder.typicode.com/posts", { /* ... */ } );
expect( resA.getStatus() ).toBe( "422 Unprocessable Entity" );
```

If you continue to make requests to the same pattern after the sequence has been exhausted, an exception will be thrown.

```cfscript
hyper.fake( {
    "https://jsonplaceholder.typicode.com/posts": function( newFakeResponse, req ) {
         return [
             newFakeResponse( 201, "Created", serializeJSON( {
                 "id": 101,
                 "title": "foo",
                 "body": "bar",
                 "userId": 1
             } ) ),
             newFakeResponse( 422, "Unprocessable Entity", "Duplicate title" )
         ];
    }
} );

var resA = hyper.post( "https://jsonplaceholder.typicode.com/posts", { /* ... */ } );
expect( resA.getStatus() ).toBe( "201 Created" );

var resB = hyper.post( "https://jsonplaceholder.typicode.com/posts", { /* ... */ } );
expect( resA.getStatus() ).toBe( "422 Unprocessable Entity" );

// THROWS a `HyperFakeSequenceExhausted` exception
var resC = hyper.post( "https://jsonplaceholder.typicode.com/posts", { /* ... */ } );
```

## Preventing Stray Requests

By default, Hyper returns a default `FakeHyperResponse` for every request that doesn't match one of your configured patterns.  You can instead cause Hyper to throw an exception if it encounters one of these stray requests by calling the `preventStrayRequests` method.

```cfscript
hyper.fake( {
    "https://google.com/*": function( newFakeResponse, req ) {
         return newFakeResponse( 404, "Not Found" );
    }
} ).preventStrayRequests();

// THROWS a `HyperFakeStrayRequest` exception
var res = hyper.get( "https://github.com" );
```

## Making Assertions

In addition to assertions made against the `FakeHyperResponse` instances returned, you can also make assertions using the `HyperBuilder` instance you faked.  These come in the form of methods on the `HyperBuilder` instance as well as custom TestBox Assertions.

### HyperBuilder Method Assertions

The following methods are available to make assertions in your tests about the requests that were sent.

#### getFakeRequestCount

Returns the number of fake requests that have been made.

| Name         | Type | Required | Default | Description |
| ------------ | ---- | -------- | ------- | ----------- |
| No arguments |      |          |         |             |

**Return**: `numeric`

#### wasRequestSent

Returns whether a request has been made that matches the `predicate`. Each request that has been made is passed to the `predicate` in order. If the `predicate` returns `true`, the request is considered a match and `true` is returned. If no request passes the `predicate`, `false` is returned.

| Name      | Type       | Required | Default | Description                                                                                            |
| --------- | ---------- | -------- | ------- | ------------------------------------------------------------------------------------------------------ |
| predicate | `function` | `true`   |         | A callback function that returns true if the request matches the criteria and returns false otherwise. |

**Return**: `boolean`

### Custom TestBox Assertions

You can register [custom TestBox assertions](https://testbox.ortusbooks.com/digging-deeper/expectations/custom-matchers) provided by Hyper for more readable tests and test failure messages.

You must [register](https://testbox.ortusbooks.com/digging-deeper/expectations/custom-matchers#class-matchers) these assertions before using them.

```cfscript
component extends="testbox.system.BaseSpec" {

    function beforeAll() {
        addMatchers( "hyper.models.TestBoxMatchers" )
    }
    
    function run() {
        // ...
    }

}
```

The following custom assertions are provided:

#### toHaveSentRequest

This takes in the `HyperBuilder` instance as the actual and a predicate function as the expected. The predicate function is passed to the `HyperBuilder` instance's `wasRequestSent` method.

```cfscript
hyper.fake();

hyper.get( "https://google.com" );

expect( hyper ).toHaveSentRequest( function( req ) {
    return req.getFullUrl() == "https://google.com";
} );

expect( hyper ).notToHaveSentRequest( function( req ) {
    return req.getFullUrl() == "https://github.com";
} );
```

#### toHaveSentCount

This takes in the `HyperBuilder` instance as the actual and an integer number of requests that should have been sent.

```cfscript
hyper.fake();

hyper.get( "https://google.com" );

expect( hyper ).toHaveSentCount( 1 );
expect( hyper ).notToHaveSentCount( 2 );
```

#### toHaveSentNothing

This takes in the `HyperBuilder` instance as the actual and no other parameters.

```cfscript
hyper.fake();

expect( hyper ).toHaveSentNothing();

hyper.get( "https://google.com" );

expect( hyper ).notToHaveSentNothing();
```

## Resetting the Builder

To reset the sent request counts and sequences but keep the fake configuration, use the `resetFakes` method:

```javascript
hyper.fake();

hyper.get( "https://google.com" );

expect( hyper ).toHaveSentCount( 1 );

hyper.resetFakes();

expect( hyper ).toHaveSentNothing();
```

To reset the `HyperBuilder` instance to normal operation call the `clearFakes` method:

```cfscript
hyper.fake();

hyper.get( "https://google.com" );

hyper.clearFakes();
```

{% hint style="info" %}
These are useful methods to call in an [`afterEach`](https://testbox.ortusbooks.com/in-depth/life-cycle-methods/bdd#aftereach-body-data) block in TestBox to make sure you are only faking requests when you want to.
{% endhint %}


