Functions API Reference
Overview
The Functions API allows you to create, manage, and invoke JavaScript functions in a secure Trusted Execution Environment (TEE). This API enables serverless function execution with integration to the Neo N3 blockchain.
Base URL
https://api.neo-service-layer.io/v1/functions
Authentication
All API requests require authentication using an API key. Include your API key in theX-API-Key
header with each request:
curl -X GET "https://api.neo-service-layer.io/v1/functions" \ -H "X-API-Key: your-api-key-here"
Endpoints
Functions Management
Method | Endpoint | Description |
---|---|---|
GET | /functions | List all functions |
POST | /functions | Create a new function |
GET | /functions/{functionId} | Get a specific function |
PUT | /functions/{functionId} | Update a function |
DELETE | /functions/{functionId} | Delete a function |
Function Execution
Method | Endpoint | Description |
---|---|---|
POST | /functions/{functionId}/invoke | Invoke a function |
GET | /functions/{functionId}/executions | List function executions |
GET | /functions/{functionId}/executions/{executionId} | Get execution details |
Function Secrets & Environment
Method | Endpoint | Description |
---|---|---|
GET | /functions/{functionId}/environment | Get function environment variables |
PUT | /functions/{functionId}/environment | Update environment variables |
PUT | /functions/{functionId}/secrets | Update function secrets access |
Request and Response Formats
All API requests and responses use JSON format. Specific formats for each endpoint are detailed below.
List Functions
Retrieves a list of functions in your account. The results can be filtered and paginated.
Endpoint: GET /functions
Query Parameters
Parameter | Type | Required | Description |
---|---|---|---|
limit | Integer | No | Maximum number of functions to return (default: 10, max: 100) |
offset | Integer | No | Number of functions to skip (default: 0) |
tag | String | No | Filter functions by tag |
runtime | String | No | Filter functions by runtime (e.g., node16) |
sort | String | No | Sort by field (createdAt, name, updatedAt) |
order | String | No | Sort order (asc, desc) |
Response
{ "success": true, "data": [ { "id": "func_1234567890", "name": "hello-world", "description": "A simple hello world function", "runtime": "node16", "status": "active", "createdAt": "2023-07-01T12:34:56Z", "updatedAt": "2023-07-01T12:34:56Z", "tags": ["example", "demo"], "lastInvocation": "2023-07-02T10:21:45Z" }, { "id": "func_0987654321", "name": "token-price-checker", "description": "Checks token prices", "runtime": "node16", "status": "active", "createdAt": "2023-06-30T14:22:33Z", "updatedAt": "2023-06-30T14:22:33Z", "tags": ["price", "token"], "lastInvocation": "2023-07-01T09:11:22Z" } ], "pagination": { "total": 12, "limit": 10, "offset": 0, "hasMore": true } }
Code Example
// JavaScript example using Fetch API fetch('https://api.neo-service-layer.io/v1/functions?limit=10&offset=0&sort=createdAt&order=desc', { method: 'GET', headers: { 'Content-Type': 'application/json', 'X-API-Key': 'your-api-key-here' } }) .then(response => response.json()) .then(data => console.log(data)) .catch(error => console.error('Error:', error)); // Using the SDK const { NeoServiceLayer } = require('neo-service-layer-sdk'); const serviceLayer = new NeoServiceLayer({ apiKey: 'your-api-key-here' }); async function listFunctions() { const functions = await serviceLayer.functions.list({ limit: 10, offset: 0, sort: 'createdAt', order: 'desc' }); console.log(functions); } listFunctions().catch(console.error);
Create a Function
Creates a new function with the specified code and configuration.
Endpoint: POST /functions
Request Body
Parameter | Type | Required | Description |
---|---|---|---|
name | String | Yes | Function name (alphanumeric with hyphens, max 64 chars) |
code | String | Yes | JavaScript code for the function |
runtime | String | Yes | Runtime environment (node16, node18) |
description | String | No | Function description |
timeout | Integer | No | Maximum execution time in seconds (default: 30, max: 300) |
environment | Object | No | Environment variables as key-value pairs |
secrets | Array | No | Array of secret names to make available to the function |
tags | Array | No | Array of tags for organizing functions |
Response
{ "success": true, "data": { "id": "func_1234567890", "name": "hello-world", "description": "A simple hello world function", "runtime": "node16", "timeout": 30, "code": "module.exports = async function(context) { ... }", "status": "active", "createdAt": "2023-07-01T12:34:56Z", "updatedAt": "2023-07-01T12:34:56Z", "tags": ["example", "demo"], "environment": { "LOG_LEVEL": "info" }, "secrets": ["api-key-1"] } }
Code Example
// JavaScript example using Fetch API const functionCode = ` module.exports = async function(context) { const { params } = context; return { message: `Hello, ${params.name || 'World'}!`, timestamp: new Date().toISOString() }; }; `; fetch('https://api.neo-service-layer.io/v1/functions', { method: 'POST', headers: { 'Content-Type': 'application/json', 'X-API-Key': 'your-api-key-here' }, body: JSON.stringify({ name: 'hello-world', code: functionCode, runtime: 'node16', description: 'A simple hello world function', environment: { LOG_LEVEL: 'info' }, secrets: ['api-key-1'], tags: ['example', 'demo'] }) }) .then(response => response.json()) .then(data => console.log(data)) .catch(error => console.error('Error:', error)); // Using the SDK const { NeoServiceLayer } = require('neo-service-layer-sdk'); const serviceLayer = new NeoServiceLayer({ apiKey: 'your-api-key-here' }); async function createFunction() { const functionCode = ` module.exports = async function(context) { const { params } = context; return { message: `Hello, ${params.name || 'World'}!`, timestamp: new Date().toISOString() }; }; `; const result = await serviceLayer.functions.create({ name: 'hello-world', code: functionCode, runtime: 'node16', description: 'A simple hello world function', environment: { LOG_LEVEL: 'info' }, secrets: ['api-key-1'], tags: ['example', 'demo'] }); console.log(result); } createFunction().catch(console.error);
Get a Function
Retrieves details of a specific function by its ID.
Endpoint: GET /functions/{functionId}
Path Parameters
Parameter | Type | Required | Description |
---|---|---|---|
functionId | String | Yes | Unique identifier of the function |
Query Parameters
Parameter | Type | Required | Description |
---|---|---|---|
include_code | Boolean | No | Include function code in the response (default: false) |
Response
{ "success": true, "data": { "id": "func_1234567890", "name": "hello-world", "description": "A simple hello world function", "runtime": "node16", "timeout": 30, "status": "active", "createdAt": "2023-07-01T12:34:56Z", "updatedAt": "2023-07-01T12:34:56Z", "tags": ["example", "demo"], "code": "module.exports = async function(context) { ... }", // Only included if include_code=true "environment": { "LOG_LEVEL": "info" }, "secrets": ["api-key-1"], "stats": { "invocations": { "total": 152, "success": 149, "failed": 3, "last24Hours": 23 }, "averageExecutionTime": 78, // milliseconds "lastInvocation": "2023-07-02T10:21:45Z" } } }
Code Example
// JavaScript example using Fetch API fetch('https://api.neo-service-layer.io/v1/functions/func_1234567890?include_code=true', { method: 'GET', headers: { 'Content-Type': 'application/json', 'X-API-Key': 'your-api-key-here' } }) .then(response => response.json()) .then(data => console.log(data)) .catch(error => console.error('Error:', error)); // Using the SDK const { NeoServiceLayer } = require('neo-service-layer-sdk'); const serviceLayer = new NeoServiceLayer({ apiKey: 'your-api-key-here' }); async function getFunction() { const functionDetails = await serviceLayer.functions.get('func_1234567890', { includeCode: true }); console.log(functionDetails); } getFunction().catch(console.error);
Invoke a Function
Executes a function with the provided parameters and returns the result.
Endpoint: POST /functions/{functionId}/invoke
Path Parameters
Parameter | Type | Required | Description |
---|---|---|---|
functionId | String | Yes | Unique identifier of the function |
Request Body
Parameter | Type | Required | Description |
---|---|---|---|
params | Object | No | Parameters to pass to the function |
async | Boolean | No | Execute asynchronously (default: false) |
Response (Synchronous Execution)
{ "success": true, "data": { "execution": { "id": "exec_abcdefghij", "status": "completed", "startedAt": "2023-07-01T12:34:56Z", "completedAt": "2023-07-01T12:34:57Z", "duration": 127 // milliseconds }, "result": { // Function result (any JSON serializable value) "message": "Hello, Neo!", "timestamp": "2023-07-01T12:34:57Z" } } }
Response (Asynchronous Execution)
{ "success": true, "data": { "execution": { "id": "exec_abcdefghij", "status": "running", "startedAt": "2023-07-01T12:34:56Z" } } }
Code Example
// JavaScript example using Fetch API fetch('https://api.neo-service-layer.io/v1/functions/func_1234567890/invoke', { method: 'POST', headers: { 'Content-Type': 'application/json', 'X-API-Key': 'your-api-key-here' }, body: JSON.stringify({ params: { name: 'Neo' }, async: false }) }) .then(response => response.json()) .then(data => console.log(data)) .catch(error => console.error('Error:', error)); // Using the SDK const { NeoServiceLayer } = require('neo-service-layer-sdk'); const serviceLayer = new NeoServiceLayer({ apiKey: 'your-api-key-here' }); async function invokeFunction() { const result = await serviceLayer.functions.invoke('func_1234567890', { name: 'Neo' }); console.log(result); } invokeFunction().catch(console.error);
List Function Executions
Retrieves the execution history for a specific function.
Endpoint: GET /functions/{functionId}/executions
Path Parameters
Parameter | Type | Required | Description |
---|---|---|---|
functionId | String | Yes | Unique identifier of the function |
Query Parameters
Parameter | Type | Required | Description |
---|---|---|---|
limit | Integer | No | Maximum number of executions to return (default: 10, max: 100) |
offset | Integer | No | Number of executions to skip (default: 0) |
status | String | No | Filter by status (completed, failed, running) |
start_date | String | No | Filter executions after this date (ISO 8601 format) |
end_date | String | No | Filter executions before this date (ISO 8601 format) |
Response
{ "success": true, "data": [ { "id": "exec_abcdefghij", "status": "completed", "startedAt": "2023-07-01T12:34:56Z", "completedAt": "2023-07-01T12:34:57Z", "duration": 127, "params": { "name": "Neo" }, "hasResult": true, "hasError": false }, { "id": "exec_klmnopqrst", "status": "failed", "startedAt": "2023-07-01T12:32:10Z", "completedAt": "2023-07-01T12:32:12Z", "duration": 2045, "params": { "name": 123 // Caused an error }, "hasResult": false, "hasError": true } ], "pagination": { "total": 32, "limit": 10, "offset": 0, "hasMore": true } }
Code Example
// JavaScript example using Fetch API fetch('https://api.neo-service-layer.io/v1/functions/func_1234567890/executions?limit=10&status=completed', { method: 'GET', headers: { 'Content-Type': 'application/json', 'X-API-Key': 'your-api-key-here' } }) .then(response => response.json()) .then(data => console.log(data)) .catch(error => console.error('Error:', error)); // Using the SDK const { NeoServiceLayer } = require('neo-service-layer-sdk'); const serviceLayer = new NeoServiceLayer({ apiKey: 'your-api-key-here' }); async function listExecutions() { const executions = await serviceLayer.functions.listExecutions('func_1234567890', { limit: 10, status: 'completed' }); console.log(executions); } listExecutions().catch(console.error);
Function Runtime Context
When your function is executed, it receives a context
object with the following properties:
Property | Type | Description |
---|---|---|
params | Object | Parameters passed to the function during invocation |
execution | Object | Information about the current execution (id, startedAt) |
environment | Object | Environment variables defined for the function |
secrets | Object | Secret values the function has access to |
services | Object | Service clients (blockchain, random, etc.) |
log | Object | Logging functions (log.info, log.error, etc.) |
Example Function Using Context
module.exports = async function(context) { const { params, environment, secrets, services, log } = context; // Log information about the execution log.info('Function executed with params:', params); // Access environment variables const logLevel = environment.LOG_LEVEL || 'info'; log.info('Current log level:', logLevel); // Use a secret const apiKey = secrets['external-api-key']; log.info('Using API key:', apiKey.substring(0, 3) + '...'); // Use Neo blockchain service const neoBalance = await services.blockchain.getBalance({ address: params.address, asset: services.blockchain.assets.NEO }); return { message: `Hello, ${params.name || 'World'}!`, neoBalance, timestamp: new Date().toISOString() }; };
Error Handling
The Functions API returns standard HTTP status codes along with detailed error information:
Status Code | Error Code | Description |
---|---|---|
400 | invalid_request | The request was malformed or contained invalid parameters |
400 | invalid_function_code | The function code is invalid or contains syntax errors |
401 | unauthorized | Authentication failed or API key was missing |
403 | forbidden | The API key doesn't have permission to perform the requested action |
404 | function_not_found | The requested function was not found |
404 | execution_not_found | The requested execution was not found |
429 | rate_limit_exceeded | The rate limit for API requests has been exceeded |
500 | execution_error | An error occurred during function execution |
500 | internal_error | An internal server error occurred |
Error Response Example
{ "success": false, "error": { "code": "execution_error", "message": "An error occurred during function execution", "details": { "name": "TypeError", "message": "Cannot read property 'toLowerCase' of undefined", "stack": "TypeError: Cannot read property 'toLowerCase' of undefined\n at module.exports (/function/index.js:5:23)\n at Runtime.handleMessage (/runtime/index.js:42:10)" } } }
SDK Reference
The Neo Service Layer SDK provides a convenient way to interact with the Functions API:
// JavaScript SDK example const { NeoServiceLayer } = require('neo-service-layer-sdk'); const serviceLayer = new NeoServiceLayer({ apiKey: 'your-api-key-here' }); // Access the Functions service const functionsService = serviceLayer.functions; // Available methods functionsService.list() // List all functions functionsService.create() // Create a new function functionsService.get() // Get a specific function functionsService.update() // Update a function functionsService.delete() // Delete a function functionsService.invoke() // Invoke a function functionsService.listExecutions() // List function executions functionsService.getExecution() // Get execution details
For more details about the SDK, see the JavaScript SDK documentation.