Files
truenas/START-HERE-DOCS/TRUENAS_API_REFERENCE.md

704 lines
14 KiB
Markdown
Raw Normal View History

# TrueNAS Scale API v2.0 Reference
**Target Server:** 192.168.2.150
**API Version:** 2.0
**Documentation Type:** Collection-Focused Reference
---
## Table of Contents
1. [Authentication](#authentication)
2. [API Basics](#api-basics)
3. [System Endpoints](#system-endpoints)
4. [Storage Endpoints](#storage-endpoints)
5. [Sharing Endpoints](#sharing-endpoints)
6. [Network Endpoints](#network-endpoints)
7. [Service Endpoints](#service-endpoints)
8. [Task Endpoints](#task-endpoints)
9. [User Management](#user-management)
10. [Error Codes](#error-codes)
11. [Examples](#examples)
---
## Authentication
### API Key Generation
**Method 1: Web UI**
1. Log in to TrueNAS Scale: `https://192.168.2.150`
2. Navigate to: **Account****API Keys**
3. Click **Add**
4. Configure:
- Name: `homelab-collection`
- Username: `admin` (or your user)
- Expiration: Optional
5. Click **Save**
6. **IMPORTANT:** Copy the key immediately (shown only once)
**Method 2: CLI (if logged in via SSH)**
```bash
midclt call auth.generate_token 120 # 120 seconds validity
```
### Authentication Headers
**All API requests require:**
```http
Authorization: Bearer <API_KEY>
Content-Type: application/json
```
**Example:**
```bash
curl -X GET "https://192.168.2.150/api/v2.0/system/info" \
-H "Authorization: Bearer 1-YourAPIKeyHere" \
-H "Content-Type: application/json" \
--insecure # Only if using self-signed certificate
```
### Testing Authentication
```bash
# Test 1: Get system version (minimal permissions)
curl -X GET "https://192.168.2.150/api/v2.0/system/version" \
-H "Authorization: Bearer ${TRUENAS_API_KEY}" \
-H "Content-Type: application/json" \
--insecure
# Expected response:
# {"fullversion": "TrueNAS-SCALE-23.10.1", "version": "23.10.1"}
# Test 2: Get system info (more detailed)
curl -X GET "https://192.168.2.150/api/v2.0/system/info" \
-H "Authorization: Bearer ${TRUENAS_API_KEY}" \
-H "Content-Type: application/json" \
--insecure | jq .
```
---
## API Basics
### Base URL
```
https://192.168.2.150/api/v2.0
```
### Response Format
All responses are JSON-formatted.
**Success Response:**
```json
{
"id": 1,
"name": "example",
"status": "SUCCESS"
}
```
**Error Response:**
```json
{
"error": "Error message",
"errname": "EINVAL",
"extra": null
}
```
### Query Parameters
**Filtering:**
```bash
# Get datasets with specific properties
curl -X GET "https://192.168.2.150/api/v2.0/pool/dataset?name=Vauly" \
-H "Authorization: Bearer ${TRUENAS_API_KEY}" \
--insecure
```
### HTTP Methods
| Method | Purpose | Idempotent | Collection Use |
|--------|---------|------------|----------------|
| GET | Retrieve data | Yes | Primary method |
| POST | Create resource | No | Not used |
| PUT | Update resource | Yes | Not used |
| DELETE | Remove resource | Yes | Not used |
**Collection scripts use GET only** (read-only operations).
---
## System Endpoints
### GET /api/v2.0/system/info
**Description:** Get comprehensive system information
**Request:**
```bash
curl -X GET "https://192.168.2.150/api/v2.0/system/info" \
-H "Authorization: Bearer ${TRUENAS_API_KEY}" \
--insecure
```
**Response:**
```json
{
"version": "TrueNAS-SCALE-23.10.1",
"hostname": "truenas",
"physmem": 68719476736,
"model": "AMD Ryzen",
"cores": 16,
"physical_cores": 8,
"loadavg": [0.5, 0.6, 0.7],
"uptime": "10 days, 5:30:15",
"uptime_seconds": 896415.0,
"boottime": "2025-12-04T10:30:00",
"datetime": "2025-12-14T15:30:15",
"timezone": "America/New_York"
}
```
**Key Fields:**
- `version`: TrueNAS Scale version
- `physmem`: Physical memory in bytes
- `cores`: Total CPU cores
- `uptime_seconds`: System uptime
- `loadavg`: 1, 5, 15-minute load averages
---
### GET /api/v2.0/system/version
**Description:** Get TrueNAS version string
**Request:**
```bash
curl -X GET "https://192.168.2.150/api/v2.0/system/version" \
-H "Authorization: Bearer ${TRUENAS_API_KEY}" \
--insecure
```
**Response:**
```json
{
"fullversion": "TrueNAS-SCALE-23.10.1",
"version": "23.10.1"
}
```
---
### GET /api/v2.0/system/advanced
**Description:** Get advanced system settings
**Response includes:**
- Boot scrub interval
- Console settings
- Power management
- Syslog configuration
- Debug settings
---
### GET /api/v2.0/system/general
**Description:** Get general system configuration
**Response includes:**
- Web UI settings (ports, protocols)
- Timezone and language
- Keyboard map
- Certificate configuration
---
## Storage Endpoints
### GET /api/v2.0/pool
**Description:** List all storage pools
**Request:**
```bash
curl -X GET "https://192.168.2.150/api/v2.0/pool" \
-H "Authorization: Bearer ${TRUENAS_API_KEY}" \
--insecure
```
**Response:**
```json
[
{
"id": 1,
"name": "Vauly",
"guid": "1234567890123456789",
"status": "ONLINE",
"path": "/mnt/Vauly",
"scan": {
"function": "SCRUB",
"state": "FINISHED",
"start_time": "2025-12-10T02:00:00",
"end_time": "2025-12-10T06:30:00",
"percentage": 100.0,
"errors": 0
},
"is_decrypted": true,
"healthy": true,
"size": 3221225472000,
"allocated": 67108864000,
"free": 3154116608000,
"fragmentation": "1%",
"topology": {
"data": [],
"cache": [],
"log": [],
"spare": []
}
}
]
```
**Key Fields:**
- `name`: Pool name (e.g., "Vauly")
- `status`: Pool health status
- `healthy`: Boolean health indicator
- `size`: Total pool size in bytes
- `free`: Available space in bytes
- `scan`: Last scrub information
---
### GET /api/v2.0/pool/dataset
**Description:** List all datasets and zvols
**Request:**
```bash
curl -X GET "https://192.168.2.150/api/v2.0/pool/dataset" \
-H "Authorization: Bearer ${TRUENAS_API_KEY}" \
--insecure
```
**Response:**
```json
[
{
"id": "Vauly/iso-vault",
"type": "FILESYSTEM",
"name": "Vauly/iso-vault",
"pool": "Vauly",
"encrypted": false,
"mountpoint": "/mnt/Vauly/iso-vault",
"compression": {
"parsed": "lz4",
"value": "lz4"
},
"used": {
"parsed": 67108864000,
"value": "62.5G"
},
"available": {
"parsed": 3154116608000,
"value": "2.9T"
}
}
]
```
**Query specific dataset:**
```bash
curl -X GET "https://192.168.2.150/api/v2.0/pool/dataset?id=Vauly/iso-vault" \
-H "Authorization: Bearer ${TRUENAS_API_KEY}" \
--insecure
```
---
### GET /api/v2.0/disk
**Description:** Get disk inventory
**Response includes:**
- Disk serial numbers
- Model information
- Size and type (HDD/SSD)
- Current pool assignment
- SMART status
- Temperature readings
---
### GET /api/v2.0/disk/temperature
**Description:** Get current disk temperatures
**Request:**
```bash
curl -X GET "https://192.168.2.150/api/v2.0/disk/temperature" \
-H "Authorization: Bearer ${TRUENAS_API_KEY}" \
--insecure
```
**Response:**
```json
{
"sda": 35,
"sdb": 32,
"sdc": 34,
"sdd": 36
}
```
---
### GET /api/v2.0/pool/scrub
**Description:** Get scrub status and history
**Response includes:**
- Current scrub state
- Start/end times
- Bytes processed
- Error count
- Completion percentage
---
### GET /api/v2.0/smart/test/results
**Description:** Get SMART test results for all disks
**Response includes:**
- Test type (short/long)
- Test status
- Completion time
- Any errors found
---
## Sharing Endpoints
### GET /api/v2.0/sharing/nfs
**Description:** Get all NFS share configurations
**Request:**
```bash
curl -X GET "https://192.168.2.150/api/v2.0/sharing/nfs" \
-H "Authorization: Bearer ${TRUENAS_API_KEY}" \
--insecure
```
**Response:**
```json
[
{
"id": 1,
"path": "/mnt/Vauly/iso-vault",
"comment": "ISO storage for Proxmox",
"networks": ["192.168.2.0/24"],
"hosts": [],
"ro": false,
"maproot_user": "root",
"maproot_group": "root",
"security": ["SYS"],
"enabled": true
}
]
```
---
### GET /api/v2.0/sharing/smb
**Description:** Get all SMB/CIFS share configurations
**Response includes:**
- Share name and path
- Access permissions
- Guest access settings
- Host allow/deny lists
- Enable status
---
### GET /api/v2.0/sharing/iscsi/target
**Description:** Get iSCSI target configurations
### GET /api/v2.0/sharing/iscsi/extent
**Description:** Get iSCSI extent configurations
---
## Network Endpoints
### GET /api/v2.0/interface
**Description:** Get network interface configurations
**Response includes:**
- Interface name and type
- IP addresses (IPv4/IPv6)
- MTU settings
- Link state
- DHCP configuration
---
### GET /api/v2.0/network/configuration
**Description:** Get global network configuration
**Response includes:**
- Hostname and domain
- Default gateway
- DNS servers
- Service announcement settings
---
### GET /api/v2.0/staticroute
**Description:** Get static route configurations
---
## Service Endpoints
### GET /api/v2.0/service
**Description:** Get status of all services
**Request:**
```bash
curl -X GET "https://192.168.2.150/api/v2.0/service" \
-H "Authorization: Bearer ${TRUENAS_API_KEY}" \
--insecure
```
**Response:**
```json
[
{
"id": 1,
"service": "ssh",
"enable": true,
"state": "RUNNING",
"pids": [1234]
},
{
"id": 2,
"service": "nfs",
"enable": true,
"state": "RUNNING",
"pids": [5678, 5679]
}
]
```
---
### GET /api/v2.0/ssh
**Description:** Get SSH service configuration
**Response includes:**
- TCP port
- Root login settings
- Password authentication
- SFTP log settings
---
## Task Endpoints
### GET /api/v2.0/cronjob
**Description:** Get cron job configurations
### GET /api/v2.0/pool/snapshottask
**Description:** Get snapshot task configurations
### GET /api/v2.0/rsynctask
**Description:** Get rsync task configurations
### GET /api/v2.0/cloudsync
**Description:** Get cloud sync task configurations
### GET /api/v2.0/replication
**Description:** Get ZFS replication task configurations
---
## User Management
### GET /api/v2.0/user
**Description:** Get all user accounts
**Response includes:**
- Username and UID
- Home directory
- Shell
- Group memberships
- SSH public keys
### GET /api/v2.0/group
**Description:** Get all groups
---
## Error Codes
### HTTP Status Codes
| Code | Meaning | Description |
|------|---------|-------------|
| 200 | OK | Request successful |
| 400 | Bad Request | Invalid request syntax |
| 401 | Unauthorized | Invalid or missing API key |
| 403 | Forbidden | Insufficient permissions |
| 404 | Not Found | Resource doesn't exist |
| 429 | Too Many Requests | Rate limit exceeded |
| 500 | Internal Server Error | Server-side error |
### TrueNAS Error Names
| Error Name | Description | Common Cause |
|------------|-------------|--------------|
| `EINVAL` | Invalid argument | Wrong parameter type or value |
| `ENOENT` | No such file or directory | Resource doesn't exist |
| `EACCES` | Permission denied | Insufficient permissions |
| `EFAULT` | General fault | Internal middleware error |
---
## Examples
### Complete Health Check Script
```bash
#!/bin/bash
# truenas-health-check.sh
TRUENAS_HOST="192.168.2.150"
TRUENAS_API_KEY="${TRUENAS_API_KEY:?API key not set}"
API_BASE="https://${TRUENAS_HOST}/api/v2.0"
CURL_OPTS="-s -H 'Authorization: Bearer ${TRUENAS_API_KEY}' --insecure"
echo "=== TrueNAS Health Check ==="
# System version
echo "System Version:"
curl ${CURL_OPTS} "${API_BASE}/system/version" | jq -r '.fullversion'
# Pool status
echo "Pool Status:"
curl ${CURL_OPTS} "${API_BASE}/pool" | \
jq -r '.[] | "\(.name): \(.status) (Healthy: \(.healthy))"'
# Disk temperatures
echo "Disk Temperatures:"
curl ${CURL_OPTS} "${API_BASE}/disk/temperature" | \
jq -r 'to_entries[] | "\(.key): \(.value)°C"'
# Service status
echo "Service Status:"
curl ${CURL_OPTS} "${API_BASE}/service" | \
jq -r '.[] | select(.enable == true) | "\(.service): \(.state)"'
```
### Export Pool Configuration
```bash
#!/bin/bash
# export-pool-config.sh
POOL_NAME="Vauly"
OUTPUT_DIR="./pool-export-$(date +%Y%m%d)"
mkdir -p "${OUTPUT_DIR}"
# Pool info
curl -s -X GET "https://192.168.2.150/api/v2.0/pool" \
-H "Authorization: Bearer ${TRUENAS_API_KEY}" \
--insecure | jq ".[] | select(.name == \"${POOL_NAME}\")" \
> "${OUTPUT_DIR}/pool-${POOL_NAME}.json"
# Datasets
curl -s -X GET "https://192.168.2.150/api/v2.0/pool/dataset" \
-H "Authorization: Bearer ${TRUENAS_API_KEY}" \
--insecure | jq ".[] | select(.pool == \"${POOL_NAME}\")" \
> "${OUTPUT_DIR}/datasets-${POOL_NAME}.json"
echo "Pool configuration exported to: ${OUTPUT_DIR}"
```
### Monitor Specific Dataset
```bash
#!/bin/bash
# monitor-dataset.sh
DATASET="Vauly/iso-vault"
API_BASE="https://192.168.2.150/api/v2.0"
# URL encode the dataset name
ENCODED_DATASET=$(echo "${DATASET}" | sed 's/\//%2F/g')
curl -s -X GET "${API_BASE}/pool/dataset?id=${ENCODED_DATASET}" \
-H "Authorization: Bearer ${TRUENAS_API_KEY}" \
--insecure | jq '{
name: .name,
type: .type,
mountpoint: .mountpoint,
used: .used.value,
available: .available.value,
compression: .compression.value
}'
```
---
## Middleware CLI Alternative
For commands requiring higher privileges or unavailable via API:
```bash
# Connect via SSH
ssh admin@192.168.2.150
# Use midclt for middleware calls
midclt call system.info
midclt call pool.query
midclt call pool.dataset.query '[["pool", "=", "Vauly"]]'
# Complex queries with filters
midclt call disk.query '[["pool", "=", "Vauly"]]' \
'{"select": ["name", "serial", "model", "size"]}'
```
---
## Version Compatibility
**This documentation is based on:**
- TrueNAS Scale 23.10.x (Cobia)
- API version 2.0
**Check API version:**
```bash
curl -X GET "https://192.168.2.150/api/v2.0/system/version" \
-H "Authorization: Bearer ${TRUENAS_API_KEY}" \
--insecure
```
---
## Additional Resources
**Official Documentation:**
- API Docs: https://www.truenas.com/docs/api/scale_rest_api.html
- WebSocket API: https://www.truenas.com/docs/api/scale_websocket_api.html
**Community:**
- Forums: https://forums.truenas.com/
- GitHub: https://github.com/truenas/middleware
**Tools:**
- API Explorer: `https://192.168.2.150/api/docs/` (built-in)
---
**Document Version:** 1.0.0
**Last Updated:** 2025-12-14
**API Version:** 2.0
**Maintained By:** Scribe Agent
**Homelab Repository:** /home/jramos/homelab