> ## Documentation Index
> Fetch the complete documentation index at: https://extended-openai-conversation.mintlify.site/llms.txt
> Use this file to discover all available pages before exploring further.

# REST Functions

> Fetch data from external REST APIs

REST functions retrieve data from external HTTP APIs and return the results to the AI. They're useful for integrating third-party services and real-time data sources.

## Configuration

```yaml theme={null}
function:
  type: rest
  resource: https://api.example.com/endpoint
  value_template: "{{ value_json.data }}"
```

<ParamField path="resource" type="string" required>
  The URL endpoint to fetch data from
</ParamField>

<ParamField path="value_template" type="string">
  Jinja2 template to format the API response. The response is available as `value_json`.
</ParamField>

## Template Processing

The `value_template` receives the API response as `value_json`:

<CodeGroup>
  ```jinja2 Extract Array theme={null}
  {{ value_json.items }}
  ```

  ```jinja2 Map Attributes theme={null}
  {{ value_json | map(attribute="name") | list }}
  ```

  ```jinja2 Filter Data theme={null}
  {{ value_json.results | selectattr('active', 'eq', true) | list }}
  ```

  ```jinja2 Format Output theme={null}
  {% for item in value_json.data %}
  - {{ item.name }}: {{ item.value }}
  {% endfor %}
  ```
</CodeGroup>

## Advanced Configuration

<AccordionGroup>
  <Accordion title="Headers">
    Add custom HTTP headers:

    ```yaml theme={null}
    function:
      type: rest
      resource: https://api.example.com/data
      headers:
        Authorization: "Bearer YOUR_TOKEN"
        Content-Type: "application/json"
      value_template: "{{ value_json }}"
    ```
  </Accordion>

  <Accordion title="Method">
    Change the HTTP method (default is GET):

    ```yaml theme={null}
    function:
      type: rest
      resource: https://api.example.com/data
      method: POST
      payload: '{"key": "{{ param }}"}'
      value_template: "{{ value_json }}"
    ```
  </Accordion>

  <Accordion title="Parameters">
    Add query parameters:

    ```yaml theme={null}
    function:
      type: rest
      resource: https://api.example.com/search
      params:
        q: "{{ query }}"
        limit: 10
      value_template: "{{ value_json.results }}"
    ```
  </Accordion>
</AccordionGroup>

## Use Cases

<CardGroup cols={2}>
  <Card title="Third-party APIs" icon="plug">
    Integrate external services and data sources
  </Card>

  <Card title="Real-time Data" icon="clock">
    Fetch current information like weather, stocks, or news
  </Card>

  <Card title="Search Services" icon="magnifying-glass">
    Query external search and lookup services
  </Card>

  <Card title="Status Checks" icon="circle-check">
    Monitor external service status and health
  </Card>
</CardGroup>

## Best Practices

<Steps>
  <Step title="Handle API errors">
    APIs may return errors. Use safe filters and defaults:

    ```jinja2 theme={null}
    {{ value_json.data | default('No data available') }}
    ```
  </Step>

  <Step title="Secure API keys">
    Never hardcode API keys in function definitions. Use Home Assistant secrets:

    ```yaml theme={null}
    headers:
      Authorization: "Bearer !secret api_token"
    ```
  </Step>

  <Step title="Format responses">
    Transform API responses into readable text for the AI:

    ```jinja2 theme={null}
    {% for item in value_json.items %}
    - {{ item.name }}: {{ item.status }}
    {% endfor %}
    ```
  </Step>

  <Step title="Add timeouts">
    Set reasonable timeouts for external APIs:

    ```yaml theme={null}
    function:
      type: rest
      resource: https://api.example.com/slow-endpoint
      timeout: 10
      value_template: "{{ value_json }}"
    ```
  </Step>
</Steps>

## Debugging

Enable logging to see API requests and responses:

```yaml theme={null}
logger:
  logs:
    custom_components.extended_openai_conversation: debug
```

Check the logs for:

* Request URL and parameters
* Response status code
* Response body
* Template rendering errors

## Examples

### Get Friend Names

Fetch and format data from a JSON API:

```yaml theme={null}
- spec:
    name: get_friend_names
    description: Use this function to get friend names
    parameters:
      type: object
      properties:
        dummy:
          type: string
          description: Not used (placeholder)
  function:
    type: rest
    resource: https://jsonplaceholder.typicode.com/users
    value_template: '{{value_json | map(attribute="name") | list }}'
```

<Frame>
  <img width="300" alt="REST API Example" src="https://github.com/jekalmin/extended_openai_conversation/assets/2917984/f968e328-5163-4c41-a479-76a5406522c1" />
</Frame>

### Cryptocurrency Prices

```yaml theme={null}
- spec:
    name: get_crypto_price
    description: Get current cryptocurrency price
    parameters:
      type: object
      properties:
        symbol:
          type: string
          description: Crypto symbol (e.g., BTC, ETH)
      required:
      - symbol
  function:
    type: rest
    resource: "https://api.coingecko.com/api/v3/simple/price"
    params:
      ids: "{{ symbol | lower }}"
      vs_currencies: "usd"
    value_template: >-
      {{ symbol | upper }}: ${{ value_json[symbol | lower].usd }}
```

### Weather Data

```yaml theme={null}
- spec:
    name: get_weather_external
    description: Get weather from external API
    parameters:
      type: object
      properties:
        city:
          type: string
          description: City name
      required:
      - city
  function:
    type: rest
    resource: "https://wttr.in/{{ city }}?format=j1"
    value_template: >-
      Weather in {{ city }}:
      Temperature: {{ value_json.current_condition[0].temp_C }}°C
      Condition: {{ value_json.current_condition[0].weatherDesc[0].value }}
      Humidity: {{ value_json.current_condition[0].humidity }}%
```

## Next Steps

<CardGroup cols={3}>
  <Card title="Scrape Functions" icon="spider" href="/functions/scrape">
    Extract web page data
  </Card>

  <Card title="Composite Functions" icon="layer-group" href="/functions/composite">
    Combine with other functions
  </Card>

  <Card title="Template Functions" icon="brackets-curly" href="/functions/template">
    Format REST data
  </Card>
</CardGroup>
