### Install TypeScript SDK Source: https://github.com/opendpp/opendpp-sdk/blob/main/README.md Install the OpenDPP SDK for TypeScript using npm. This command is required before using the SDK in your project. ```sh npm install @opendpp/sdk ``` -------------------------------- ### Reference Guides Source: https://github.com/opendpp/opendpp-sdk/blob/main/_autodocs/README.md Guides covering types, configuration, errors, and endpoints. ```APIDOC ## Reference Guides ### Types - **`types.md`**: Contains all named type definitions, including request/response shapes, error types, enums, and interfaces. ### Configuration - **`configuration.md`**: Details client setup, environment variables, authentication, runtime options, TLS, and Node.js requirements. ### Errors - **`errors.md`**: Explains HTTP status codes, error response formats, trigger conditions, and recovery strategies for all failure scenarios. ### Endpoints - **`endpoints.md`**: Provides a complete index of all endpoints, including HTTP methods, paths, query parameters, authentication requirements, and rate limits. ``` -------------------------------- ### Minimal OpenDPP Client Setup Source: https://github.com/opendpp/opendpp-sdk/blob/main/_autodocs/INDEX.md Initialize the OpenDPP client with your API key. Ensure the OPENDPP_API_KEY environment variable is set. ```typescript import { createOpenDppClient } from "@opendpp/sdk"; const client = createOpenDppClient({ apiKey: process.env.OPENDPP_API_KEY }); ``` -------------------------------- ### GET /api/v1/facilities Source: https://github.com/opendpp/opendpp-sdk/blob/main/_autodocs/endpoints.md Lists all facilities. Supports pagination and rate limiting. ```APIDOC ## GET /api/v1/facilities ### Description List all facilities. ### Method GET ### Endpoint /api/v1/facilities ### Query Parameters - page (string) - Optional - Page number for pagination - limit (string) - Optional - Number of items per page ### Response #### Success Response (200) - ListFacilitiesResponses (object) **SDK Function:** `listFacilities(options?)` ``` -------------------------------- ### Create OpenDPP Client Examples Source: https://github.com/opendpp/opendpp-sdk/blob/main/_autodocs/configuration.md Demonstrates creating an OpenDPP client with different configurations. Use minimal settings for public nodes, provide an apiKey for authenticated operations, or specify a custom baseUrl for workspace subdomains. ```typescript import { createOpenDppClient, createPassport } from "@opendpp/sdk"; // Minimal: use public node, no auth const publicClient = createOpenDppClient(); // With API key: enable authenticated operations const authClient = createOpenDppClient({ apiKey: process.env.OPENDPP_API_KEY }); // Custom workspace subdomain const workspaceClient = createOpenDppClient({ baseUrl: "https://acme.opendpp-node.eu", apiKey: process.env.OPENDPP_API_KEY }); ``` -------------------------------- ### Full Configuration and Usage in Node.js Source: https://github.com/opendpp/opendpp-sdk/blob/main/_autodocs/configuration.md This example demonstrates how to set up the OpenDPP client, verify authentication, and create a new passport within a Node.js application. Ensure your OPENDPP_API_KEY and OPENDPP_BASE_URL environment variables are set. ```typescript import { createOpenDppClient, whoami, createPassport } from "@opendpp/sdk"; // Load configuration const config = { apiKey: process.env.OPENDPP_API_KEY, baseUrl: process.env.OPENDPP_BASE_URL || "https://opendpp-node.eu" }; // Create client const client = createOpenDppClient({ apiKey: config.apiKey, baseUrl: config.baseUrl }); // Verify authentication async function verifyAuth() { const identity = await whoami({ client }); console.log(`✓ Authenticated as: ${identity.auth.role}`); console.log(` Workspace: ${identity.tenant.name}`); console.log(` Quota: ${identity.usage.activePassports}/${identity.usage.passportLimit}`); } // Create passport async function createNewPassport() { const result = await createPassport({ client, body: { productId: "00012345678905", metadata: { category: "light_sources", productName: "LED Bulb", productDescription: "Energy-efficient LED" } } }); if (result.error) { console.error(`Error: ${result.status} ${result.message}`); if (result.data?.errors) { result.data.errors.forEach(e => console.error(` ${e.path}: ${e.message}`)); } } else { console.log(`✓ Created passport: ${result.id}`); } } // Run await verifyAuth(); await createNewPassport(); ``` -------------------------------- ### GET /api/v1/materials Source: https://github.com/opendpp/opendpp-sdk/blob/main/_autodocs/endpoints.md Lists all available materials. This endpoint provides a catalog of supported materials. ```APIDOC ## GET /api/v1/materials ### Description List available materials. ### Method GET ### Endpoint /api/v1/materials ### Response #### Success Response - **MaterialVocabularyListResponse** - A list of available materials. ### SDK Function `listMaterials(options?)` ``` -------------------------------- ### Node.js ESM Import Example Source: https://github.com/opendpp/opendpp-sdk/blob/main/_autodocs/configuration.md The SDK is ESM-only. Use ES module imports for Node.js environments. ```typescript // ✓ ESM import { createOpenDppClient } from "@opendpp/sdk"; // ✗ CommonJS not supported const { createOpenDppClient } = require("@opendpp/sdk"); ``` -------------------------------- ### TypeScript Example with Typed Requests and Responses Source: https://github.com/opendpp/opendpp-sdk/blob/main/_autodocs/README.md Demonstrates how to use the fully typed SDK in TypeScript, including type-checking for request bodies and response types. Ensure necessary types and functions are imported. ```typescript import { createOpenDppClient, createPassport, type PassportCreateRequest, type PassportIngestCreated } from "@opendpp/sdk"; // Full typing for request and response const result: PassportIngestCreated | PassportIngestCreated = await createPassport({ client, body: {...} // Type-checked }); ``` -------------------------------- ### Quick Start: OpenDPP Client Usage Source: https://github.com/opendpp/opendpp-sdk/blob/main/typescript/README.md Demonstrates creating an OpenDPP client and making both public and authenticated API calls. Requires an API key set in the environment variable OPENDPP_API_KEY for authenticated operations. ```ts import { createOpenDppClient, getHealth, createPassport, getPassport } from "@opendpp/sdk"; const client = createOpenDppClient({ apiKey: process.env.OPENDPP_API_KEY }); // Public, no key needed: const health = await getHealth({ client }); // Behind your Developer-Plan key: const created = await createPassport({ client, body: { productId: "09501101531000", metadata: { category: "batteries", /* … */ } }, }); const passport = await getPassport({ client, path: { id: created.data!.id } }); ``` -------------------------------- ### Setup Environment Variables for SDK Source: https://github.com/opendpp/opendpp-sdk/blob/main/_autodocs/configuration.md Set environment variables to configure the SDK, including API key, base URL, and webhook secret. These are conventionally named with the OPENDPP prefix. ```bash # .env OPENDPP_API_KEY=op_dpp_token_your_key_here OPENDPP_BASE_URL=https://opendpp-node.eu OPENDPP_WEBHOOK_SECRET=your_webhook_secret_here ``` -------------------------------- ### Example of Handling Validation Errors Source: https://github.com/opendpp/opendpp-sdk/blob/main/_autodocs/errors.md Demonstrates how to call `createPassport` and process potential validation errors from the response. ```typescript const result = await createPassport({ client, body: { productId: "00012345678905", metadata: { category: "light_sources", // Missing productName... materialComposition: [ { component: "Glass", percentage: 150 } // Invalid: > 100 ] } } }); if (result.error === "Validation Failed") { console.error("Validation errors:"); result.errors.forEach(e => { console.error(` ${e.path}: ${e.friendlyMessage || e.message}`); }); } ``` -------------------------------- ### Create Grant Example Source: https://github.com/opendpp/opendpp-sdk/blob/main/_autodocs/api-reference/operators-facilities-grants.md Demonstrates how to create an access grant for another operator. The grantee must approve the grant for it to become active. Ensure you have a pre-configured client instance and the grantee's operator ID. ```typescript const grant = await createGrant({ client, body: { granteeOperatorId: "partner-operator-uuid", scope: "read", expiresAt: "2026-12-31" } }); console.log(`Grant created (pending approval): ${grant.id}`); ``` -------------------------------- ### GET /context/v1 Source: https://github.com/opendpp/opendpp-sdk/blob/main/_autodocs/endpoints.md Retrieves the base JSON-LD context. This provides foundational context for JSON-LD data. ```APIDOC ## GET /context/v1 ### Description Get base JSON-LD context. ### Method GET ### Endpoint /context/v1 ### Response #### Success Response - **JSON-LD context** - The base JSON-LD context document. ### SDK Function `getJsonLdContext(options?)` ``` -------------------------------- ### GET /api/v1/facilities/{id} Source: https://github.com/opendpp/opendpp-sdk/blob/main/_autodocs/endpoints.md Retrieves a single facility by its ID. Requires authentication and read permissions. ```APIDOC ## GET /api/v1/facilities/{id} ### Description Retrieve a single facility. ### Method GET ### Endpoint /api/v1/facilities/{id} ### Path Parameters - id (UUID) - Required - The unique identifier of the facility ### Response #### Success Response (200) - GetFacilityResponses (object) **SDK Function:** `getFacility(options)` ``` -------------------------------- ### GET /contexts/dpp/v1 Source: https://github.com/opendpp/opendpp-sdk/blob/main/_autodocs/endpoints.md Retrieves the OpenDPP JSON-LD context. This is essential for understanding and processing OpenDPP data structures. ```APIDOC ## GET /contexts/dpp/v1 ### Description Get OpenDPP JSON-LD context (no auth). ### Method GET ### Endpoint /contexts/dpp/v1 ### Response #### Success Response - **JSON-LD context** - The OpenDPP JSON-LD context document. ### SDK Function `getDppJsonLdContext(options?)` ``` -------------------------------- ### Core API Reference Source: https://github.com/opendpp/opendpp-sdk/blob/main/_autodocs/README.md Detailed function signatures, parameter tables, return types, examples, and error conditions for every exported operation. ```APIDOC ## Core API Reference Detailed function signatures, parameter tables, return types, examples, and error conditions for every exported operation. ### Client Factory - **`createOpenDppClient()`**: Initializes and configures the OpenDPP client. ### Passports - **14 operations**: Includes create, read, update, seal, validate, list, bulk, and status transitions for digital product passports. ### Battery Units - **8 operations**: Includes serialize, list, get, delete, validate, events, and QR code generation for battery units. ### Operators, Facilities, and Grants - **17 operations**: Covers registration of operators, management of facilities, and access grants. ### Webhooks - **6 operations**: Includes creating subscriptions, listing, updating, deleting, testing, rotating secrets, and accessing delivery history. ### GS1 Resolution Utilities - **14 operations**: Provides GS1 decoding, public resolution, traceability events, and system health checks. ``` -------------------------------- ### Handling Webhook Payloads Source: https://github.com/opendpp/opendpp-sdk/blob/main/_autodocs/api-reference/webhooks.md Provides guidance and code examples for securely receiving and verifying webhook payloads sent by the OpenDPP API. ```APIDOC ## Handling Webhook Payloads ### Description Webhooks are sent as POST requests with JSON bodies. It is crucial to verify the signature of incoming requests to ensure their authenticity before processing the event data. ### Behavior - **HTTPS required:** The webhook URL must use HTTPS. - **Signed payloads:** Each webhook POST includes three headers: - `X-OpenDPP-Signature`: HMAC-SHA256(body, secret) in hex - `X-OpenDPP-Timestamp`: ISO 8601 delivery timestamp - `User-Agent`: Identifies the OpenDPP webhook service - **Retry policy:** Failed deliveries are retried with exponential backoff (3 attempts). ### Verification Example ```typescript import crypto from "crypto"; function verifyWebhookSignature( body: string, signature: string, secret: string ): boolean { const hmac = crypto .createHmac("sha256", secret) .update(body) .digest("hex"); return hmac === signature; } // In your webhook handler: app.post("/webhooks/opendpp", (req, res) => { const signature = req.headers["x-opendpp-signature"]; const timestamp = req.headers["x-opendpp-timestamp"]; const body = JSON.stringify(req.body); if (!verifyWebhookSignature(body, signature, process.env.OPENDPP_WEBHOOK_SECRET)) { return res.status(401).send("Unauthorized"); } const event = req.body; console.log(`Received ${event.type} event:`, event); res.status(200).send({ success: true }); }); ``` ``` -------------------------------- ### Check for Missing Permission Source: https://github.com/opendpp/opendpp-sdk/blob/main/_autodocs/errors.md Example of how to check if a credential has the necessary permission before performing an operation. This helps in proactively handling potential authorization errors. ```typescript const identity = await whoami({ client }); if (!identity.auth.permissions.includes("passport:create")) { console.error("Missing permission: passport:create"); } ``` -------------------------------- ### GET /api/v1/grants Source: https://github.com/opendpp/opendpp-sdk/blob/main/_autodocs/endpoints.md Lists all available grants. Requires authentication and the `grant:read` permission. Supports pagination and filtering. Rate limited to 100 requests per minute per IP. ```APIDOC ## GET /api/v1/grants ### Description List all grants. ### Method GET ### Endpoint /api/v1/grants ### Parameters #### Query Parameters - **page** (string) - Optional - The page number for pagination. - **limit** (string) - Optional - The number of items per page. - **filter** (string) - Optional - Criteria to filter the grants. ### Response #### Success Response (200) - **ListGrantsResponses** (object) - Represents the response containing a list of grants. ### SDK Function `listGrants(options?)` ``` -------------------------------- ### GET /tenants/{tenantId}/did.json Source: https://github.com/opendpp/opendpp-sdk/blob/main/_autodocs/endpoints.md Retrieves the W3C Decentralized Identifier (DID) document for a given tenant. This endpoint is publicly accessible and rate-limited. ```APIDOC ## GET /tenants/{tenantId}/did.json ### Description Get tenant DID document (W3C DIDs). ### Method GET ### Endpoint /tenants/{tenantId}/did.json ### Parameters #### Path Parameters - **tenantId** (UUID) - Required - The ID of the tenant to retrieve the DID document for. ### Response #### Success Response - **DidWebDocument** - The tenant's DID document in W3C format. ``` -------------------------------- ### List Passports with Pagination Source: https://github.com/opendpp/opendpp-sdk/blob/main/_autodocs/api-reference/passports.md Retrieves a paginated list of passports, specifying the page number and items per page. This example demonstrates how to access passport IDs and product names, and log pagination details. ```typescript const result = await listPassports({ client, query: { page: 1, limit: 50 } }); result.passports.forEach(p => { console.log(`${p.id}: ${p.metadata.productName}`); }); console.log(`Page ${result.page} of ${result.totalPages}`); ``` -------------------------------- ### GET /api/v1/passports/{id}/qr Source: https://github.com/opendpp/opendpp-sdk/blob/main/_autodocs/endpoints.md Get QR code image for a passport. Retrieve a QR code image for a specific passport, with support for various image formats. ```APIDOC ## GET /api/v1/passports/{id}/qr ### Description Get QR code image for a passport. ### Method GET ### Endpoint /api/v1/passports/{id}/qr ### Parameters #### Path Parameters - **id** (UUID) - Required - The unique identifier of the passport. #### Query Parameters - **format** (string) - Optional - Image format (png, svg, etc.). Defaults to 'png'. ### Response #### Success Response - **Binary (PNG, SVG, etc.)** - The QR code image data. ``` -------------------------------- ### Get Battery Unit by ID Source: https://github.com/opendpp/opendpp-sdk/blob/main/_autodocs/api-reference/battery-units.md Retrieves a single battery unit by its ID. Use this to get the complete unit record with all telemetry and lifecycle history. Requires the unit's UUID. ```typescript const unit = await getBatteryUnit({ client, path: { id: "unit-uuid" } }); console.log(`${unit.serialNumber}: ${unit.status}`); console.log(`Manufactured: ${unit.manufacturedAt}`); ``` -------------------------------- ### Importing the Default Client Source: https://github.com/opendpp/opendpp-sdk/blob/main/_autodocs/configuration.md Illustrates importing a pre-configured default client instance from the SDK. ```typescript // Import default client import { client } from "@opendpp/sdk"; ``` -------------------------------- ### Passports - Get by ID Source: https://github.com/opendpp/opendpp-sdk/blob/main/_autodocs/endpoints.md Retrieve a single passport by its unique identifier. ```APIDOC ## GET /api/v1/passports/{id} ### Description Retrieve a single passport. ### Method GET ### Endpoint /api/v1/passports/{id} ### Parameters #### Path Parameters - **id** (UUID) - Required - The unique identifier of the passport. #### Query Parameters None ### Response #### Success Response (200) - **GetPassportResponses** (object) - The details of the requested passport. ### Request Example None ### Response Example ```json { "id": "a1b2c3d4-e5f6-7890-1234-567890abcdef", "serial_number": "SN12345", "model": "ModelX" } ``` ``` -------------------------------- ### Basic OpenDPP SDK Usage Source: https://github.com/opendpp/opendpp-sdk/blob/main/_autodocs/README.md Demonstrates creating an OpenDPP client, checking API health, and creating a product passport. Ensure your OPENDPP_API_KEY environment variable is set. ```typescript import { createOpenDppClient, createPassport, getHealth } from "@opendpp/sdk"; // Create client const client = createOpenDppClient({ apiKey: process.env.OPENDPP_API_KEY }); // Verify API is up const health = await getHealth(); console.log(`API Status: ${health.status}`); // Create a passport const result = await createPassport({ client, body: { productId: "00012345678905", metadata: { category: "light_sources", productName: "LED Bulb", productDescription: "Energy-efficient LED light source" } } }); if (result.error) { console.error(`Failed: ${result.message}`); } else { console.log(`Created: ${result.id}`); } ``` -------------------------------- ### Set Up Webhook Subscription Source: https://github.com/opendpp/opendpp-sdk/blob/main/_autodocs/README.md Demonstrates how to create a webhook subscription to receive event notifications. Store the returned secret securely. ```typescript const webhook = await createWebhookSubscription({ client, body: { url: "https://example.com/webhooks/opendpp", events: ["passport.created", "passport.sealed"], description: "Production listener" } }); console.log(`Secret: ${webhook.subscription.secret}`); // Store securely ``` -------------------------------- ### Get Base JSON-LD Context Source: https://github.com/opendpp/opendpp-sdk/blob/main/_autodocs/api-reference/gs1-resolution-utilities.md Retrieves the base JSON-LD context. This is a public endpoint. ```typescript const context = await getJsonLdContext(); ``` -------------------------------- ### GET /api/v1/units/{id} Source: https://github.com/opendpp/opendpp-sdk/blob/main/_autodocs/endpoints.md Retrieve detailed information for a single battery unit by its ID. ```APIDOC ## GET /api/v1/units/{id} ### Description Retrieve a single battery unit. ### Method GET ### Endpoint /api/v1/units/{id} ### Parameters #### Path Parameters - **id** (UUID) - Required - The unique identifier of the battery unit. ### Response #### Success Response - **GetBatteryUnitResponses** - The response containing details of the specified battery unit. ``` -------------------------------- ### Initialize and Use TypeScript SDK Source: https://github.com/opendpp/opendpp-sdk/blob/main/README.md Demonstrates how to create an OpenDPP client with an API key and retrieve health status. Ensure the OPENDPP_API_KEY environment variable is set. ```ts import { createOpenDppClient, getHealth } from "@opendpp/sdk"; const client = createOpenDppClient({ apiKey: process.env.OPENDPP_API_KEY }); const health = await getHealth({ client }); ``` -------------------------------- ### Importing All SDK Modules Source: https://github.com/opendpp/opendpp-sdk/blob/main/_autodocs/configuration.md Demonstrates importing all SDK exports using a namespace import. ```typescript // Import everything import * as sdk from "@opendpp/sdk"; ``` -------------------------------- ### GET /.well-known/opendpp-seal-ca.pem Source: https://github.com/opendpp/opendpp-sdk/blob/main/_autodocs/endpoints.md Retrieves the X.509 seal CA certificate. This is used for security and verification purposes. ```APIDOC ## GET /.well-known/opendpp-seal-ca.pem ### Description Get X.509 seal CA certificate. ### Method GET ### Endpoint /.well-known/opendpp-seal-ca.pem ### Response #### Success Response - **PEM certificate** - The X.509 seal CA certificate in PEM format. ### SDK Function `getSealCaCertificate(options?)` ``` -------------------------------- ### GET /health Source: https://github.com/opendpp/opendpp-sdk/blob/main/_autodocs/endpoints.md Performs a health check on the system. This endpoint is useful for monitoring the status of the API. ```APIDOC ## GET /health ### Description Health check (no auth). ### Method GET ### Endpoint /health ### Response #### Success Response - **HealthStatus** - The status of the system's health. ### SDK Function `getHealth(options?)` ``` -------------------------------- ### Create OpenDPP Client with Environment Variables Source: https://github.com/opendpp/opendpp-sdk/blob/main/_autodocs/configuration.md Create an OpenDPP client instance using environment variables for API key and base URL. This approach is useful for managing credentials securely. ```typescript // app.ts import { createOpenDppClient } from "@opendpp/sdk"; const client = createOpenDppClient({ apiKey: process.env.OPENDPP_API_KEY, baseUrl: process.env.OPENDPP_BASE_URL }); ``` -------------------------------- ### GET /api/v1/operators Source: https://github.com/opendpp/opendpp-sdk/blob/main/_autodocs/endpoints.md List all operators in the workspace. This endpoint retrieves a paginated list of existing operators. ```APIDOC ## GET /api/v1/operators ### Description List all operators in the workspace. ### Method GET ### Endpoint /api/v1/operators ### Parameters #### Query Parameters - **page** (integer) - Optional - The page number for pagination. - **limit** (integer) - Optional - The number of operators to return per page. ### Response #### Success Response (200) - **response** (ListOperatorsResponses) - A list of operators. #### Response Example ```json { "example": "response body for ListOperatorsResponses" } ``` ``` -------------------------------- ### GET /api/v1/passports/{passportId}/units Source: https://github.com/opendpp/opendpp-sdk/blob/main/_autodocs/endpoints.md List battery units under a specific passport. Supports pagination. ```APIDOC ## GET /api/v1/passports/{passportId}/units ### Description List battery units under a passport. ### Method GET ### Endpoint /api/v1/passports/{passportId}/units ### Parameters #### Path Parameters - **passportId** (UUID) - Required - The ID of the passport whose units are to be listed. #### Query Parameters - **page** (integer) - Optional - The page number for pagination. - **limit** (integer) - Optional - The number of items to return per page. ### Response #### Success Response - **ListBatteryUnitsResponses** - The response containing a list of battery units. ``` -------------------------------- ### Create a Passport Source: https://github.com/opendpp/opendpp-sdk/blob/main/_autodocs/README.md Demonstrates how to create a new passport using the SDK. Ensure you have your API key configured in the environment. ```typescript import { createOpenDppClient, createPassport } from "@opendpp/sdk"; const client = createOpenDppClient({ apiKey: process.env.OPENDPP_API_KEY }); const result = await createPassport({ client, body: { productId: "00012345678905", metadata: { category: "light_sources", productName: "LED Bulb", materialComposition: [ { component: "Glass", percentage: 60 }, { component: "Copper", percentage: 40 } ] } } }); if (!result.error) { console.log(`Created: ${result.id}`); console.log(`Warnings: ${result.warnings?.length ?? 0}`); } else { console.error(result.message); } ``` -------------------------------- ### Default Client Configuration Source: https://github.com/opendpp/opendpp-sdk/blob/main/_autodocs/api-reference/client.md The SDK provides a pre-configured default client instance that can be configured globally. ```APIDOC ## Default Client ### Description The SDK also exports a pre-configured default client instance. It can be configured globally instead of passing a client per operation. ### Example ```typescript import { client, getHealth } from "@opendpp/sdk"; // Configure once client.setConfig({ baseUrl: "https://opendpp-node.eu", auth: () => process.env.OPENDPP_API_KEY }); // Use it implicitly in all operations const health = await getHealth(); ``` ``` -------------------------------- ### GET /api/v1/version Source: https://github.com/opendpp/opendpp-sdk/blob/main/_autodocs/endpoints.md Retrieves information about the API version. This endpoint helps in identifying the deployed API version. ```APIDOC ## GET /api/v1/version ### Description Get API version info. ### Method GET ### Endpoint /api/v1/version ### Response #### Success Response - **GetApiVersionResponses** - Information about the API version. ### SDK Function `getApiVersion(options?)` ``` -------------------------------- ### Create a Basic Passport Source: https://github.com/opendpp/opendpp-sdk/blob/main/_autodocs/api-reference/passports.md Use this snippet to create a new passport with essential product and metadata information. Ensure the OpenDPP client is initialized and the `productId` is valid. ```typescript import { createOpenDppClient, createPassport } from "@opendpp/sdk"; const client = createOpenDppClient({ apiKey: process.env.OPENDPP_API_KEY }); const result = await createPassport({ client, body: { productId: "00012345678905", metadata: { category: "light_sources", productName: "LED Bulb", description: "Energy-efficient LED light source", materialComposition: [ { component: "Glass", percentage: 60 }, { component: "Copper", percentage: 40 } ] } } }); console.log(`Created passport ${result.passport.id}`); ``` -------------------------------- ### GET /api/v1/operators/{id} Source: https://github.com/opendpp/opendpp-sdk/blob/main/_autodocs/endpoints.md Retrieve a single operator by its ID. This endpoint fetches the details of a specific operator. ```APIDOC ## GET /api/v1/operators/{id} ### Description Retrieve a single operator. ### Method GET ### Endpoint /api/v1/operators/{id} ### Parameters #### Path Parameters - **id** (UUID) - Required - The unique identifier of the operator to retrieve. ### Response #### Success Response (200) - **response** (GetOperatorResponses) - The details of the requested operator. #### Response Example ```json { "example": "response body for GetOperatorResponses" } ``` ``` -------------------------------- ### listFacilities Source: https://github.com/opendpp/opendpp-sdk/blob/main/_autodocs/api-reference/operators-facilities-grants.md Lists all Facilities in the workspace. This endpoint supports pagination through query parameters. ```APIDOC ## listFacilities ### Description Lists all Facilities in the workspace. This endpoint supports pagination through query parameters. ### Method Not specified (SDK function call) ### Endpoint Not specified (SDK function call) ### Parameters #### Query Parameters - **options.query?.page** (number) - Optional - Page number, defaults to `1`. - **options.query?.limit** (number) - Optional - Items per page, defaults to `100` (max 200). #### Request Body None ### Response #### Success Response (200 OK) - **success** (boolean) - Indicates if the request was successful. - **count** (number) - The number of facilities returned in this page. - **total** (number) - The total number of facilities available. - **facilities** (Array) - An array of facility objects. ### Response Example ```json { "success": true, "count": 10, "total": 100, "facilities": [ { "name": "Example Facility", "gln": "1234567890123" } ] } ``` ### Rate Limits Global limiter: 100 requests/min per IP. ``` -------------------------------- ### GET /api/v1/units/{id}/qr Source: https://github.com/opendpp/opendpp-sdk/blob/main/_autodocs/endpoints.md Retrieve the QR code for a specific battery unit in a specified format. ```APIDOC ## GET /api/v1/units/{id}/qr ### Description Get QR code for a battery unit. ### Method GET ### Endpoint /api/v1/units/{id}/qr ### Parameters #### Path Parameters - **id** (UUID) - Required - The unique identifier of the battery unit for which to get the QR code. #### Query Parameters - **format** (string) - Optional - The desired format of the QR code image (e.g., PNG, SVG). ### Response #### Success Response - **Binary image** - The QR code image data. ``` -------------------------------- ### Importing Specific SDK Operations and Types Source: https://github.com/opendpp/opendpp-sdk/blob/main/_autodocs/configuration.md Shows how to import individual functions and types from the SDK for more granular control. ```typescript // Import specific operations and types import { createOpenDppClient, createPassport, getPassport, type PassportCreateRequest, type WhoamiResponse } from "@opendpp/sdk"; ``` -------------------------------- ### Get Event Lineage Source: https://github.com/opendpp/opendpp-sdk/blob/main/_autodocs/endpoints.md Retrieves the supply chain lineage for a given passport ID. This endpoint requires authentication. ```APIDOC ## GET /api/v1/events/{id}/lineage ### Description Get supply chain lineage for a passport. ### Method GET ### Endpoint /api/v1/events/{id}/lineage ### Parameters #### Path Parameters - **id** (string) - Required - The ID of the passport. #### Query Parameters - **limit** (integer) - Optional - The maximum number of lineage records to return. - **offset** (integer) - Optional - The number of lineage records to skip. ``` -------------------------------- ### Create OpenDPP Client with API Key Source: https://github.com/opendpp/opendpp-sdk/blob/main/_autodocs/README.md Instantiate the OpenDPP client using an API key, typically stored in an environment variable. This is suitable for programmatic access and integrations. ```typescript const client = createOpenDppClient({ apiKey: process.env.OPENDPP_API_KEY }); ``` -------------------------------- ### GET /api/v1/units/{id}/events Source: https://github.com/opendpp/opendpp-sdk/blob/main/_autodocs/endpoints.md List all telemetry events recorded for a specific battery unit. Supports pagination. ```APIDOC ## GET /api/v1/units/{id}/events ### Description List telemetry events for a battery unit. ### Method GET ### Endpoint /api/v1/units/{id}/events ### Parameters #### Path Parameters - **id** (UUID) - Required - The unique identifier of the battery unit whose events are to be listed. #### Query Parameters - **page** (integer) - Optional - The page number for pagination. - **limit** (integer) - Optional - The number of items to return per page. ### Response #### Success Response - **ListBatteryUnitEventsResponses** - The response containing a list of telemetry events for the battery unit. ``` -------------------------------- ### Create and Use OpenDPP Client with API Key Source: https://github.com/opendpp/opendpp-sdk/blob/main/_autodocs/api-reference/client.md Instantiate an OpenDPP client with an API key for authenticated requests. The client can then be used with any SDK operation or configured globally. ```typescript import { createOpenDppClient, getPassport, createPassport } from "@opendpp/sdk"; // Create a client with API key const client = createOpenDppClient({ apiKey: process.env.OPENDPP_API_KEY }); // Use it with any operation const passport = await getPassport({ client, path: { id: "passport-uuid" } }); // Create a new passport const created = await createPassport({ client, body: { productId: "00012345678905", metadata: { productName: "Test Product" } } }); // Or configure globally (applies to all subsequent operations) client.setConfig({ baseUrl: "https://custom.opendpp-node.eu", auth: () => "your-api-key" }); ``` -------------------------------- ### Update OpenDPP Client Configuration at Runtime Source: https://github.com/opendpp/opendpp-sdk/blob/main/_autodocs/configuration.md Shows how to update the configuration of an existing OpenDPP client using the `setConfig` method. Supports changing baseUrl and authentication details. ```typescript const client = createOpenDppClient(); // Later, update configuration client.setConfig({ baseUrl: "https://custom.opendpp-node.eu", auth: () => process.env.OPENDPP_API_KEY // Function form }); ``` -------------------------------- ### Serialize Battery Units Source: https://github.com/opendpp/opendpp-sdk/blob/main/_autodocs/README.md Example of serializing battery units for a passport. This involves providing a list of units with their details. ```typescript const result = await serializeBatteryUnits({ client, path: { passportId: "passport-uuid" }, body: { units: [ { serialNumber: "SN20250001", status: "IN_SERVICE", manufacturedAt: "2025-01-15" }, { serialNumber: "SN20250002", status: "IN_SERVICE", manufacturedAt: "2025-01-15" } ] } }); console.log(`Created ${result.created}, skipped ${result.errors.length}`); ``` -------------------------------- ### Configure and Use Default OpenDPP Client Globally Source: https://github.com/opendpp/opendpp-sdk/blob/main/_autodocs/api-reference/client.md Configure the pre-exported default client instance once with base URL and API key. This configuration is then implicitly used by all subsequent SDK operations. ```typescript import { client, getHealth } from "@opendpp/sdk"; // Configure once client.setConfig({ baseUrl: "https://opendpp-node.eu", auth: () => process.env.OPENDPP_API_KEY }); // Use it implicitly in all operations const health = await getHealth(); ``` -------------------------------- ### GET /api/v1/version Source: https://github.com/opendpp/opendpp-sdk/blob/main/_autodocs/endpoints.md Retrieves the current API version information. This endpoint is part of the versioning strategy to inform clients about the contract. ```APIDOC ## GET /api/v1/version ### Description Retrieves the current API version information. This endpoint is part of the versioning strategy to inform clients about the contract. ### Method GET ### Endpoint /api/v1/version ### Response #### Success Response (200) - **version** (string) - The current API version string. ``` -------------------------------- ### GET /tenants/{tenantId}/status/revocation Source: https://github.com/opendpp/opendpp-sdk/blob/main/_autodocs/endpoints.md Fetches the revocation status list for a specific tenant. This endpoint is publicly accessible and rate-limited. ```APIDOC ## GET /tenants/{tenantId}/status/revocation ### Description Get tenant revocation status list. ### Method GET ### Endpoint /tenants/{tenantId}/status/revocation ### Parameters #### Path Parameters - **tenantId** (UUID) - Required - The ID of the tenant to retrieve the revocation status for. ### Response #### Success Response - **Revocation status list** - A list detailing the revocation status of items associated with the tenant. ``` -------------------------------- ### POST /api/v1/facilities Source: https://github.com/opendpp/opendpp-sdk/blob/main/_autodocs/endpoints.md Creates a new facility. This endpoint requires authentication and specific permissions. ```APIDOC ## POST /api/v1/facilities ### Description Create a new facility. ### Method POST ### Endpoint /api/v1/facilities ### Request Body - FacilityCreateRequest (object) - Required ### Response #### Success Response (201) - CreateFacilityResponses (object) **SDK Function:** `createFacility(options)` ``` -------------------------------- ### Get OpenDPP JSON-LD Context Source: https://github.com/opendpp/opendpp-sdk/blob/main/_autodocs/api-reference/gs1-resolution-utilities.md Retrieves the JSON-LD context for the OpenDPP vocabulary. This is a public endpoint used by JSON-LD processors. ```typescript const context = await getDppJsonLdContext(); console.log(context["@context"]); ``` -------------------------------- ### Get a Specific Economic Operator Source: https://github.com/opendpp/opendpp-sdk/blob/main/_autodocs/api-reference/operators-facilities-grants.md Retrieve a single economic operator by its unique ID. Ensure you have the `operator:read` permission. ```typescript const operator = await getOperator({ client, path: { id: "operator-uuid" } }); console.log(`${operator.name} (${operator.address.country})`); ``` -------------------------------- ### createOpenDppClient Source: https://github.com/opendpp/opendpp-sdk/blob/main/_autodocs/api-reference/client.md Creates and returns a configured OpenDPP API client. This client can be used for API operations or configured globally. ```APIDOC ## createOpenDppClient ### Description Creates and returns a configured OpenDPP API client. The returned client can be passed to any operation via its `client` option, or configured globally via `client.setConfig()`. ### Signature ```typescript function createOpenDppClient(options?: OpenDppClientOptions): Client ``` ### Parameters #### Options: OpenDppClientOptions - **baseUrl** (`string`) - Optional - Default: `https://opendpp-node.eu` - Base URL of the OpenDPP node. Supports custom domains or workspace subdomains (e.g., `https://{workspace}.opendpp-node.eu`). - **apiKey** (`string`) - Optional - Base64 encoded API key. When provided, it is automatically sent as `Authorization: Bearer ` on operations that declare a security requirement. Public operations work without it. ### Return Value Returns a `Client` instance that can be passed to any SDK operation. The client maintains configuration state and can be reconfigured at any time via `client.setConfig()`. ### Example ```typescript import { createOpenDppClient, getPassport, createPassport } from "@opendpp/sdk"; // Create a client with API key const client = createOpenDppClient({ apiKey: process.env.OPENDPP_API_KEY }); // Use it with any operation const passport = await getPassport({ client, path: { id: "passport-uuid" } }); // Create a new passport const created = await createPassport({ client, body: { productId: "00012345678905", metadata: { productName: "Test Product" } } }); // Or configure globally (applies to all subsequent operations) client.setConfig({ baseUrl: "https://custom.opendpp-node.eu", auth: () => "your-api-key" }); ``` ``` -------------------------------- ### Configure Default Client Globally Source: https://github.com/opendpp/opendpp-sdk/blob/main/_autodocs/configuration.md Configure the default client once globally to be used across all operations. Ensure the `baseUrl` and `auth` function are correctly set. ```typescript import { client, whoami } from "@opendpp/sdk"; // Configure once globally client.setConfig({ baseUrl: "https://opendpp-node.eu", auth: () => process.env.OPENDPP_API_KEY }); // Use in all operations without passing client explicitly const identity = await whoami(); // Uses configured default ``` -------------------------------- ### GET /api/v1/schemas/{category} Source: https://github.com/opendpp/opendpp-sdk/blob/main/_autodocs/endpoints.md Retrieves the JSON Schema for a specified ESPR category. Useful for data validation and understanding data structures. ```APIDOC ## GET /api/v1/schemas/{category} ### Description Get JSON Schema for an ESPR category. ### Method GET ### Endpoint /api/v1/schemas/{category} ### Parameters #### Path Parameters - **category** (string) - Required - The ESPR category for which to retrieve the schema (e.g., "light_sources"). ### Response #### Success Response - **JSON Schema document** - The JSON Schema for the specified category. ### SDK Function `getSectorSchema(options)` ``` -------------------------------- ### Per-Operation Configuration Options Source: https://github.com/opendpp/opendpp-sdk/blob/main/_autodocs/configuration.md Configure individual operations by passing a client explicitly, using the default configured client, or overriding headers for a single operation. This allows for fine-grained control. ```typescript import { createPassport } from "@opendpp/sdk"; // Option 1: Pass client explicitly const result = await createPassport({ client: myCustomClient, body: { /* ... */ } }); // Option 2: Use default (if configured globally) const result = await createPassport({ body: { /* ... */ } }); // Option 3: Override headers for a single operation const result = await createPassport({ client: myClient, body: { /* ... */ }, headers: { "X-Custom-Header": "value" } }); ``` -------------------------------- ### Get Facility by ID Source: https://github.com/opendpp/opendpp-sdk/blob/main/_autodocs/api-reference/operators-facilities-grants.md Retrieves a single facility by its unique identifier (UUID). Use this when you need detailed information about a specific facility. ```typescript const facility = await getFacility({ client, path: { id: "facility-uuid" } }); console.log(`${facility.name} - GLN: ${facility.gln}`); ``` -------------------------------- ### OpenDppClient Source: https://github.com/opendpp/opendpp-sdk/blob/main/_autodocs/INDEX.md Functions for creating and configuring the OpenDppClient, which serves as the primary interface for interacting with the OpenDPP API. ```APIDOC ## createOpenDppClient() ### Description Initializes and returns a new instance of the OpenDppClient. ### Function Signature `createOpenDppClient(options?: OpenDppClientOptions): OpenDppClient` ### Parameters #### Options (`OpenDppClientOptions`) - **apiKey** (string) - Required - The API key for authentication. - **baseUrl** (string) - Optional - The base URL for the OpenDPP API. Defaults to the production URL. - **timeout** (number) - Optional - The request timeout in milliseconds. Defaults to 30000. ### Return Value An instance of `OpenDppClient` configured with the provided options. ### Usage Example ```javascript import { createOpenDppClient } from '@opendpp/sdk'; const client = createOpenDppClient({ apiKey: 'YOUR_API_KEY', baseUrl: 'https://api.opendpp.com' }); // Use the client to interact with the API ``` ``` -------------------------------- ### createFacility Source: https://github.com/opendpp/opendpp-sdk/blob/main/_autodocs/api-reference/operators-facilities-grants.md Creates a new Facility (production location) within an Economic Operator. Facilities are identified by GLN and used to anchor passport metadata. ```APIDOC ## createFacility ### Description Creates a new Facility (production location) within an Economic Operator. Facilities are identified by GLN (Global Location Number) and used to anchor passport metadata. ### Method POST ### Endpoint /facilities ### Parameters #### Path Parameters (No path parameters specified in the source) #### Query Parameters (No query parameters specified in the source) #### Request Body - **operatorId** (string) - Required - UUID of the operator owning this facility - **name** (string) - Required - Facility name - **gln** (string) - Required - Global Location Number (GLN), unique per operator - **address** (object) - Required - Facility address (street, city, country, postal code) ### Request Example ```typescript const facility = await createFacility({ client, body: { operatorId: "operator-uuid", name: "Berlin Production Plant", gln: "4012345000007", address: { street: "123 Industrial Way", city: "Berlin", country: "DE", postalCode: "10115" } } }); console.log(`Facility created: ${facility.id}`); ``` ### Response #### Success Response (201 Created) { id: string; // UUID operatorId: string; name: string; gln: string; address: object; // ... } ### Errors - **400** Bad Request: Missing required fields or invalid GLN format - **403** Unauthorized: No permission `facility:write` - **404** Not Found: Operator does not exist - **409** Conflict: GLN already exists for this operator ``` -------------------------------- ### Create Webhook Subscription Source: https://github.com/opendpp/opendpp-sdk/blob/main/_autodocs/endpoints.md Allows users to create a new webhook subscription. Requires authentication and the `webhook:write` permission. ```APIDOC ## POST /api/v1/webhooks ### Description Create a webhook subscription. ### Method POST ### Endpoint /api/v1/webhooks ### Request Body WebhookSubscriptionCreateRequest ### Response #### Success Response (201) CreateWebhookSubscriptionResponses ``` -------------------------------- ### Handle API Rate Limits Source: https://github.com/opendpp/opendpp-sdk/blob/main/_autodocs/configuration.md Demonstrates how to catch rate limit errors (429) and check remaining quota using SDK headers and response objects. ```typescript const result = await whoami({ client }).catch(err => { if (err.status === 429) { const retryAfter = err.headers["retry-after"]; // Seconds console.log(`Rate limited, retry after ${retryAfter}s`); } }); // Check remaining quota const identity = await whoami({ client }); const remaining = identity.usage.passportLimit - identity.usage.activePassports; console.log(`Quota remaining: ${remaining}`); ``` -------------------------------- ### Get API Health Status Source: https://github.com/opendpp/opendpp-sdk/blob/main/_autodocs/api-reference/gs1-resolution-utilities.md Retrieves the operational status of the API. No authentication is required. Use this to check if the API is online and ready to serve requests. ```typescript const health = await getHealth(); console.log(`API Status: ${health.status}`); ``` -------------------------------- ### Get Sector Schema Source: https://github.com/opendpp/opendpp-sdk/blob/main/_autodocs/api-reference/gs1-resolution-utilities.md Retrieves the JSON Schema for a specific ESPR category, used for validating metadata before submission. Ensure the 'category' parameter is correctly specified. ```typescript const schema = await getSectorSchema({ path: { category: "light_sources" } }); // Use with a JSON schema validator console.log(JSON.stringify(schema, null, 2)); ``` -------------------------------- ### OpenDPP Client Options Interface Source: https://github.com/opendpp/opendpp-sdk/blob/main/_autodocs/configuration.md Defines the configuration options available when creating an OpenDPP client. Options include baseUrl and apiKey. ```typescript interface OpenDppClientOptions { baseUrl?: string; apiKey?: string; } ``` -------------------------------- ### Create a New Passport Source: https://github.com/opendpp/opendpp-sdk/blob/main/_autodocs/INDEX.md Create a new passport for a product, including its ID and metadata. Check the result for errors and log the created passport ID. ```typescript const result = await createPassport({ client, body: { productId: "00012345678905", metadata: { category: "light_sources", productName: "LED Bulb" } } }); if (!result.error) { console.log(`Created: ${result.id}`); } ``` -------------------------------- ### Get API Version Information Source: https://github.com/opendpp/opendpp-sdk/blob/main/_autodocs/api-reference/gs1-resolution-utilities.md Retrieves the API server version and the OpenAPI contract version. This endpoint is public and does not require authentication. Useful for compatibility checks. ```typescript const version = await getApiVersion(); console.log(`API: ${version.version}`); console.log(`OpenAPI: ${version.openapi}`); ``` -------------------------------- ### Unauthorized Response Body - Missing Permission Source: https://github.com/opendpp/opendpp-sdk/blob/main/_autodocs/errors.md Example of a response body indicating a missing permission error. This occurs when a credential lacks the required permission for an operation. ```json { success: false; error: "Unauthorized"; message: "You do not have permission 'passport:create'."; } ```