API Integration
This document covers how to integrate with OctoMesh APIs, including authentication, GraphQL operations, and the service client SDK.
API Overview
OctoMesh provides multiple API access methods:
| API Type | Protocol | Use Case |
|---|---|---|
| GraphQL | HTTPS | Primary data access, queries, mutations |
| REST | HTTPS | Administrative operations, file uploads |
| AMQP | RabbitMQ | Real-time messaging, adapter communication |
Authentication
OAuth 2.0 / OpenID Connect
OctoMesh uses OAuth 2.0 with OpenID Connect for authentication.
Obtaining Access Tokens
OctoMesh supports two primary authentication methods depending on whether a user context is needed.
Authorization Code with PKCE (User-Based)
Use this flow when your application acts on behalf of a user. The user authenticates interactively, and the issued token contains their identity, roles, and tenant context.
Step 1 — Redirect the user to the authorize endpoint:
GET /connect/authorize?
response_type=code
&client_id=my-application
&redirect_uri=https://my-app.example.com/callback
&scope=openid profile email role octo_api
&acr_values=tenant:{tenantId}
&code_challenge={challenge}
&code_challenge_method=S256
&state={state}
The acr_values=tenant:{tenantId} parameter directs the Identity Service to the correct tenant's login page. The user authenticates with the credentials and identity providers configured for that tenant.
Step 2 — Exchange the authorization code for tokens:
POST /connect/token HTTP/1.1
Host: identity.octomesh.local
Content-Type: application/x-www-form-urlencoded
grant_type=authorization_code
&client_id=my-application
&code={authorization_code}
&redirect_uri=https://my-app.example.com/callback
&code_verifier={verifier}
Response:
{
"access_token": "eyJhbGciOiJSUzI1NiIsInR5cCI6IkpXVCJ9...",
"id_token": "eyJhbGciOiJSUzI1NiIsInR5cCI6IkpXVCJ9...",
"token_type": "Bearer",
"expires_in": 3600,
"scope": "openid profile email role octo_api"
}
The issued access token contains the user's sub, tenant_id, role, and allowed_tenants claims scoped to the selected tenant.
The OAuth client must be registered in each tenant where users need to authenticate. See Clients and API Scopes for details on client management.
Client Credentials (Service-to-Service)
Use this flow for background services and automated processes where no user is involved. The client authenticates with its own credentials.
POST /connect/token HTTP/1.1
Host: identity.octomesh.local
Content-Type: application/x-www-form-urlencoded
grant_type=client_credentials
&client_id=my-service
&client_secret=my-secret
&scope=octo_api
&acr_values=tenant:my-tenant
acr_values is requiredClients are registered per tenant, and /connect/token has no tenant path segment. The acr_values=tenant:{tenantId} form parameter tells the Identity Service which tenant's client store to search — without it the lookup falls back to the system tenant and the request fails with invalid_client for any tenant-registered client.
Response:
{
"access_token": "eyJhbGciOiJSUzI1NiIsInR5cCI6IkpXVCJ9...",
"token_type": "Bearer",
"expires_in": 3600,
"scope": "octo_api"
}
Client-credentials tokens have no user identity (sub claim) and no allowed_tenants claim. They carry tenant_id = the tenant selected with acr_values, and services check the route tenant against it like for user tokens: a service token may address only its own tenant unless its client is allow-listed. See Tenant Authorization and Tenant Generations.
API Scopes
| Scope | Description |
|---|---|
octo_api | Full read/write access to all OctoMesh APIs |
octo_api.read_only | Read-only access to all OctoMesh APIs |
Using the Token
Include the token in the Authorization header:
GET /tenants/my-tenant/graphql HTTP/1.1
Host: asset-repo.octomesh.local
Authorization: Bearer eyJhbGciOiJSUzI1NiIsInR5cCI6IkpXVCJ9...
Content-Type: application/json
GraphQL API
Endpoint
https://{asset-repo-host}/tenants/{tenantId}/graphql
GraphQL Playground (interactive explorer):
https://{asset-repo-host}/tenants/{tenantId}/graphql/playground
Query Structure
The GraphQL schema is organized into two main query roots:
type Query {
runtime: RuntimeQuery # Master data (MongoDB)
streamData: StreamQuery # Time-series data (CrateDB)
}
type Mutation {
runtime: RuntimeMutation
}
Runtime Queries
Query all entities of a type:
query GetEnergyMeters {
runtime {
rtIndustryEnergyEnergyMeter(
first: 50
after: "cursor"
filter: {
status: { eq: "Active" }
}
orderBy: { name: ASC }
) {
items {
rtId
ckTypeId
wellKnownName
name
serialNumber
status
location {
items {
rtId
name
address
}
}
}
pageInfo {
hasNextPage
endCursor
totalCount
}
}
}
}
Query by ID:
query GetMeterById($rtId: OctoObjectId!) {
runtime {
rtIndustryEnergyEnergyMeterById(rtId: $rtId) {
rtId
name
serialNumber
readings(first: 10) {
items {
timestamp
value
}
}
}
}
}
Query by wellKnownName:
query GetMeterByName {
runtime {
rtIndustryEnergyEnergyMeterByWellKnownName(
wellKnownName: "main-building-meter"
) {
rtId
name
}
}
}
Stream Data Queries
Query time-series data:
query GetMeterReadings($rtId: OctoObjectId!) {
streamData {
tsIndustryEnergyMeterReading(
first: 1000
filter: {
rtId: { eq: $rtId }
timestamp: {
gte: "2024-01-01T00:00:00Z"
lte: "2024-01-31T23:59:59Z"
}
}
orderBy: { timestamp: DESC }
) {
items {
rtId
timestamp
voltage
current
power
energy
}
pageInfo {
hasNextPage
endCursor
}
}
}
}
Mutations
Create entity:
mutation CreateEnergyMeter {
runtime {
createRtIndustryEnergyEnergyMeter(
entity: {
wellKnownName: "new-meter-001"
attributes: {
name: "New Energy Meter"
serialNumber: "EM-2024-001"
manufacturer: "Siemens"
status: Active
}
}
) {
rtId
wellKnownName
}
}
}
Update entity:
mutation UpdateEnergyMeter($rtId: OctoObjectId!) {
runtime {
updateRtIndustryEnergyEnergyMeter(
rtId: $rtId
entity: {
attributes: {
status: Maintenance
}
}
) {
rtId
status
}
}
}
Delete entity:
mutation DeleteEnergyMeter($rtId: OctoObjectId!) {
runtime {
deleteRtIndustryEnergyEnergyMeter(rtId: $rtId)
}
}
Manage associations:
mutation AddMeterToLocation($meterId: OctoObjectId!, $locationId: OctoObjectId!) {
runtime {
addAssociationRtIndustryEnergyEnergyMeter(
rtId: $meterId
association: "location"
targetRtIds: [$locationId]
) {
rtId
location {
items {
rtId
}
}
}
}
}
Filtering
OctoMesh GraphQL supports rich filtering:
query FilteredQuery {
runtime {
rtIndustryEnergyEnergyMeter(
filter: {
AND: [
{ status: { eq: "Active" } }
{
OR: [
{ manufacturer: { contains: "Siemens" } }
{ manufacturer: { contains: "ABB" } }
]
}
{ maxCapacity: { gte: 100 } }
]
}
) {
items {
rtId
name
}
}
}
}
Available filter operators:
| Operator | Description |
|---|---|
eq | Equals |
neq | Not equals |
gt / gte | Greater than / Greater than or equal |
lt / lte | Less than / Less than or equal |
contains | String contains |
startsWith | String starts with |
endsWith | String ends with |
in | Value in list |
AND / OR | Logical operators |
Service Client SDK
The .NET SDK provides a typed client for OctoMesh APIs.
Installation
dotnet add package Meshmakers.Octo.Sdk.ServiceClient
Configuration
using Meshmakers.Octo.Sdk.ServiceClient;
var services = new ServiceCollection();
services.AddOctoMeshServiceClient(options =>
{
options.IdentityServiceUrl = "https://identity.octomesh.local";
options.AssetRepositoryUrl = "https://asset-repo.octomesh.local";
options.ClientId = "my-application";
options.ClientSecret = "my-secret";
options.TenantId = "my-tenant";
});
Using the Service Client
public class MyService
{
private readonly IAssetRepositoryClient _client;
public MyService(IAssetRepositoryClient client)
{
_client = client;
}
public async Task<IEnumerable<EnergyMeter>> GetActiveMetersAsync(
CancellationToken cancellationToken)
{
var query = new GraphQLRequest
{
Query = @"
query {
runtime {
rtIndustryEnergyEnergyMeter(
filter: { status: { eq: ""Active"" } }
) {
items {
rtId
name
serialNumber
}
}
}
}"
};
var response = await _client.ExecuteGraphQLAsync<EnergyMeterResponse>(
query, cancellationToken);
return response.Runtime.RtIndustryEnergyEnergyMeter.Items;
}
public async Task<string> CreateMeterAsync(
CreateMeterRequest request,
CancellationToken cancellationToken)
{
var mutation = new GraphQLRequest
{
Query = @"
mutation CreateMeter($input: CreateEnergyMeterInput!) {
runtime {
createRtIndustryEnergyEnergyMeter(entity: $input) {
rtId
}
}
}",
Variables = new { input = request }
};
var response = await _client.ExecuteGraphQLAsync<CreateMeterResponse>(
mutation, cancellationToken);
return response.Runtime.CreateRtIndustryEnergyEnergyMeter.RtId;
}
}
Source Generation
Use source generation to create typed DTOs:
dotnet add package Meshmakers.Octo.Sdk.SourceGeneration
// Define your models with source generation attributes
[GenerateGraphQLTypes("Industry.Energy/EnergyMeter")]
public partial class EnergyMeterDto
{
}
// Generated code provides:
// - Strongly typed properties matching CK attributes
// - Serialization support
// - GraphQL query/mutation helpers
REST API
Operations that move from REST to CK methods keep their REST endpoint until a sunset date that is announced in advance.
Deprecated REST Endpoints and Sunset Dates lists every deprecated endpoint with the method
that replaces it and its sunset date, and explains the Deprecation, Sunset and Link response headers.
Administrative Endpoints
Get tenant information:
GET /api/tenants/{tenantId}
Authorization: Bearer {token}
Upload file:
POST /api/tenants/{tenantId}/files
Authorization: Bearer {token}
Content-Type: multipart/form-data
file=@document.pdf
Get system health:
GET /health
Construction Kit Management
List CK libraries:
GET /api/tenants/{tenantId}/construction-kits
Authorization: Bearer {token}
Upload CK library:
POST /api/tenants/{tenantId}/construction-kits
Authorization: Bearer {token}
Content-Type: application/json
{
"libraryId": "MyCompany.Domain",
"version": "1.0.0",
"types": [...],
"enums": [...]
}
Which tenants may my app offer?
An application that lets a signed-in user pick a tenant (a tenant switcher, a list of plants or customers) has to learn which tenants below its root tenant the user may use. Two rules:
- Access to a tenant's API needs a token of that tenant: every OctoMesh API service with tenant routes (all except platform services) compares the route tenant with the token's
tenant_id(see Tenant Authorization and Tenant Generations). Theallowed_tenantsclaim lists the tenants the user may switch to; to use one, the app signs the user in to it or exchanges the token. - Capability — which tenants exist below the root, how deep they are, and whether they have children — comes from the Identity Service, via the Tenant Topology API. Never derive it by calling the GraphQL or REST route of another tenant with the user's token: the tenant check of the OctoMesh API services refuses such calls when it is enforced, so an app built that way stops working.
Angular applications use TenantTopologyService.load(rootTenantId) of @meshmakers/shared-auth (see the "Tenant Topology" section of the shared-auth library documentation); it never throws, caches per session and reports why a topology is unknown. Other clients call GET /api/tenant-topology?scope=<rootTenantId> with the user's bearer token.
Reading the result
The response lists the tenants the user may use below the root, each with depth (1 = direct child of the root) and hasChildren. Two shapes are known:
| Shape | Example | What the app offers |
|---|---|---|
| Direct children of the root | acme-root → acme-plant-a, acme-plant-b (depth 1, hasChildren: false) | The tenants with hasChildren: false. |
| Leaves below grouping tenants | acme-root → acme-group-b (depth 1, hasChildren: true) → acme-plant-b1 (depth 2, hasChildren: false) | The tenants with hasChildren: false at any depth. A tenant with hasChildren: true is a grouping tenant: use it for navigation, not as the place the user works in. |
If scopeHasChildren is false (and tenants is empty), the root has no tenants below it. This is the legacy single-tenant case: the root tenant itself is the application tenant.
When the topology is unknown
Treat every failure as "topology unknown" and fall back to the tenant of the token only. Never fall back to a call to another tenant.
| Answer | Meaning | What the app does |
|---|---|---|
404, or 200 with a content type that is not JSON | The Identity Service is older than the endpoint | Show only the token tenant; do not retry for the session. |
401 | Token expired or invalid | Let the normal token refresh run; show the token tenant meanwhile. |
403 | Client-credentials token, or the user token lacks the octo_api read scope | Show only the token tenant; fix the app's client configuration. |
400 | The root tenant id is missing or empty | Fix the app configuration. |
429 | Rate limit | Wait (Retry-After: 60) and use the cached result meanwhile. |
503 | Identity could not read the whole hierarchy | Show the token tenant and try again later; never act on a partial list. |
None of this is a security boundary. The topology only shapes what the app offers; the backend checks the tenant and the permissions on every request.
Error Handling
GraphQL Errors
GraphQL errors are returned in the errors array:
{
"data": null,
"errors": [
{
"message": "Entity not found",
"locations": [{ "line": 2, "column": 3 }],
"path": ["runtime", "rtIndustryEnergyEnergyMeterById"],
"extensions": {
"code": "ENTITY_NOT_FOUND",
"details": {
"rtId": "invalid-id"
}
}
}
]
}
Common Error Codes
| Code | Description |
|---|---|
UNAUTHORIZED | Missing or invalid token |
FORBIDDEN | Insufficient permissions |
ENTITY_NOT_FOUND | Requested entity does not exist |
VALIDATION_ERROR | Input validation failed |
CK_TYPE_NOT_FOUND | Construction Kit type not found |
ASSOCIATION_ERROR | Invalid association operation |
Client-Side Error Handling
try
{
var result = await _client.ExecuteGraphQLAsync<Response>(query, ct);
if (result.Errors?.Any() == true)
{
foreach (var error in result.Errors)
{
_logger.LogError("GraphQL error: {Message} (Code: {Code})",
error.Message,
error.Extensions?["code"]);
}
throw new OctoMeshException("GraphQL operation failed", result.Errors);
}
return result.Data;
}
catch (HttpRequestException ex)
{
_logger.LogError(ex, "HTTP request failed");
throw;
}
catch (AuthenticationException ex)
{
_logger.LogError(ex, "Authentication failed");
// Refresh token and retry
throw;
}
Rate Limiting
OctoMesh implements rate limiting to protect the platform:
| Endpoint Type | Limit |
|---|---|
| GraphQL queries | 100 req/min per client |
| Mutations | 50 req/min per client |
| File uploads | 10 req/min per client |
When rate limited, you'll receive:
HTTP/1.1 429 Too Many Requests
Retry-After: 60
Best Practices
Query Optimization
- Request only needed fields: Reduce response size
- Use pagination: Always set
firstparameter - Filter server-side: Don't fetch and filter client-side
- Batch related queries: Combine in single request
Connection Management
- Reuse HTTP clients: Use connection pooling
- Handle token refresh: Implement automatic refresh
- Implement retry logic: Handle transient failures
- Use timeouts: Set appropriate request timeouts
Security
- Secure credentials: Use secrets management
- Minimal scopes: Request only needed permissions
- Validate responses: Don't trust external data
- Log securely: Don't log tokens or sensitive data
Next Steps
- SDK Overview: Explore available SDK libraries
- Adapter Development: Build custom integrations
- Deprecated REST Endpoints: Replacing methods and sunset dates
- API Reference: Complete API documentation