Version 1.0.0
GitHub
Get Support

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

MethodEndpointDescription
GET/functionsList all functions
POST/functionsCreate a new function
GET/functions/{functionId}Get a specific function
PUT/functions/{functionId}Update a function
DELETE/functions/{functionId}Delete a function

Function Execution

MethodEndpointDescription
POST/functions/{functionId}/invokeInvoke a function
GET/functions/{functionId}/executionsList function executions
GET/functions/{functionId}/executions/{executionId}Get execution details

Function Secrets & Environment

MethodEndpointDescription
GET/functions/{functionId}/environmentGet function environment variables
PUT/functions/{functionId}/environmentUpdate environment variables
PUT/functions/{functionId}/secretsUpdate 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

ParameterTypeRequiredDescription
limitIntegerNoMaximum number of functions to return (default: 10, max: 100)
offsetIntegerNoNumber of functions to skip (default: 0)
tagStringNoFilter functions by tag
runtimeStringNoFilter functions by runtime (e.g., node16)
sortStringNoSort by field (createdAt, name, updatedAt)
orderStringNoSort 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

ParameterTypeRequiredDescription
nameStringYesFunction name (alphanumeric with hyphens, max 64 chars)
codeStringYesJavaScript code for the function
runtimeStringYesRuntime environment (node16, node18)
descriptionStringNoFunction description
timeoutIntegerNoMaximum execution time in seconds (default: 30, max: 300)
environmentObjectNoEnvironment variables as key-value pairs
secretsArrayNoArray of secret names to make available to the function
tagsArrayNoArray 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

ParameterTypeRequiredDescription
functionIdStringYesUnique identifier of the function

Query Parameters

ParameterTypeRequiredDescription
include_codeBooleanNoInclude 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

ParameterTypeRequiredDescription
functionIdStringYesUnique identifier of the function

Request Body

ParameterTypeRequiredDescription
paramsObjectNoParameters to pass to the function
asyncBooleanNoExecute 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

ParameterTypeRequiredDescription
functionIdStringYesUnique identifier of the function

Query Parameters

ParameterTypeRequiredDescription
limitIntegerNoMaximum number of executions to return (default: 10, max: 100)
offsetIntegerNoNumber of executions to skip (default: 0)
statusStringNoFilter by status (completed, failed, running)
start_dateStringNoFilter executions after this date (ISO 8601 format)
end_dateStringNoFilter 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:

PropertyTypeDescription
paramsObjectParameters passed to the function during invocation
executionObjectInformation about the current execution (id, startedAt)
environmentObjectEnvironment variables defined for the function
secretsObjectSecret values the function has access to
servicesObjectService clients (blockchain, random, etc.)
logObjectLogging 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 CodeError CodeDescription
400invalid_requestThe request was malformed or contained invalid parameters
400invalid_function_codeThe function code is invalid or contains syntax errors
401unauthorizedAuthentication failed or API key was missing
403forbiddenThe API key doesn't have permission to perform the requested action
404function_not_foundThe requested function was not found
404execution_not_foundThe requested execution was not found
429rate_limit_exceededThe rate limit for API requests has been exceeded
500execution_errorAn error occurred during function execution
500internal_errorAn 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.

Was this page helpful?

Edit this page on GitHub