---
title: "Use Template Functions in Your Theme"
slug: use-template-functions
type: how-to
plugin: huxx-connect
summary: "Call configured endpoints from theme and plugin PHP with huxx_api(), handle failures with huxx_api_is_error(), and control caching, parameters, and extraction per call."
keywords: [template functions, huxx_api, PHP, error handling, themes]
version_added: 1.2.5
version_updated: 1.2.5
level: advanced
related: [template-functions, display-data-with-shortcodes, extract-values-with-keys, debug-api-requests]
---

The template functions are the PHP counterpart to the `[huxx_api]` shortcode: the same configured endpoints, called from a theme template, a block render callback, or another plugin. Unlike the shortcode, nothing is rendered for you — you receive the data and decide the markup. Full signatures are in the [Template Function Reference](/docs/connect/reference/template-functions/).

> **Quick version:**
>
> ```php
> $data = huxx_api( 'demo_api', 'get_products', array(
>     'query_variables' => array( 'limit' => 5 ),
>     'keys'            => 'products.[].title',
>     'cache'           => 300,
> ) );
>
> if ( huxx_api_is_error( $data ) ) {
>     $error = huxx_api_get_error( $data );
>     error_log( 'DummyJSON failed: ' . $error['message'] );
>     return;
> }
> ```
>
> `huxx_connect_api()`, `huxx_connect_is_error()`, and `huxx_connect_get_error()` are identical long-form names.

## Call an endpoint from a template

`huxx_api( $api_id, $endpoint_id, $args )` executes a configured endpoint and returns the response — for the default Results Format, a decoded PHP array. This example renders the DummyJSON product list in a theme template:

```php
<?php
// In a theme template file, e.g. page-products.php.
$data = huxx_api( 'demo_api', 'get_products' );

if ( ! huxx_api_is_error( $data ) && ! empty( $data['products'] ) ) : ?>
    <ul class="product-list">
        <?php foreach ( $data['products'] as $product ) : ?>
            <li>
                <?php echo esc_html( $product['title'] ); ?> —
                $<?php echo esc_html( number_format( (float) $product['price'], 2 ) ); ?>
            </li>
        <?php endforeach; ?>
    </ul>
<?php endif;
```

Output:

```html
<ul class="product-list">
    <li>Essence Mascara Lash Princess — $9.99</li>
    <li>Eyeshadow Palette with Mirror — $19.99</li>
</ul>
```

Always escape API data on output (`esc_html()`, `esc_url()`, `esc_attr()`) — the response comes from an external server and must be treated as untrusted.

## Handle errors before touching the data

A failed call does not return an array you can loop over. `huxx_api()` returns an `ErrorResponse` object on failure, or `false` when either id argument is empty. With `debug` set, a failure of the HTTP request itself is returned as an error array instead — but configuration failures (unknown API or endpoint id, deactivated API) return an `ErrorResponse` object regardless of `debug`. Check every response before use:

```php
<?php
$data = huxx_api( 'demo_api', 'get_products' );

if ( huxx_api_is_error( $data ) ) {
    $error = huxx_api_get_error( $data );
    error_log( sprintf(
        'HuxxConnect error %d: %s',
        $error['code'],
        $error['message']
    ) );
    return; // Render fallback content instead.
}
```

Output in the PHP error log when the API server is unreachable:

```
HuxxConnect error 503: Connection refused. The API server may be down or unreachable.
```

`huxx_api_is_error()` recognizes both forms a failure can take — the `ErrorResponse` object and its array conversion — so one check covers every case. `huxx_api_get_error()` returns the details as an array with the keys `_huxx_connect_error`, `code`, `message`, `original_response`, and `context`, or `null` when the response is not an error.

## Pass runtime arguments

The third parameter customizes a single call without touching the saved configuration. All entries are optional. This example uses a `product_detail` endpoint (GET `/products/{0}`) added to the demo API:

```php
<?php
$product = huxx_api( 'demo_api', 'product_detail', array(
    'endpoint_variables' => array( 1 ),                       // Fills {0} in the path /products/{0}.
    'query_variables'    => array( 'select' => 'id,title,price' ),
    'header_variables'   => array( 'X-Request-Source' => 'theme' ),
    'keys'               => '{title},{price}',
) );

print_r( $product );
```

Output:

```
Array
(
    [title] => Essence Mascara Lash Princess
    [price] => 9.99
)
```

- `endpoint_variables` — fills [path variables](/docs/connect/how-to/use-path-variables/); an indexed array maps by position, an associative array by name.
- `query_variables`, `header_variables`, `body_variables` — merge over the saved parameters; runtime values win. Body values for multipart endpoints may be structured arrays with `value`, `filename`, `type`, and `is_file`.
- `keys` — extraction path(s), string or array; see [Extract Values with the keys Syntax](/docs/connect/how-to/extract-values-with-keys/).
- `debug` — when `true`, a failure of the HTTP request itself returns the error as an array instead of an `ErrorResponse` object; configuration-lookup failures (unknown API or endpoint id) still return `ErrorResponse`. `huxx_api_is_error()` handles both forms.

Note that unlike the shortcode's comma-separated attribute strings, PHP arrays carry values with commas (like `select` above) without any escaping concerns.

## Override caching per call

Responses to GET requests are cached for the endpoint's configured [cache duration](/docs/connect/how-to/cache-endpoint-responses/). The `cache` argument overrides it for one call:

```php
<?php
// Force a fresh request — skip the cache entirely.
$fresh = huxx_api( 'demo_api', 'get_products', array( 'cache' => false ) );

// Cache this call's response for 10 minutes regardless of the endpoint setting.
$cached = huxx_api( 'demo_api', 'get_products', array( 'cache' => 600 ) );

echo esc_html( $fresh['total'] . ' / ' . $cached['total'] );
```

Output:

```
194 / 194
```

Both calls return the same decoded array — the difference is whether a stored copy may be served and how long the fresh response is kept. `false` or `0` disables caching for the call; a positive integer is the TTL in seconds. Only GET requests are ever cached.

## If it didn't work

- **`huxx_api()` returned `false`.** One of the first two arguments was empty. The function does not look anything up in that case — check that both ids are non-empty strings.
- **`huxx_api_is_error()` is true and the message says the API or endpoint was "not found".** The id doesn't match the configuration. Copy the exact ids from the API detail screen — they are slugs, not display names.
- **The call works but you see stale data.** A cached response is being served. Pass `'cache' => false` to confirm, then adjust the endpoint's cache duration — see [Cache Endpoint Responses](/docs/connect/how-to/cache-endpoint-responses/). Cache-served calls do not appear in the request log — only real HTTP requests are logged, so the absence of a new log entry confirms a cache hit. See [Debug API Requests](/docs/connect/how-to/debug-api-requests/).
