# Tables — Move REST API on Movement

## Overview

Move tables are on-chain key-value stores used extensively by DeFi protocols, NFT collections, token registries, and governance systems on Movement. Unlike Move resources (which are stored at a specific account address), table items are stored under opaque handles and accessed by key. This endpoint lets you look up individual table items by providing the table handle, key type, value type, and key value.

Tables are the backbone of many Move data structures. Token balances in `CoinStore`, NFT ownership records, DEX liquidity positions, and staking delegations are all stored in tables.

## Endpoint

```
POST /v1/tables/{table_handle}/item
```

**Base URL:** `https://api-movement-mainnet.n.dwellir.com/YOUR_API_KEY/v1`

## Request Parameters

- `table_handle` (`string, required`): Path parameter: Hex-encoded table handle. Obtained from account resources that contain `Table` or `TableWithLength` fields.
- `ledger_version` (`string, optional`): Query parameter: Specific ledger version to query. Defaults to the latest version.
- `key_type` (`string, required`): Body Schema: Move type of the table key (e.g., `address`, `u64`, `0x1::string::String`).
- `value_type` (`string, required`): Body Schema: Move type of the table value.
- `key` (`any, required`): Body Schema: JSON-encoded key value matching `key_type`.

## Request Example

```json
{
  "key_type": "address",
  "value_type": "0x1::coin::CoinStore<0x1::aptos_coin::AptosCoin>",
  "key": "0xYOUR_ADDRESS"
}
```

## Response Fields

- `result` (`OBJECT, required`): ### Success Response (200) The response body is the JSON-encoded value from the table. The structure depends on `value_type`. **Example: simple value** ```json "1000000" ``` **Example: struct value** ```json { "coin": { "value": "50000000000" }, "frozen": false, "deposit_events": { "counter": "15", "guid": { "id": { "creation_num": "2", "addr": "0xYOUR_ADDRESS" } } }, "withdraw_events": { "counter": "8", "guid": { "id": { "creation_num": "3", "addr": "0xYOUR_ADDRESS" } } } } ``` ### Error Responses | Status | Description | Common Cause | |---|---|---| | `400` | Bad request | Invalid key type, value type, or key encoding | | `404` | Table item not found | Key does not exist in the table | | `500` | Internal server error | Node issue, retry after a moment | ```json { "message": "Table item not found by Table handle(0x...), Table key(0x...)", "error_code": "table_item_not_found", "vm_error_code": null } ``` A `404` response is expected behavior when a key does not exist. Use this to check for existence (e.g., whether an address holds a specific token).

## Successful Response

```json
"1000000"
```

## Code Examples

### Look Up a Table Item

cURL
Python
TypeScript

```bash
# Look up a string-to-string table item
curl -s -X POST "https://api-movement-mainnet.n.dwellir.com/YOUR_API_KEY/v1/tables/0xTABLE_HANDLE/item" \
  -H "Content-Type: application/json" \
  -d '{
    "key_type": "0x1::string::String",
    "value_type": "0x1::string::String",
    "key": "my_key"
  }'
```

```python
import requests

BASE = "https://api-movement-mainnet.n.dwellir.com/YOUR_API_KEY/v1"
table_handle = "0xTABLE_HANDLE"

resp = requests.post(
    f"{BASE}/tables/{table_handle}/item",
    json={
        "key_type": "0x1::string::String",
        "value_type": "0x1::string::String",
        "key": "my_key",
    },
)

if resp.status_code == 200:
    print(f"Value: {resp.json()}")
elif resp.status_code == 404:
    print("Key not found in table")
else:
    print(f"Error: {resp.status_code} - {resp.text}")
```

```typescript
const BASE = "https://api-movement-mainnet.n.dwellir.com/YOUR_API_KEY/v1";
const tableHandle = "0xTABLE_HANDLE";

const resp = await fetch(`${BASE}/tables/${tableHandle}/item`, {
  method: "POST",
  headers: { "Content-Type": "application/json" },
  body: JSON.stringify({
    key_type: "0x1::string::String",
    value_type: "0x1::string::String",
    key: "my_key",
  }),
});

if (resp.ok) {
  console.log("Value:", await resp.json());
} else if (resp.status === 404) {
  console.log("Key not found in table");
}
```

### Look Up Token Balance from a Table

cURL
Python
TypeScript

```bash
# Look up a token balance using address as key
curl -s -X POST "https://api-movement-mainnet.n.dwellir.com/YOUR_API_KEY/v1/tables/0xBALANCE_TABLE_HANDLE/item" \
  -H "Content-Type: application/json" \
  -d '{
    "key_type": "address",
    "value_type": "u64",
    "key": "0xYOUR_ADDRESS"
  }'
# Response: "5000000000"
```

```python
import requests

BASE = "https://api-movement-mainnet.n.dwellir.com/YOUR_API_KEY/v1"

# Look up balance from a custom token's balance table
resp = requests.post(
    f"{BASE}/tables/0xBALANCE_TABLE_HANDLE/item",
    json={
        "key_type": "address",
        "value_type": "u64",
        "key": "0xYOUR_ADDRESS",
    },
)

if resp.status_code == 200:
    balance = int(resp.json())
    print(f"Balance: {balance}")
elif resp.status_code == 404:
    print("No balance entry (account has not interacted with this token)")
```

```typescript
import { Aptos, AptosConfig, Network } from "@aptos-labs/ts-sdk";

const config = new AptosConfig({
  network: Network.CUSTOM,
  fullnode: "https://api-movement-mainnet.n.dwellir.com/YOUR_API_KEY/v1",
});
const aptos = new Aptos(config);

// Use the SDK's table item lookup
const balance = await aptos.getTableItem<string>({
  handle: "0xBALANCE_TABLE_HANDLE",
  data: {
    key_type: "address",
    value_type: "u64",
    key: "0xYOUR_ADDRESS",
  },
});

console.log(`Balance: ${balance}`);
```

### Finding Table Handles from Resources

cURL
Python
TypeScript

```bash
# Step 1: Find table handles by inspecting account resources
# Tables appear as fields with "handle" properties in resource data
curl -s "https://api-movement-mainnet.n.dwellir.com/YOUR_API_KEY/v1/accounts/0xPROTOCOL_ADDRESS/resources" \
  -H "Accept: application/json" \
  | jq '.[] | select(.data.table? or (.data | keys[] | test("table";"i"))) | {type: .type, data: .data}'

# Step 2: Extract the handle value from the resource
# Example output might show: "balances": { "handle": "0xabc123...", "length": "42" }

# Step 3: Use the handle to look up items
curl -s -X POST "https://api-movement-mainnet.n.dwellir.com/YOUR_API_KEY/v1/tables/0xabc123/item" \
  -H "Content-Type: application/json" \
  -d '{"key_type": "address", "value_type": "u64", "key": "0xYOUR_ADDRESS"}'
```

```python
from aptos_sdk.client import RestClient

client = RestClient("https://api-movement-mainnet.n.dwellir.com/YOUR_API_KEY/v1")

# Step 1: Get resources to find table handles
resources = client.account_resources("0xPROTOCOL_ADDRESS")

# Step 2: Find resources containing tables
for resource in resources:
    data = resource["data"]
    for key, value in data.items():
        if isinstance(value, dict) and "handle" in value:
            print(f"Found table '{key}' in {resource['type']}")
            print(f"  Handle: {value['handle']}")
            if "length" in value:
                print(f"  Length: {value['length']}")
```

```typescript
import { Aptos, AptosConfig, Network } from "@aptos-labs/ts-sdk";

const config = new AptosConfig({
  network: Network.CUSTOM,
  fullnode: "https://api-movement-mainnet.n.dwellir.com/YOUR_API_KEY/v1",
});
const aptos = new Aptos(config);

// Find table handles in account resources
const resources = await aptos.getAccountResources({
  accountAddress: "0xPROTOCOL_ADDRESS",
});

for (const resource of resources) {
  const data = resource.data as Record<string, any>;
  for (const [key, value] of Object.entries(data)) {
    if (value && typeof value === "object" && "handle" in value) {
      console.log(`Table '${key}' in ${resource.type}`);
      console.log(`  Handle: ${value.handle}`);
    }
  }
}
```

### Checking if a Key Exists

Python
TypeScript

```python
import requests

BASE = "https://api-movement-mainnet.n.dwellir.com/YOUR_API_KEY/v1"

def table_key_exists(handle: str, key_type: str, value_type: str, key) -> bool:
    """Check if a key exists in a table. Returns True/False."""
    resp = requests.post(
        f"{BASE}/tables/{handle}/item",
        json={"key_type": key_type, "value_type": value_type, "key": key},
    )
    return resp.status_code == 200

# Example: check if an address is whitelisted
is_whitelisted = table_key_exists(
    "0xWHITELIST_TABLE_HANDLE",
    "address",
    "bool",
    "0xUSER_ADDRESS",
)
print(f"Whitelisted: {is_whitelisted}")
```

```typescript
const BASE = "https://api-movement-mainnet.n.dwellir.com/YOUR_API_KEY/v1";

async function tableKeyExists(
  handle: string,
  keyType: string,
  valueType: string,
  key: any
): Promise<boolean> {
  const resp = await fetch(`${BASE}/tables/${handle}/item`, {
    method: "POST",
    headers: { "Content-Type": "application/json" },
    body: JSON.stringify({ key_type: keyType, value_type: valueType, key }),
  });
  return resp.ok;
}

// Check if an address is whitelisted
const isWhitelisted = await tableKeyExists(
  "0xWHITELIST_TABLE_HANDLE",
  "address",
  "bool",
  "0xUSER_ADDRESS"
);
console.log(`Whitelisted: ${isWhitelisted}`);
```

## Common Use Cases

### Token Registry Lookups

Many token registries and metadata stores use tables. Look up token metadata (name, symbol, decimals, icon URL) by token address. This is common for wallet applications and DEX aggregators.

### NFT Ownership and Metadata

NFT collections use tables to map token IDs to owner addresses and metadata. Query individual token ownership, collection statistics, and property maps through table lookups.

### Protocol Configuration

DeFi protocols store configuration parameters (fee tiers, interest rates, oracle addresses) in tables. Query these to display current protocol parameters or validate settings before submitting transactions.

### Staking and Delegation Records

Staking protocols track delegations, rewards, and validator information in tables. Look up a user's staking position by their address, or query validator performance data.

## Movement-Specific Notes

- Table handles are opaque hex strings assigned when a table is created on-chain. They are not human-readable and cannot be derived -- you must discover them from the account resources that contain the table.
- Keys and values are BCS-encoded internally, but the REST API handles serialization and deserialization. You provide JSON-encoded values and receive JSON-encoded responses.
- There is no endpoint to enumerate all keys in a table. To iterate over table contents, you need an indexer or to use event logs that track insertions.
- Table lookups are constant-time operations (O(1)) on-chain, making them efficient for large data sets.

## Related Endpoints

- [`GET /v1/accounts/{address}/resources`](https://www.dwellir.com/docs/movement/account_resources) -- Find table handles within account resources.
- [`POST /v1/view`](https://www.dwellir.com/docs/movement/modules_view) -- Call view functions that may internally query tables.
- [`GET /v1/accounts/{address}/modules`](https://www.dwellir.com/docs/movement/account_modules) -- Inspect module ABIs to understand table key/value types.
- [`GET /v1/accounts/{address}/events/{creation_number}`](https://www.dwellir.com/docs/movement/events) -- Track table insertions and updates via events.
