API Overview
EnerOS provides four API interfaces to meet access needs in different scenarios. All APIs are exposed through the eneros-api and eneros-graphql crates, and unified authentication, rate limiting, and security audit are performed by eneros-gateway. Regardless of which protocol is chosen, the underlying layer shares the same set of kernel system calls, ensuring data consistency, constraint validation, and audit logs.
API Type Comparison
EnerOS provides four API interfaces, corresponding to different access scenarios and communication models:
| Type | Protocol | Transmission Direction | Applicable Scenarios | Real-time | Browser Native | Auto Reconnect | Typical Use |
|---|---|---|---|---|---|---|---|
| REST | HTTP/1.1 or HTTP/2 | Request-Response | CRUD operations, configuration management, batch tasks | Synchronous | Yes (fetch) | No | Network/Agent/Device management |
| GraphQL | HTTP/1.1 or HTTP/2 | Request-Response | Flexible queries, on-demand data fetching, aggregate analysis | Synchronous | Yes (fetch) | No | Cross-resource aggregate queries |
| WebSocket | WS/WSS (HTTP upgrade) | Bidirectional full-duplex | Real-time event push, remote command dispatch | Real-time (millisecond) | Yes (WebSocket) | Manual implementation required | Agent status, control commands |
| SSE | HTTP/1.1 long connection | Server→Client | One-way real-time push, lightweight subscription | Real-time (second) | Yes (EventSource) | Yes | Alert dashboard, event display |
Selection Decision Tree
Does the server need to push proactively?
├── No → Need flexible field selection or cross-resource aggregation?
│ ├── Yes → GraphQL
│ └── No → REST
└── Yes → Does the client need to send commands to the server?
├── Yes (bidirectional) → WebSocket
└── No (one-way) → Running in a browser?
├── Yes → SSE (auto reconnect)
└── No → WebSocket (more efficient)
Concurrency and Resource Usage
| Dimension | REST | GraphQL | WebSocket | SSE |
|---|---|---|---|---|
| Single connection memory | ~50 KB | ~50 KB | ~80 KB | ~30 KB |
| Single connection CPU (idle) | 0% | 0% | 0.1% | 0% |
| Single connection CPU (active) | 0.5% | 0.5% | 1.0% | 0.3% |
| Max connections per tenant | Unlimited | Unlimited | 20 | 50 |
| Protocol overhead | Medium | Medium | Low (after first packet) | Low |
Basic Information
Base URL
The root URL of the EnerOS API depends on the deployment mode:
| Deployment Mode | Base URL | Description |
|---|---|---|
| Standalone local | http://localhost:8080/api/v1 | Development and testing |
| Standalone production | https://api.example.com/api/v1 | Single instance external |
| Multi-region | https://{region}.api.eneros.io/api/v1 | e.g., cn-east.api.eneros.io |
| Intranet mesh | http://eneros-api.nerve.svc:8080/api/v1 | Kubernetes internal |
Protocol endpoints:
| Protocol | Endpoint | Description |
|---|---|---|
| REST | http://<host>:8080/api/v1 | Resource CRUD |
| GraphQL | http://<host>:8080/graphql | Query / Mutation |
| GraphQL Subscription | ws://<host>:8080/graphql | Real-time subscription |
| WebSocket | ws://<host>:8080/ws | Bidirectional event stream |
| SSE | http://<host>:8080/api/v1/events/stream | One-way push |
Production environments enforce HTTPS / WSS, with certificates issued by eneros-trust.
Common Conventions
| Item | Value |
|---|---|
| Content Type | application/json; charset=utf-8 |
| Character Encoding | UTF-8 |
| Time Format | RFC 3339 / UTC (e.g., 2026-07-06T08:30:00Z) |
| Timezone | All timestamps default to UTC, can append ?tz=Asia/Shanghai for display conversion |
| Numeric Precision | Floating-point uses IEEE 754 double, electrical quantities default to 6 significant digits |
| ID Format | String, prefix identifies type (net_, agent_, dev_, evt_) |
| Resource Naming | Plural form (/networks, /agents, /devices) |
| Field Naming | Backend snake_case, REST responses preserve snake_case, GraphQL converts to camelCase |
Authentication Methods
EnerOS supports three authentication methods, which can be used individually or in combination:
1. Bearer Token
The most commonly used authentication method. Tokens are issued by eneros-trust and contain tenant, role, expiration time, and permission scope. Tokens default to 1-hour validity and can be renewed through the refresh mechanism.
Authorization: Bearer eyJhbGciOiJSUzI1NiIsInR5cCI6IkpXVCJ9...
| Field | Type | Required | Default | Description |
|---|---|---|---|---|
Authorization | string | Yes | — | Fixed prefix Bearer + JWT |
| Token Format | JWT (RS256) | — | — | Header.Payload.Signature |
| Token Validity | int (seconds) | — | 3600 | Configurable in eneros.toml |
| Refresh Token | string | No | — | 30-day validity, single use only |
2. mTLS Mutual Authentication
Recommended for production environments. Client and gateway mutually verify X.509 certificates, issued by internal CA. mTLS can be stacked with Bearer Token for dual verification.
curl --cert client.crt --key client.key --cacert ca.crt \
https://api.example.com/api/v1/networks
| Field | Type | Required | Default | Description |
|---|---|---|---|---|
| Client Certificate | X.509 PEM | Yes | — | CN must be agent-{id} or service-{name} |
| Client Private Key | RSA/EC PEM | Yes | — | At least 2048 bits |
| CA Certificate | X.509 PEM | Yes | — | EnerOS internal CA |
| Certificate Validity | int (days) | — | 365 | Alert 30 days before expiry |
3. API Key (Internal Service Calls Only)
Long-term credentials for internal service calls, cannot be used for end-user scenarios. API Keys are bound to specific service accounts with restricted permission scope.
X-API-Key: sk-internal-xxxxxxxxxxxxxxxxxxxx
Authentication Method Comparison
| Method | Security Level | Applicable Scenarios | Expiry Management | Mutual Identity Verification |
|---|---|---|---|---|
| Bearer Token | Medium | Web/App terminals, short-term sessions | Auto expiry + refresh | No |
| mTLS | High | Inter-service, Agent ↔ Gateway | Certificate rotation | Yes |
| API Key | Low | Internal trusted services | Manual rotation | No |
Common Request Headers
| Header | Type | Required | Default | Description |
|---|---|---|---|---|
Authorization | string | Yes* | — | Bearer <token>, except for public endpoints |
Content-Type | string | Yes | application/json | Required for POST/PUT/PATCH |
Accept | string | No | application/json | Can specify application/json or application/graphql-response+json |
X-Tenant-Id | string | No | Auto-parsed from Token | Explicitly specify tenant, requires cross-tenant permission |
X-Request-Id | string | No | Auto-generated UUID | Trace ID, transparently passed to audit log |
X-Trace-Id | string | No | — | OpenTelemetry trace ID |
User-Agent | string | No | eneros-client/0.1 | Client identifier |
Accept-Language | string | No | zh-CN | Error message language |
Common Response Format
Success Response
All REST success responses are JSON, with top-level fields as follows:
| Field | Type | Required | Description |
|---|---|---|---|
data | object/array | Yes | Business data body |
meta | object | No | Pagination, version, and other metadata |
request_id | string | Yes | Request trace ID |
timestamp | string | Yes | Response generation time (RFC 3339) |
Example:
{
"data": {
"id": "net_8f3a2b",
"name": "IEEE-14"
},
"meta": {
"version": "v1",
"deprecated": false
},
"request_id": "req_20260706_8f3a2b",
"timestamp": "2026-07-06T08:30:00Z"
}
Error Response
Unified error response format:
| Field | Type | Required | Description |
|---|---|---|---|
error.code | string | Yes | Uppercase underscore error code |
error.message | string | Yes | Human-readable error description |
error.details | object | No | Structured supplementary information |
error.trace_id | string | Yes | Trace ID |
error.doc_url | string | No | Documentation link |
request_id | string | Yes | Request trace ID |
Example:
{
"error": {
"code": "CONSTRAINT_VIOLATION",
"message": "Branch 1-2 overload: 105% of limit",
"details": {
"branch_id": "1-2",
"loading": 1.05,
"limit": 1.0
},
"trace_id": "trace_abc123",
"doc_url": "https://docs.openeneros.com/api-reference/rest#error-codes"
},
"request_id": "req_20260706_8f3a2b"
}
Error Code Table
EnerOS error codes are divided into five categories: client errors (4xx), server errors (5xx), gateway errors, security errors, and business errors.
Client Errors (4xx)
| HTTP | Error Code | Meaning | Handling Suggestion |
|---|---|---|---|
| 400 | INVALID_REQUEST | Invalid request parameters or JSON format error | Check request body and parameters |
| 400 | INVALID_FIELD | Invalid field value (e.g., enum mismatch) | Check field description |
| 401 | UNAUTHORIZED | Not authenticated or token invalid | Re-obtain token |
| 401 | TOKEN_EXPIRED | Token has expired | Refresh token |
| 403 | FORBIDDEN | Insufficient permissions | Contact administrator to adjust role |
| 403 | TENANT_MISMATCH | Cross-tenant access denied | Check X-Tenant-Id |
| 404 | NOT_FOUND | Resource does not exist | Verify resource ID |
| 405 | METHOD_NOT_ALLOWED | HTTP method not supported | Check endpoint definition |
| 409 | CONFLICT | Resource state conflict | Re-read and retry |
| 409 | CONSTRAINT_VIOLATION | Security constraint violation | Correct electrical parameters |
| 413 | PAYLOAD_TOO_LARGE | Request body exceeds 1MB | Reduce batch size |
| 422 | VALIDATION_FAILED | Business validation failed | Check error details |
| 429 | RATE_LIMITED | Rate limit triggered | Retry per Retry-After |
Server Errors (5xx)
| HTTP | Error Code | Meaning | Handling Suggestion |
|---|---|---|---|
| 500 | INTERNAL_ERROR | Uncaught kernel error | Contact operations, attach trace_id |
| 501 | NOT_IMPLEMENTED | Endpoint not yet implemented | Wait for version update |
| 502 | BAD_GATEWAY | Upstream service exception | Retry or check dependencies |
| 503 | SERVICE_UNAVAILABLE | Service overloaded or under maintenance | Backoff and retry |
| 504 | GATEWAY_TIMEOUT | Gateway timed out waiting for upstream | Check if task is asynchronous |
Security Errors
| HTTP | Error Code | Meaning | Handling Suggestion |
|---|---|---|---|
| 401 | CERT_INVALID | mTLS certificate invalid | Check certificate chain |
| 401 | CERT_EXPIRED | Certificate has expired | Rotate certificate |
| 403 | IP_BLOCKED | IP blacklisted | Contact administrator to unblock |
| 403 | AUDIT_REQUIRED | Operation requires audit trail | Add audit context |
Business Errors
| HTTP | Error Code | Meaning | Handling Suggestion |
|---|---|---|---|
| 409 | POWERFLOW_DIVERGED | Load flow did not converge | Adjust initial values or method |
| 409 | NETWORK_LOCKED | Network is locked (computation in progress) | Wait or release lock |
| 422 | TOPOLOGY_INVALID | Topology invalid (island/loop) | Fix topology |
| 422 | PARAM_OUT_OF_RANGE | Electrical parameter out of bounds | Check upper/lower limits |
| 422 | AGENT_BUSY | Agent is busy | Queue or wait |
Version Management
EnerOS API adopts a dual strategy of URL path versioning + semantic versioning:
| Version | Status | Release Date | Deprecation Date | Description |
|---|---|---|---|---|
v1 | Stable | 2026-01 | — | Current major version |
v2 | Preview | 2026-09 (planned) | — | Next major version |
See Version Management for detailed strategy.
Rate Limiting Strategy
EnerOS adopts layered rate limiting, see Rate Limiting and Quota:
| Dimension | Rate | Description |
|---|---|---|
| Global (IP) | 600 req/min | Prevent malicious API abuse |
| Tenant | 5000 req/h | Fair scheduling |
| Computation endpoints | 30 req/min | Protect kernel compute power |
| Time-series writes | 1000 req/min | High-throughput scenarios |
All rate limit responses include X-RateLimit-* response headers for client adaptive rate reduction.
SDK List
EnerOS officially provides the following SDKs, encapsulating common logic such as authentication, retry, and serialization:
| Language | Package Name | Version | Maintenance Status | Repository |
|---|---|---|---|---|
| Rust | eneros-sdk | 0.47.0 | Official mainline | eneros/crates/eneros-sdk |
| Python | eneros-sdk-python | 0.47.0 | Official sync | eneros/sdks/python |
| JavaScript/TypeScript | @eneros/sdk | 0.47.0 | Official sync | eneros/sdks/js |
| Go | eneros-sdk-go | 0.47.0 | Community contributed | github.com/eneros/go-sdk |
| Java | eneros-sdk-java | 0.45.0 | Community contributed | github.com/eneros/java-sdk |
SDK Selection Suggestion
// Rust SDK example
use eneros_sdk::ApiClient;
let client = ApiClient::builder()
.endpoint("http://localhost:8080")
.api_version("v1")
.token("<bearer-token>")
.build()?;
let networks = client.networks().list().await?;
# Python SDK example
from eneros_sdk import ApiClient
client = ApiClient(
endpoint="http://localhost:8080",
api_version="v1",
token="<bearer-token>",
)
networks = client.networks.list()
// JavaScript SDK example
import { ApiClient } from '@eneros/sdk';
const client = new ApiClient({
endpoint: 'http://localhost:8080',
apiVersion: 'v1',
token: '<bearer-token>',
});
const networks = await client.networks.list();
Quick Verification
Use cURL to quickly verify API availability:
# 1. Health check (no authentication required)
curl http://localhost:8080/api/v1/health
# 2. Get Token (development environment)
curl -X POST http://localhost:8080/api/v1/auth/token \
-H "Content-Type: application/json" \
-d '{"username":"admin","password":"admin"}'
# 3. Get network list
curl -H "Authorization: Bearer <token>" \
http://localhost:8080/api/v1/networks
# 4. Create Agent
curl -X POST http://localhost:8080/api/v1/agents \
-H "Authorization: Bearer <token>" \
-H "Content-Type: application/json" \
-d '{"type":"dispatch","config":{}}'
# 5. GraphQL query
curl -X POST http://localhost:8080/graphql \
-H "Content-Type: application/json" \
-H "Authorization: Bearer <token>" \
-d '{"query":"{ networks { id name } }"}'
# 6. SSE subscribe to alerts
curl -N -H "Authorization: Bearer <token>" \
"http://localhost:8080/api/v1/events/stream?topics=alarm&severity=critical"
Common Response Field Enums
Resource Status Enums
| Resource | Status Values | Description |
|---|---|---|
| Network | draft / ready / locked / archived | Draft/Ready/Locked/Archived |
| Agent | idle / running / paused / error / stopped | Idle/Running/Paused/Error/Stopped |
| Device | online / offline / maintenance / fault | Online/Offline/Maintenance/Fault |
| Task | queued / running / completed / failed / cancelled | Queued/Running/Completed/Failed/Cancelled |
| Alarm | active / acknowledged / cleared | Active/Acknowledged/Cleared |
Severity Level Enums
| Value | Numeric | Description |
|---|---|---|
info | 0 | Information |
warn | 1 | Warning |
error | 2 | Error |
critical | 3 | Critical, requires immediate action |
Related Documentation
- REST API — Complete endpoint documentation
- GraphQL — Schema and query examples
- WebSocket — Real-time event stream protocol
- SSE Real-time Push — One-way subscription endpoint
- Rate Limiting and Quota — Rate limiting strategy
- Version Management — API version evolution