Skip to main content

API Overview

API Reference

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:

TypeProtocolTransmission DirectionApplicable ScenariosReal-timeBrowser NativeAuto ReconnectTypical Use
RESTHTTP/1.1 or HTTP/2Request-ResponseCRUD operations, configuration management, batch tasksSynchronousYes (fetch)NoNetwork/Agent/Device management
GraphQLHTTP/1.1 or HTTP/2Request-ResponseFlexible queries, on-demand data fetching, aggregate analysisSynchronousYes (fetch)NoCross-resource aggregate queries
WebSocketWS/WSS (HTTP upgrade)Bidirectional full-duplexReal-time event push, remote command dispatchReal-time (millisecond)Yes (WebSocket)Manual implementation requiredAgent status, control commands
SSEHTTP/1.1 long connectionServer→ClientOne-way real-time push, lightweight subscriptionReal-time (second)Yes (EventSource)YesAlert 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

DimensionRESTGraphQLWebSocketSSE
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 tenantUnlimitedUnlimited2050
Protocol overheadMediumMediumLow (after first packet)Low

Basic Information

Base URL

The root URL of the EnerOS API depends on the deployment mode:

Deployment ModeBase URLDescription
Standalone localhttp://localhost:8080/api/v1Development and testing
Standalone productionhttps://api.example.com/api/v1Single instance external
Multi-regionhttps://{region}.api.eneros.io/api/v1e.g., cn-east.api.eneros.io
Intranet meshhttp://eneros-api.nerve.svc:8080/api/v1Kubernetes internal

Protocol endpoints:

ProtocolEndpointDescription
RESThttp://<host>:8080/api/v1Resource CRUD
GraphQLhttp://<host>:8080/graphqlQuery / Mutation
GraphQL Subscriptionws://<host>:8080/graphqlReal-time subscription
WebSocketws://<host>:8080/wsBidirectional event stream
SSEhttp://<host>:8080/api/v1/events/streamOne-way push

Production environments enforce HTTPS / WSS, with certificates issued by eneros-trust.

Common Conventions

ItemValue
Content Typeapplication/json; charset=utf-8
Character EncodingUTF-8
Time FormatRFC 3339 / UTC (e.g., 2026-07-06T08:30:00Z)
TimezoneAll timestamps default to UTC, can append ?tz=Asia/Shanghai for display conversion
Numeric PrecisionFloating-point uses IEEE 754 double, electrical quantities default to 6 significant digits
ID FormatString, prefix identifies type (net_, agent_, dev_, evt_)
Resource NamingPlural form (/networks, /agents, /devices)
Field NamingBackend 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...
FieldTypeRequiredDefaultDescription
AuthorizationstringYesFixed prefix Bearer + JWT
Token FormatJWT (RS256)Header.Payload.Signature
Token Validityint (seconds)3600Configurable in eneros.toml
Refresh TokenstringNo30-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
FieldTypeRequiredDefaultDescription
Client CertificateX.509 PEMYesCN must be agent-{id} or service-{name}
Client Private KeyRSA/EC PEMYesAt least 2048 bits
CA CertificateX.509 PEMYesEnerOS internal CA
Certificate Validityint (days)365Alert 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

MethodSecurity LevelApplicable ScenariosExpiry ManagementMutual Identity Verification
Bearer TokenMediumWeb/App terminals, short-term sessionsAuto expiry + refreshNo
mTLSHighInter-service, Agent ↔ GatewayCertificate rotationYes
API KeyLowInternal trusted servicesManual rotationNo

Common Request Headers

HeaderTypeRequiredDefaultDescription
AuthorizationstringYes*Bearer <token>, except for public endpoints
Content-TypestringYesapplication/jsonRequired for POST/PUT/PATCH
AcceptstringNoapplication/jsonCan specify application/json or application/graphql-response+json
X-Tenant-IdstringNoAuto-parsed from TokenExplicitly specify tenant, requires cross-tenant permission
X-Request-IdstringNoAuto-generated UUIDTrace ID, transparently passed to audit log
X-Trace-IdstringNoOpenTelemetry trace ID
User-AgentstringNoeneros-client/0.1Client identifier
Accept-LanguagestringNozh-CNError message language

Common Response Format

Success Response

All REST success responses are JSON, with top-level fields as follows:

FieldTypeRequiredDescription
dataobject/arrayYesBusiness data body
metaobjectNoPagination, version, and other metadata
request_idstringYesRequest trace ID
timestampstringYesResponse 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:

FieldTypeRequiredDescription
error.codestringYesUppercase underscore error code
error.messagestringYesHuman-readable error description
error.detailsobjectNoStructured supplementary information
error.trace_idstringYesTrace ID
error.doc_urlstringNoDocumentation link
request_idstringYesRequest 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)

HTTPError CodeMeaningHandling Suggestion
400INVALID_REQUESTInvalid request parameters or JSON format errorCheck request body and parameters
400INVALID_FIELDInvalid field value (e.g., enum mismatch)Check field description
401UNAUTHORIZEDNot authenticated or token invalidRe-obtain token
401TOKEN_EXPIREDToken has expiredRefresh token
403FORBIDDENInsufficient permissionsContact administrator to adjust role
403TENANT_MISMATCHCross-tenant access deniedCheck X-Tenant-Id
404NOT_FOUNDResource does not existVerify resource ID
405METHOD_NOT_ALLOWEDHTTP method not supportedCheck endpoint definition
409CONFLICTResource state conflictRe-read and retry
409CONSTRAINT_VIOLATIONSecurity constraint violationCorrect electrical parameters
413PAYLOAD_TOO_LARGERequest body exceeds 1MBReduce batch size
422VALIDATION_FAILEDBusiness validation failedCheck error details
429RATE_LIMITEDRate limit triggeredRetry per Retry-After

Server Errors (5xx)

HTTPError CodeMeaningHandling Suggestion
500INTERNAL_ERRORUncaught kernel errorContact operations, attach trace_id
501NOT_IMPLEMENTEDEndpoint not yet implementedWait for version update
502BAD_GATEWAYUpstream service exceptionRetry or check dependencies
503SERVICE_UNAVAILABLEService overloaded or under maintenanceBackoff and retry
504GATEWAY_TIMEOUTGateway timed out waiting for upstreamCheck if task is asynchronous

Security Errors

HTTPError CodeMeaningHandling Suggestion
401CERT_INVALIDmTLS certificate invalidCheck certificate chain
401CERT_EXPIREDCertificate has expiredRotate certificate
403IP_BLOCKEDIP blacklistedContact administrator to unblock
403AUDIT_REQUIREDOperation requires audit trailAdd audit context

Business Errors

HTTPError CodeMeaningHandling Suggestion
409POWERFLOW_DIVERGEDLoad flow did not convergeAdjust initial values or method
409NETWORK_LOCKEDNetwork is locked (computation in progress)Wait or release lock
422TOPOLOGY_INVALIDTopology invalid (island/loop)Fix topology
422PARAM_OUT_OF_RANGEElectrical parameter out of boundsCheck upper/lower limits
422AGENT_BUSYAgent is busyQueue or wait

Version Management

EnerOS API adopts a dual strategy of URL path versioning + semantic versioning:

VersionStatusRelease DateDeprecation DateDescription
v1Stable2026-01Current major version
v2Preview2026-09 (planned)Next major version

See Version Management for detailed strategy.

Rate Limiting Strategy

EnerOS adopts layered rate limiting, see Rate Limiting and Quota:

DimensionRateDescription
Global (IP)600 req/minPrevent malicious API abuse
Tenant5000 req/hFair scheduling
Computation endpoints30 req/minProtect kernel compute power
Time-series writes1000 req/minHigh-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:

LanguagePackage NameVersionMaintenance StatusRepository
Rusteneros-sdk0.47.0Official mainlineeneros/crates/eneros-sdk
Pythoneneros-sdk-python0.47.0Official synceneros/sdks/python
JavaScript/TypeScript@eneros/sdk0.47.0Official synceneros/sdks/js
Goeneros-sdk-go0.47.0Community contributedgithub.com/eneros/go-sdk
Javaeneros-sdk-java0.45.0Community contributedgithub.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

ResourceStatus ValuesDescription
Networkdraft / ready / locked / archivedDraft/Ready/Locked/Archived
Agentidle / running / paused / error / stoppedIdle/Running/Paused/Error/Stopped
Deviceonline / offline / maintenance / faultOnline/Offline/Maintenance/Fault
Taskqueued / running / completed / failed / cancelledQueued/Running/Completed/Failed/Cancelled
Alarmactive / acknowledged / clearedActive/Acknowledged/Cleared

Severity Level Enums

ValueNumericDescription
info0Information
warn1Warning
error2Error
critical3Critical, requires immediate action