---
title: "OpenAPIServiceConnector"
id: openapiserviceconnector
slug: "/openapiserviceconnector"
description: "`OpenAPIServiceConnector` is a component that acts as an interface between the Haystack ecosystem and OpenAPI services."
---

# OpenAPIServiceConnector

`OpenAPIServiceConnector` is a component that acts as an interface between the Haystack ecosystem and OpenAPI services.

:::tip[Consider using MCP instead]

These OpenAPI components are a legacy way to connect Haystack to external APIs. For most use cases, we recommend the [`MCPTool`](../../tools/mcptool.mdx) instead: it is the modern, standardized way to give your pipelines and agents access to external tools and services.

:::

<div className="key-value-table">

|  |  |
| --- | --- |
| **Most common position in a pipeline** | Flexible |
| **Mandatory run variables** | `messages`: A list of [`ChatMessage`](../../concepts/data-classes/chatmessage.mdx)  objects where the last message must be from the assistant and contain tool calls.  <br /> <br />`service_openapi_spec`: OpenAPI specification of the service being invoked. It can be YAML/JSON, and all ref values must be resolved.  <br /> <br />`service_credentials`: Authentication credentials for the service. We currently support two OpenAPI spec v3 security schemes:  <br /> <br />1. http – for Basic, Bearer, and other HTTP authentication schemes;  <br />2. apiKey – for API keys and cookie authentication. |
| **Output variables** | `service_response`: A list of [`ChatMessage`](../../concepts/data-classes/chatmessage.mdx)  objects where each message corresponds to a tool call invocation.  <br />If a message contains multiple tool calls, there will be multiple responses. |
| **API reference** | [OpenAPI](/reference/integrations-openapi) |
| **GitHub link** | https://github.com/deepset-ai/haystack-core-integrations/tree/main/integrations/openapi |
| **Package name** | `openapi-haystack` |

</div>

## Overview

`OpenAPIServiceConnector` acts as a bridge between Haystack ecosystem and OpenAPI services. This component works by using information from a `ChatMessage` to dynamically invoke service methods. It handles parameter payload parsing from `ChatMessage`, service authentication, method invocation, and response formatting, making it easier to integrate OpenAPI services.

To use `OpenAPIServiceConnector`, you need to install the `openapi-haystack` package with:

```shell
pip install openapi-haystack
```

`OpenAPIServiceConnector` component doesn’t have any init parameters.

## Usage

### On its own

This component is primarily meant to be used in pipelines, as [`OpenAPIServiceToFunctions`](../converters/openapiservicetofunctions.mdx), in tandem with an LLM with tool calling capabilities, resolves the actual tool call parameters that are injected as invocation parameters for `OpenAPIServiceConnector`.

### In a pipeline

Let's say we're linking the Serper search engine to a pipeline. Here, `OpenAPIServiceConnector` uses the abilities of `OpenAPIServiceToFunctions`. `OpenAPIServiceToFunctions` first fetches and changes the [Serper's OpenAPI specification](https://bit.ly/serper_dev_spec) into function definitions that an LLM with tool calling capabilities can understand. Then, `OpenAPIServiceConnector` activates the Serper service using this specification.

More precisely, `OpenAPIServiceConnector` dynamically calls methods defined in the Serper OpenAPI specification. This involves reading chat messages to extract tool call parameters, handling authentication with the Serper service, and making the right API calls. The connector makes sure that the method call follows the Serper API requirements, such as correct formatting requests and handling responses.

Note that we used Serper just as an example here. This could be any OpenAPI-compliant service.

:::info
To run the following code snippet, note that you have to have your own Serper and OpenAI API keys.
:::

```python
import json
import requests

from typing import Any

from haystack import Pipeline
from haystack.components.converters import OutputAdapter
from haystack.components.generators.chat import OpenAIChatGenerator
from haystack.dataclasses import ChatMessage
from haystack.dataclasses.byte_stream import ByteStream
from haystack_integrations.components.connectors.openapi import OpenAPIServiceConnector
from haystack_integrations.components.converters.openapi import (
    OpenAPIServiceToFunctions,
)


def prepare_fc_params(openai_functions_schema: dict[str, Any]) -> dict[str, Any]:
    return {
        "tools": [{"type": "function", "function": openai_functions_schema}],
        "tool_choice": {
            "type": "function",
            "function": {"name": openai_functions_schema["name"]},
        },
    }


serperdev_spec = requests.get("https://bit.ly/serper_dev_spec").json()
system_prompt = requests.get("https://bit.ly/serper_dev_system").text
user_prompt = "Why was Sam Altman ousted from OpenAI?"

pipe = Pipeline()
pipe.add_component("spec_to_functions", OpenAPIServiceToFunctions())
pipe.add_component(
    "prepare_fc_adapter",
    OutputAdapter(
        "{{functions[0] | prepare_fc}}",
        dict[str, Any],
        {"prepare_fc": prepare_fc_params},
    ),
)
pipe.add_component("functions_llm", OpenAIChatGenerator())
pipe.add_component("openapi_connector", OpenAPIServiceConnector())
pipe.add_component(
    "message_adapter",
    OutputAdapter(
        "{{system_message + service_response}}",
        list[ChatMessage],
        unsafe=True,
    ),
)
pipe.add_component("llm", OpenAIChatGenerator())

pipe.connect("spec_to_functions.functions", "prepare_fc_adapter.functions")
pipe.connect(
    "spec_to_functions.openapi_specs",
    "openapi_connector.service_openapi_spec",
)
pipe.connect("prepare_fc_adapter", "functions_llm.generation_kwargs")
pipe.connect("functions_llm.replies", "openapi_connector.messages")
pipe.connect("openapi_connector.service_response", "message_adapter.service_response")
pipe.connect("message_adapter", "llm.messages")

result = pipe.run(
    data={
        "functions_llm": {
            "messages": [
                ChatMessage.from_system("Only do tool/function calling"),
                ChatMessage.from_user(user_prompt),
            ],
        },
        "openapi_connector": {
            "service_credentials": serper_dev_key,
        },
        "spec_to_functions": {
            "sources": [ByteStream.from_string(json.dumps(serperdev_spec))],
        },
        "message_adapter": {
            "system_message": [ChatMessage.from_system(system_prompt)],
        },
    },
)

print(result["llm"]["replies"][0].text)

# Sam Altman was ousted from OpenAI on November 17, 2023, following
# a "deliberative review process" by the board of directors. The board concluded
# that he was not "consistently candid in his communications". However, he
# returned as CEO just days after his ouster.
```
