FunctionScript

FunctionScript

JavaScript函数到强类型HTTP API的转换规范

FunctionScript是一种语言和规范,用于将JavaScript函数转换为强类型HTTP API。开发者只需在注释块中定义HTTP接口,即可将Node.js函数轻松导出为API。这一规范既适合初学者入门API开发,又能满足专业开发需求。作为Autocode平台的核心规范,FunctionScript为开发者提供了快速构建高质量API的工具。

FunctionScriptAPI开发JavaScript函数类型检查HTTP接口Github开源项目

FunctionScript

FunctionScript Logo

travis-ci build npm version

An API gateway and framework for turning functions into web services

FunctionScript is a language and specification for turning JavaScript functions into typed HTTP APIs. It allows JavaScript (Node.js) functions to be seamlessly exported as HTTP APIs by defining what the HTTP interface will look like and how it behaves in the preceding comment block - including type-safety mechanisms.

FunctionScript arose out of a need to introduce developers with little programming experience, but familiarity with JavaScript, to full-stack API development and best practices around defining and connecting HTTP application interfaces. For this reason, the goals of the language are significantly different than TypeScript. FunctionScript is intended to provide an easy introduction to API development for those of any skill level, while maintaining professional power and flexibility.

FunctionScript is the primary specification underpinning the Autocode platform and its standard library of APIs.

Quick Example of a FunctionScript API

The following is a real-world excerpt of an API that can be used to query a Spreadsheet like a Database. The underlying implementation has been hidden, but the parameters for the API can be seen.

/** * Select Rows from a Spreadsheet by querying it like a Database * @param {string} spreadsheetId The id of the Spreadsheet. * @param {string} range The A1 notation of the values to use as a table. * @param {enum} bounds Specify the ending bounds of the table. * ["FIRST_EMPTY_ROW", "FIRST_EMPTY_ROW"] * ["FULL_RANGE", "FULL_RANGE"] * @param {object} where A list of column values to filter by. * @param {object} limit A limit representing the number of results to return * @ {number} offset The offset of records to begin at * @ {number} count The number of records to return, 0 will return all * @returns {object} selectQueryResult * @ {string} spreadsheetId * @ {string} range * @ {array} rows An array of objects corresponding to row values */ module.exports = async ( spreadsheetId = null, range, bounds = 'FIRST_EMPTY_ROW', where = {}, limit = {offset: 0, count: 0}, context ) => { /* implementation-specific JavaScript */ return {/* some data */}; };

It generates an API which accepts (and type checks against, following schemas):

  • spreadsheetId A string
  • range A string
  • bounds An enum, can be either "FIRST_EMPTY_ROW" or "FULL_RANGE"
  • where An object
  • limit An object that must contain:
    • limit.offset, a number
    • limit.count, a number

It will return an object:

  • selectQueryResult
    • selectQueryResult.spreadsheetId must be a string
    • selectQueryResult.range must be a string
    • selectQueryResult.rows must be an array

Background

The impetus for creating FunctionScript is simple: it stems from the initial vision of Autocode. We believe the modern web is missing a base primitive - the API. Daily, computer systems and developers around the planet make trillions of requests to perform specific tasks: process credit card payments with Stripe, send team messages via Slack, create SMS messages with Twilio. These requests are made primarily over HTTP: Hypertext Transfer Protocol. However, little to no "hypertext" is actually sent or received, these use cases have emerged in an ad hoc fashion as a testament to the power of the world wide web. Oftentimes, API standardization attempts have been presented as band-aids instead of solutions: requiring developers to jury rig a language, framework, markup language and hosting provider together just to get a simple "hello world" out the door.

By creating API development standards as part of a language specification instead of a framework, FunctionScript truly treats the web API as a base primitive of software development instead of an afterthought. This allows teams to be able to deliver high-quality APIs with the same fidelity as organizations like Stripe in a fraction of the time without requiring any additional tooling.

Table of Contents

  1. Introduction
  2. Why FunctionScript?
  3. FunctionScript Examples
    1. All Available Types
  4. Specification
    1. FunctionScript Resource Definition
    2. Context Definition
    3. Parameters
      1. Constraints
      2. Types
      3. Type Conversion
      4. Nullability
    4. FunctionScript Resource Requests
      1. Context
      2. Errors
        1. ClientError
        2. ParameterError
          1. Details: Required
          2. Details: Invalid
        3. FatalError
        4. RuntimeError
        5. ValueError
  5. FunctionScript Server and Gateway: Implementation
  6. Acknowledgements

Introduction

To put it simply, FunctionScript defines semantics and rules for turning exported JavaScript (Node.js) functions into strongly-typed, HTTP-accessible web APIs. In order to use FunctionScript, you'd set up your own FunctionScript Gateway or you would use an existing FunctionScript-compliant service like Autocode.

FunctionScript allows you to turn something like this...

// hello_world.js /** * My hello world function! */ module.exports = (name = 'world') => { return `hello ${name}`; };

Into a web API that can be called over HTTP like this (GET):

https://$user.api.stdlib.com/service@dev/hello_world?name=joe

Or like this (POST):

{ "name": "joe" }

And gives a result like this:

"hello joe"

Or, when a type mismatch occurs (like {"name":10}):

{ "error": { "type":"ParameterError" ... } }

Why FunctionScript?

FunctionScript is intended primarily to provide a scaffold to build and deliver APIs easily. It works best as a part of the Autocode platform which consumes the FunctionScript API definitions, hosts the code, generates documentation from the definitions, and automatically handles versioning and environment management. The reason we've open sourced the language specification is so that developers have an easier time developing against the highly modular API ecosystem we've created and can contribute their thoughts and requests.

You can break down the reason for the development of FunctionScript into a few key points:

  • Modern developers and people being introduced to software development for the first time are often trying to build web-native scripts. It is exceedingly difficult to go from "zero to API" in less than a few hours, writing code is just the first step of many. We'd like it to be the first and only step.

  • No true standards around APIs have ever been built or enforced in a rigorous manner across the industry. Primarily, opinions around SOAP, REST and GraphQL requests have been built into frameworks and tools instead of a language specification, which has artificially inflated the cognitive overhead required to ship functional web-based software.

  • Companies like Stripe and Twilio which have built and enforced their own API development paradigms internally have unlocked massive developer audiences in short timeframes, indicating the power of treating web APIs as a first-class citizen of development.

  • Serverless computing, specifically the Function-as-a-Service model of web-based computation, has made API development significantly more accessible but has not brought us over the "last-mile" hump.

  • JavaScript, specifically Node.js, is an ideal target for API development standardization due to its accessibility (front-end and back-end), growth trajectory, and flexibility. Most new developers are introduced to JavaScript out of necessity.

  • As opposed to something like TypeScript, FunctionScript helps newer entrants to software development by extending JavaScript with very little overhead. It adds types around only the HTTP interface, leaving the majority of the language footprint untouched but strengthening the "weakest" and least predictable link in the development chain: user input.

With FunctionScript, it's our goal to develop a language specification for building APIs that automatically provides a number of necessary features without additional tooling:

  • Standardized API Calling Conventions (HTTP)
  • Type-Safety Mechanisms at the HTTP -> Code Interface
  • Automatically Generated API Documentation

FunctionScript Examples

We'll be updating this section with examples for you to play with and modify on your own.

All Available Types

Here's an example of a hypothetical createUser.js function that can be used to create a user resource. It includes all available type definitions.

/** * @param {integer} id ID of the User * @param {string} username Name of the user * @param {number} age Age of the user * @param {float} communityScore Community score (between 0.00 and 100.00) * @param {object} metadata Key-value pairs corresponding to additional user data * @ {string} createdAt Created at ISO-8601 String. Required as part of metadata. * @ {?string} notes Additional notes. Nullable (not required) as part of object * @param {array} friendIds List of friend ids * @ {integer} friendId ID of a user (forces array to have all integer entries) * @param {buffer} profilePhoto Base64-encoded filedata, read into Node as a Buffer * @param {enum} userGroup The user group. Can be "USER" (read as 0) or "ADMIN" (read as 9) * ["USER", 0] * ["ADMIN", 9] * @param {boolean} overwrite Overwrite current user data, if username matching * @returns {object.http} successPage API Returns an HTTP object (webpage) */ module.exports = async (id = null, username, age, communityScore, metadata, friendsIds = [], profilePhoto, userGroup, overwrite = false) => { // NOTE: id, friendIds and overwrite will be OPTIONAL as they have each been // provided a defaultValue // Implementation-specific code here // API Output // NOTE: Note that because "object.http" was specified, this MUST follow the // object.http schema: headers, statusCode, body return { headers: {'Content-Type': 'text/html'}, statusCode: 200, body: Buffer.from('Here is a success message!') }; };

Specification

FunctionScript Resource Definition

A FunctionScript definition is a JSON output, traditionally saved as a definition.json file, generated from a JavaScript file, that respects the following format.

Given a function like this (filename my_function.js):

// my_function.js /** * This is my function, it likes the greek alphabet * @param {String} alpha Some letters, I guess * @param {Number} beta And a number * @param {Boolean} gamma True or false? * @returns {Object} some value */ module.exports = async (alpha, beta = 2, gamma, context) => { /* your code */ };

The FunctionScript parser will generate a definition.json file that looks like the following:

{ "name": "my_function", "format": { "language": "nodejs", "async": true }, "description": "This is my function, it likes the greek alphabet", "bg": { "mode": "info", "value": "" }, "context": null, "params": [ { "name": "alpha", "type": "string", "description": "Some letters, I guess" }, { "name": "beta", "type": "number", "defaultValue": 2, "description": "And a number" }, { "name": "gamma", "type": "boolean", "description": "True or false?" } ], "returns": { "type": "object", "description": "some value" } }

A definition must implement the following fields;

FieldDefinition
nameA user-readable function name (used to execute the function), must match /[A-Z][A-Z0-9_]*/i
formatAn object requiring a language field, along with any implementation details
descriptionA brief description of what the function does, can be empty ("")
bgAn object containing "mode" and "value" parameters specifying the behavior of function responses when executed in the background
paramsAn array of NamedParameters, representing function arguments
returnsA Parameter without a defaultValue representing function return value

Context Definition

If the function does not access execution context details, this should always be null. If it is an object, it indicates that the function does access context details (i.e. remoteAddress, http headers, etc. - see Context).

This object does not have to be empty, it can contain vendor-specific details; for example "context": {"user": ["id", "email"]} may indicate that the execution context specifically accesses authenticated user id and email addresses.

Parameters

Parameters have the following format;

FieldRequiredDefinition
nameNamedParameter OnlyThe name of the Parameter, must match /[A-Z][A-Z0-9_]*/i
typeyesA string representing a valid FunctionScript type
descriptionyesA short description of the parameter, can be empty string ("")
defaultValuenoMust match the specified type. If type is not provided, this parameter is required

Types

As FunctionScript interfaces with "userland" (user input), a strongly typed signature is enforced for all inbound parameters. The following is a list of supported FunctionScript types.

TypeDefinitionExample Input Values (JSON)
booleanTrue or Falsetrue or false
stringBasic text or character strings"hello", "GOODBYE!"
numberAny double-precision Floating Point value2e+100, 1.02, -5
floatAlias for number2e+100, 1.02, -5
integerSubset of number, integers between -2^53 + 1 and +2^53 - 1 (inclusive)0, -5, 2000
objectAny JSON-serializable Object{}, {"a":true}, {"hello":["world"]}
object.httpAn object representing an HTTP Response. Accepts headers, body and statusCode keys{"body": "Hello World"}, {"statusCode": 404, "body": "not found"}, {"headers": {"Content-Type": "image/png"}, "body": Buffer.from(...)}
arrayAny JSON-serializable Array[], [1, 2, 3], [{"a":true}, null, 5]
bufferRaw binary octet (byte) data representing a file{"_bytes": [8, 255]} or {"_base64": "d2h5IGRpZCB5b3UgcGFyc2UgdGhpcz8/"}
anyAny value mentioned above5, "hello", []
enumAn enumeration that maps input strings to values of your choosing"STRING_OF_YOUR_CHOICE"

Type Conversion

The buffer type will automatically be converted from any object with a single key-value pair matching the footprints {"_bytes": []} or {"_base64": ""}.

Otherwise, parameters provided to a function are expected to match their defined types. Requests made over HTTP via query parameters or POST data with type application/x-www-form-urlencoded will be automatically converted from strings to their respective expected types, when possible (see FunctionScript Resource Requests below):

TypeConversion Rule
boolean"t" and "true" become true, "f" and "false" become false, otherwise do not convert
stringNo conversion
numberDetermine float value, if NaN do not convert, otherwise convert
floatDetermine float value, if NaN do not convert, otherwise convert
integerDetermine float value, if NaN do not convert, may fail integer type check if not in range
objectParse as JSON, if invalid do not convert, object may

编辑推荐精选

蛙蛙写作

蛙蛙写作

AI小说写作助手,一站式润色、改写、扩写

蛙蛙写作—国内先进的AI写作平台,涵盖小说、学术、社交媒体等多场景。提供续写、改写、润色等功能,助力创作者高效优化写作流程。界面简洁,功能全面,适合各类写作者提升内容品质和工作效率。

AI辅助写作AI工具蛙蛙写作AI写作工具学术助手办公助手营销助手AI助手
Trae

Trae

字节跳动发布的AI编程神器IDE

Trae是一种自适应的集成开发环境(IDE),通过自动化和多元协作改变开发流程。利用Trae,团队能够更快速、精确地编写和部署代码,从而提高编程效率和项目交付速度。Trae具备上下文感知和代码自动完成功能,是提升开发效率的理想工具。

AI工具TraeAI IDE协作生产力转型热门
问小白

问小白

全能AI智能助手,随时解答生活与工作的多样问题

问小白,由元石科技研发的AI智能助手,快速准确地解答各种生活和工作问题,包括但不限于搜索、规划和社交互动,帮助用户在日常生活中提高效率,轻松管理个人事务。

热门AI助手AI对话AI工具聊天机器人
Transly

Transly

实时语音翻译/同声传译工具

Transly是一个多场景的AI大语言模型驱动的同声传译、专业翻译助手,它拥有超精准的音频识别翻译能力,几乎零延迟的使用体验和支持多国语言可以让你带它走遍全球,无论你是留学生、商务人士、韩剧美剧爱好者,还是出国游玩、多国会议、跨国追星等等,都可以满足你所有需要同传的场景需求,线上线下通用,扫除语言障碍,让全世界的语言交流不再有国界。

讯飞智文

讯飞智文

一键生成PPT和Word,让学习生活更轻松

讯飞智文是一个利用 AI 技术的项目,能够帮助用户生成 PPT 以及各类文档。无论是商业领域的市场分析报告、年度目标制定,还是学生群体的职业生涯规划、实习避坑指南,亦或是活动策划、旅游攻略等内容,它都能提供支持,帮助用户精准表达,轻松呈现各种信息。

AI办公办公工具AI工具讯飞智文AI在线生成PPTAI撰写助手多语种文档生成AI自动配图热门
讯飞星火

讯飞星火

深度推理能力全新升级,全面对标OpenAI o1

科大讯飞的星火大模型,支持语言理解、知识问答和文本创作等多功能,适用于多种文件和业务场景,提升办公和日常生活的效率。讯飞星火是一个提供丰富智能服务的平台,涵盖科技资讯、图像创作、写作辅助、编程解答、科研文献解读等功能,能为不同需求的用户提供便捷高效的帮助,助力用户轻松获取信息、解决问题,满足多样化使用场景。

热门AI开发模型训练AI工具讯飞星火大模型智能问答内容创作多语种支持智慧生活
Spark-TTS

Spark-TTS

一种基于大语言模型的高效单流解耦语音令牌文本到语音合成模型

Spark-TTS 是一个基于 PyTorch 的开源文本到语音合成项目,由多个知名机构联合参与。该项目提供了高效的 LLM(大语言模型)驱动的语音合成方案,支持语音克隆和语音创建功能,可通过命令行界面(CLI)和 Web UI 两种方式使用。用户可以根据需求调整语音的性别、音高、速度等参数,生成高质量的语音。该项目适用于多种场景,如有声读物制作、智能语音助手开发等。

咔片PPT

咔片PPT

AI助力,做PPT更简单!

咔片是一款轻量化在线演示设计工具,借助 AI 技术,实现从内容生成到智能设计的一站式 PPT 制作服务。支持多种文档格式导入生成 PPT,提供海量模板、智能美化、素材替换等功能,适用于销售、教师、学生等各类人群,能高效制作出高品质 PPT,满足不同场景演示需求。

讯飞绘文

讯飞绘文

选题、配图、成文,一站式创作,让内容运营更高效

讯飞绘文,一个AI集成平台,支持写作、选题、配图、排版和发布。高效生成适用于各类媒体的定制内容,加速品牌传播,提升内容营销效果。

热门AI辅助写作AI工具讯飞绘文内容运营AI创作个性化文章多平台分发AI助手
材料星

材料星

专业的AI公文写作平台,公文写作神器

AI 材料星,专业的 AI 公文写作辅助平台,为体制内工作人员提供高效的公文写作解决方案。拥有海量公文文库、9 大核心 AI 功能,支持 30 + 文稿类型生成,助力快速完成领导讲话、工作总结、述职报告等材料,提升办公效率,是体制打工人的得力写作神器。

下拉加载更多