> ## Documentation Index
> Fetch the complete documentation index at: https://docs.ai2fin.com/llms.txt
> Use this file to discover all available pages before exploring further.

# REST API reference — authentication and endpoints

> Get started with the AI2Fin REST API for transaction management, bill automation, and AI-powered tax analysis using OAuth and API key authentication.

## Welcome to AI2Fin API

The AI2Fin API provides endpoints for financial management, transaction processing, bill automation, and AI-powered tax optimization.

<Card title="OpenAPI Specification" icon="code" href="/api-reference/openapi.json">
  View the complete OpenAPI 3.1 specification
</Card>

## Quick Start

### Authentication Methods

AI2Fin API supports **two authentication methods**:

<Tabs>
  <Tab title="JWT Token (OAuth)">
    Standard authentication for web and mobile apps
  </Tab>

  <Tab title="API Key">
    For MCP integrations, automation, and server-to-server communication
  </Tab>
</Tabs>

### Method 1: Bearer Token (OAuth Login)

All API endpoints (except registration and login) require authentication. Sign in to receive a bearer token, then send it in the `Authorization` header on every request.

```bash theme={null}
# Sign in and receive a token
curl -X POST https://api.ai2fin.com/api/auth/login \
  -H "Content-Type: application/json" \
  -d '{
    "email": "user@example.com",
    "password": "********"
  }'
```

```json theme={null}
{
  "success": true,
  "token": "<YOUR_TOKEN>",
  "user": {
    "id": "user-uuid",
    "email": "user@example.com",
    "firstName": "John",
    "lastName": "Smith"
  }
}
```

**Using your token:**

```bash theme={null}
curl -X GET https://api.ai2fin.com/api/bank/transactions \
  -H "Authorization: Bearer <YOUR_TOKEN>"
```

### Method 2: API Key

API keys are ideal for:

* MCP integrations
* Server-to-server automation
* Custom integrations and webhooks
* Testing and development

<Card title="Create API Key" icon="key" href="https://app.ai2fin.com/#/api" target="_blank">
  Generate a new API key from the AI2Fin dashboard.
</Card>

**Generate an API key:**

Create an API key using your bearer token:

```bash theme={null}
curl -X POST https://api.ai2fin.com/api/api-keys \
  -H "Authorization: Bearer <YOUR_TOKEN>" \
  -H "Content-Type: application/json" \
  -d '{
    "name": "My MCP Integration",
    "scopes": ["mcp:full"],
    "expiresInDays": 90
  }'
```

**Response:**

```json theme={null}
{
  "id": "key_...",
  "key": "<YOUR_API_KEY>",
  "name": "My MCP Integration",
  "scopes": ["mcp:full"],
  "expiresAt": "2026-04-01T00:00:00Z",
  "createdAt": "2026-01-01T00:00:00Z"
}
```

<Warning>
  Your API key is shown only once at creation. Copy and store it somewhere safe — you won't be able to view it again.
</Warning>

<Note>
  **Default Scope:** If you don't specify `scopes`, the key defaults to `["mcp:full"]`.
</Note>

**Using an API key:**

Send your API key in either the `X-API-Key` header or the `Authorization: Bearer` header.

```bash theme={null}
# X-API-Key header
curl -X GET https://api.ai2fin.com/api/bank/transactions \
  -H "X-API-Key: <YOUR_API_KEY>"

# Authorization header
curl -X GET https://api.ai2fin.com/api/bank/transactions \
  -H "Authorization: Bearer <YOUR_API_KEY>"
```

<Warning>
  **Keep your API keys safe:**

  * Store keys securely (for example, in environment variables or a secret manager)
  * Rotate keys periodically and revoke any key you believe is exposed
  * Grant only the scopes each integration actually needs
</Warning>

**API Key Scopes:**

* `mcp:read` - Read-only MCP operations
* `mcp:tools:list` - List available tools
* `mcp:tools:call` - Execute tools (read-only)
* `mcp:resources:read` - Read resources
* `mcp:full` - Full MCP access (read + write)

### Connecting an MCP client

AI2Fin exposes a Model Context Protocol (MCP) endpoint so AI assistants and automation clients can work with your financial data securely. Authenticate with an API key, then use standard JSON-RPC methods such as `tools/list` and `tools/call`.

```bash theme={null}
# List the MCP tools available to your key
curl -X POST https://api.ai2fin.com/mcp \
  -H "X-API-Key: <YOUR_API_KEY>" \
  -H "Content-Type: application/json" \
  -d '{
    "jsonrpc": "2.0",
    "id": 1,
    "method": "tools/list",
    "params": {}
  }'
```

## API Features

<CardGroup cols={2}>
  <Card title="Bank Transactions" icon="bank">
    Import, categorize, and manage bank transactions with CSV upload support
  </Card>

  <Card title="AI Classification" icon="brain">
    Intelligent transaction categorization with tax deduction analysis
  </Card>

  <Card title="Smart Categories (Elite+)" icon="folder-tree">
    Category sets, multi-category assignments, and transaction history tracking
  </Card>

  <Card title="Bill Automation" icon="calendar-check">
    Recurring bill patterns with automatic occurrence generation
  </Card>

  <Card title="Custom Rules" icon="wand-magic-sparkles">
    Create automation rules with conditions and actions for any entity
  </Card>

  <Card title="Tax Reports" icon="file-invoice-dollar">
    Tax-ready exports with GST/VAT calculations included
  </Card>

  <Card title="Analytics" icon="chart-line">
    Real-time financial summaries and insights
  </Card>
</CardGroup>

## AI Assistant Chat APIs

Use the chat endpoints to power the in-app assistant, automate financial workflows, and ingest receipts securely. See the [AI Assistant guide](/features/ai-assistant) for user experience details.

| Method | Endpoint                            | Purpose                                                            |
| ------ | ----------------------------------- | ------------------------------------------------------------------ |
| `POST` | `/api/chat/message`                 | Send a message and receive an AI response with tool usage metadata |
| `GET`  | `/api/chat/conversations`           | List conversations for the authenticated user                      |
| `POST` | `/api/chat/conversations`           | Create a new conversation thread                                   |
| `GET`  | `/api/chat/conversations/:id`       | Fetch the full message history and tool calls                      |
| `POST` | `/api/chat/upload`                  | Upload files (receipts, invoices, spreadsheets) for analysis       |
| `GET`  | `/api/chat/files/:userId/:fileName` | Retrieve stored attachments with access control                    |

```bash theme={null}
curl -X POST https://api.ai2fin.com/api/chat/message \
  -H "Authorization: Bearer <YOUR_TOKEN>" \
  -H "Content-Type: application/json" \
  -d '{
    "conversationId": "conv_123",
    "message": "Show expenses missing receipts for September"
  }'
```

<Tip>
  Use `/api/chat/upload` before calling `/api/chat/message` when attaching a receipt image or PDF; include the returned `assetUrl` in the message payload so the assistant can analyze it.
</Tip>

## GST & Tax APIs

These endpoints provide localized GST/VAT/Sales Tax rate lookup and accurate tax calculations for transactions. They power the [User Preferences](/features/user-preferences) and [Transaction Management](/guides/transaction-management) experiences.

| Method | Endpoint                      | Purpose                                                             |
| ------ | ----------------------------- | ------------------------------------------------------------------- |
| `GET`  | `/api/tax/country-rates`      | List active tax rates grouped by country                            |
| `GET`  | `/api/tax/rates/:countryCode` | Get the tax profile for a country code (e.g. `AU`, `GB`)            |
| `POST` | `/api/tax/calculate`          | Calculate the tax amount for a tax-inclusive or tax-exclusive price |

```bash theme={null}
curl -X POST https://api.ai2fin.com/api/tax/calculate \
  -H "Authorization: Bearer <YOUR_TOKEN>" \
  -H "Content-Type: application/json" \
  -d '{
    "amount": 220.0,
    "taxIncluded": true,
    "countryCode": "AU"
  }'
```

The response returns the calculated tax, the pre-tax amount, and the rate applied for the country — so you always see exactly how the figure was reached.

```json theme={null}
{
  "success": true,
  "data": {
    "total": 220,
    "subtotal": 200,
    "tax": 20,
    "rate": 0.1,
    "countryCode": "AU"
  }
}
```

## Core Concepts

### Data Scoping

Every API request is scoped to the authenticated user. You can only ever read and write your own data — accounts are isolated from one another.

### Pagination

List endpoints support pagination with standard query parameters:

* `page`: Page number (default: 1)
* `limit`: Items per page (default: 50, max: 200)

```json theme={null}
{
  "transactions": [...],
  "pagination": {
    "page": 1,
    "limit": 50,
    "total": 1250,
    "pages": 25
  }
}
```

### Rate Limiting

The API is rate limited to keep the platform fast and reliable for everyone. Limits scale with your subscription tier, with higher allowances on paid and Enterprise plans. If you exceed your limit, the API responds with `429 Too Many Requests` — pause briefly and retry.

Each response includes standard `X-RateLimit-*` headers so your client can see its remaining allowance and when it resets.

### Error Handling

All errors follow a consistent format:

```json theme={null}
{
  "success": false,
  "error": "Resource not found",
  "code": "NOT_FOUND"
}
```

**HTTP Status Codes:**

* `200` - Success
* `201` - Created
* `400` - Bad Request (validation error)
* `401` - Unauthorized (missing/invalid token)
* `403` - Forbidden (insufficient permissions)
* `404` - Not Found
* `429` - Rate Limited
* `500` - Internal Server Error

## Advanced Features

### Custom Rules Engine

Create powerful automation rules with:

* Multiple condition types (contains, equals, regex, etc.)
* Flexible actions (set category, tax flags, etc.)
* Priority-based execution
* Support for transactions, bills, expenses, and patterns

### GST/VAT Calculations

Built-in support for both tax-inclusive and tax-exclusive amounts. Send a price and a country, and the API returns the tax, the pre-tax subtotal, and the rate applied — ready to display or store against a transaction.

### AI-Powered Features

* **Smart Categorization**: Transactions are sorted into the right categories automatically
* **Tax Analysis**: Likely deductions are surfaced for you to review
* **Pattern Recognition**: Recurring bills and subscriptions are detected
* **Intelligent Search**: Ask questions in plain language across all your data

### Access Control

* **Bearer token authentication** for user sessions (from OAuth login)
* **API key authentication** for server-to-server and automation
* Per-account data isolation — you only ever access your own records
* Activity is logged to support compliance and account security

**Authentication Headers:**

* `Authorization: Bearer <YOUR_TOKEN>` - bearer token from OAuth login or an API key
* `X-API-Key: <YOUR_API_KEY>` - API key (recommended for MCP)

## Webhooks

Subscribe to real-time events:

* Transaction imported
* Bill due soon
* Pattern detected
* Rule executed

<Note>
  Webhook support is available on Professional and Enterprise plans.
</Note>

## Calling the API

The AI2Fin REST API works with any HTTP client. Authenticate with a bearer token or an API key, then call the JSON endpoints directly.

<CodeGroup>
  ```bash cURL theme={null}
  # Using a bearer token (from OAuth login)
  curl "https://api.ai2fin.com/api/bank/transactions?page=1&limit=50" \
    -H "Authorization: Bearer <YOUR_TOKEN>"

  # Or using an API key
  curl "https://api.ai2fin.com/api/bank/transactions?page=1&limit=50" \
    -H "X-API-Key: <YOUR_API_KEY>"
  ```

  ```javascript JavaScript (fetch) theme={null}
  const res = await fetch(
    "https://api.ai2fin.com/api/bank/transactions?page=1&limit=50",
    { headers: { "X-API-Key": process.env.AI2FIN_API_KEY } }
  );
  const data = await res.json();
  ```

  ```python Python (requests) theme={null}
  import os, requests

  res = requests.get(
      "https://api.ai2fin.com/api/bank/transactions",
      params={"page": 1, "limit": 50},
      headers={"X-API-Key": os.environ["AI2FIN_API_KEY"]},
  )
  data = res.json()
  ```
</CodeGroup>

<Info>
  **Official SDKs — coming soon.** First-party client libraries are planned to make integration even faster. In the meantime, the REST and MCP endpoints above work with any standard HTTP or MCP client.
</Info>

## Support

* **Documentation**: [https://docs.ai2fin.com](https://docs.ai2fin.com)
* **Status Page**: [https://status.ai2fin.com](https://status.ai2fin.com)
