---
question: How do I write an integration class in a module?
kind: task
via_web: na
via_cli: available
via_python: available
via_api: na
via_config: na
ref_cli: abi new integration
ref_python: Integration
prereq: You need a module of your project. [Create a module](/capabilities/build/modules/creating-a-module) first.
next:
  - /capabilities/build/integrations/add-credentials
  - /capabilities/build/integrations/use-in-an-agent
  - /capabilities/build/knowledge-graph/creating-a-pipeline
---

# Create an integration

Integrations are the external API adapters in ABI. They are the smallest, most atomic units - they talk to a specific external service and nothing else. They do not depend on pipelines, workflows, or agents.

An integration is a subclass of `Integration` from `naas_abi_sdk.integration`, with an `IntegrationConfiguration` dataclass for its key and settings. The base classes are standard library only: bring an async HTTP client such as `httpx`. The module does not find or serve integrations: its workflows, pipelines and agents build them.

## Role in the stack

```text
External API  →  Integration  →  Pipeline (transforms to RDF)
                              →  Workflow (business logic)
                              →  Agent tool (direct invocation by the model)
```

An integration should:
- Handle authentication and HTTP communication.
- Return raw data from the external service.
- Offer LangChain tools through a module-level `as_tools()` function, when an agent uses it.

An integration must NOT:
- Write to the triple store directly.
- Depend on other ABI modules, or on services beyond what it needs for itself.
- Contain business logic.

## Web UI

Not applicable. Nexus has no screen that writes an integration: it is a Python class in a module. Use the CLI or Python on this page.

## CLI

### Scaffold the integration

From the module's folder (`src/my_module`):

```bash
abi new integration My
```

It writes `integrations/MyIntegration.py` and `integrations/MyIntegration_test.py`: the name is converted to PascalCase and `Integration` is appended. The arguments are `<name> [path]`; the default path is the package's `integrations/` folder. The command prints "Created MyIntegration.py (naas_abi_sdk). Nothing in the engine consumes it: build it in a workflow, pipeline or agent, with credentials from self.engine.services.secret (declare the secret service in ModuleDependencies)." The command is [`abi new integration`](/user-guide/reference/cli#abi-new-integration).

The scaffold holds a configuration with `api_key` and `base_url`, and an `async def ping()` that raises `IntegrationConnectionError` without a key. Its test runs offline: see [Test an integration](/capabilities/build/integrations/test-an-integration).

## Python

### Write the class

Filled in, the class looks like this:

```python title="integrations/MyIntegration.py"
from __future__ import annotations

from dataclasses import dataclass

import httpx
from naas_abi_sdk.integration import (
    Integration,
    IntegrationConfiguration,
    IntegrationConnectionError,
)


@dataclass
class MyIntegrationConfiguration(IntegrationConfiguration):
    """Credentials and settings for MyService."""

    api_key: str = ""
    base_url: str = "https://api.myservice.com"


class MyIntegration(Integration):
    __configuration: MyIntegrationConfiguration

    def __init__(self, configuration: MyIntegrationConfiguration):
        super().__init__(configuration)
        self.__configuration = configuration

    async def _make_request(
        self, endpoint: str, method: str = "GET", params: dict | None = None
    ) -> dict | list:
        try:
            async with httpx.AsyncClient(base_url=self.__configuration.base_url) as client:
                response = await client.request(
                    method,
                    endpoint,
                    headers={"Authorization": f"Bearer {self.__configuration.api_key}"},
                    params=params,
                )
        except httpx.TransportError as exc:
            raise IntegrationConnectionError(f"MyService: {exc}") from exc
        response.raise_for_status()
        return response.json()

    async def list_items(self, filter: str | None = None) -> list[dict]:
        """List items from MyService, optionally filtered."""
        params = {"filter": filter} if filter else None
        return await self._make_request("/items", params=params)

    async def get_item(self, item_id: str) -> dict:
        """Get a single item by ID."""
        return await self._make_request(f"/items/{item_id}")
```

Every call to the engine from a module is async, so write the integration's methods `async` too.

### Expose it as tools

By convention, an integration file also defines an `as_tools(configuration)` function at module level, which an agent of the module calls to get the tools. The base class has no such method:

```python title="integrations/MyIntegration.py"
def as_tools(configuration: MyIntegrationConfiguration) -> list:
    """Convert MyIntegration into LangChain tools."""
    from langchain_core.tools import StructuredTool
    from pydantic import BaseModel, Field

    integration = MyIntegration(configuration)

    class ListItemsSchema(BaseModel):
        filter: str | None = Field(None, description="Optional filter expression")

    class GetItemSchema(BaseModel):
        item_id: str = Field(..., description="The ID of the item to retrieve")

    return [
        StructuredTool.from_function(
            coroutine=integration.list_items,
            name="list_myservice_items",
            description="List items from MyService. Use when the user asks to see or search items.",
            args_schema=ListItemsSchema,
        ),
        StructuredTool.from_function(
            coroutine=integration.get_item,
            name="get_myservice_item",
            description="Get a specific item from MyService by its ID.",
            args_schema=GetItemSchema,
        ),
    ]
```

A module's agent calls its tools with `ainvoke`, so a `coroutine=` tool runs on the module's event loop. LangChain comes with the `naas-abi-sdk[agent]` extra, which a module that `abi new module` generated installs.

## REST API

Not applicable. There is no REST call that scaffolds an integration, and no API mounts integrations as routes. The full process list is the [API](/api).

## Config

Not applicable for the class. Credentials for the external API are on [Add credentials](/capabilities/build/integrations/add-credentials).

## Best practices

- **One integration per external service.** A `GitHubIntegration` for GitHub, a `SalesforceIntegration` for Salesforce.
- **Document all methods.** Agents use tool descriptions to decide when to call them. Vague descriptions lead to wrong invocations.
- **Handle errors gracefully.** Raise descriptive exceptions; don't swallow HTTP errors silently. Raise `IntegrationConnectionError` (from `naas_abi_sdk.integration`) for transport-level failures, so callers can tell them from logic errors.
- **Keep credentials in secrets.** Never hardcode API keys, and never read them from the module's environment. The module declares the `secret` service and reads the key with `await self.engine.services.secret.get("MY_API_KEY")`, then passes it in the configuration: see [Add credentials](/capabilities/build/integrations/add-credentials).
- **Guard optional keys.** Add the tools only when the key exists: see [Use in an agent](/capabilities/build/integrations/use-in-an-agent).

---

## Testing

Test the class without the engine or the network: build it with a fake key and patch the method that makes the HTTP call (`_make_request` above). `abi new integration` writes `MyIntegration_test.py` next to the class. The steps are on [Test an integration](/capabilities/build/integrations/test-an-integration).
