BoxLang 🚀 A New JVM Dynamic Language Learn More...

Boxlang RESTful Services Compatibility Module

v1.0.0-snapshot BoxLang Modules

BoxLang REST Compatibility Module

A comprehensive ColdFusion RESTful services compatibility module for BoxLang that provides compatibility for the CFML REST specification including routing, serialization, and OpenAPI documentation generation.

Overview

This module provides ColdFusion-compatible REST services for BoxLang web applications, supporting:

  • RESTful Service Discovery & Registration: Automatic discovery and registration of REST-enabled CFCs
  • Intelligent Routing: Path-based routing with support for path parameters, query strings, and HTTP method matching
  • Content Negotiation: Automatic serialization/deserialization based on Accept and Content-Type headers
  • OpenAPI Documentation: Auto-generated OpenAPI 3.0 documentation for all registered services
  • CF-Compatible BIFs: restInitApplication, restSetResponse, restDeleteApplication
  • Multiple HTTP Methods: GET, POST, PUT, PATCH, DELETE, HEAD, OPTIONS
  • Rich Annotations Support: All standard CF REST annotations including httpMethod, produces, consumes, restPath, restArgSource

Installation

box install bx-compat-rest

Quick Start

1. Create a REST-Enabled Component

// HelloService.bx
component rest="true" restPath="hello" {
    
    remote string function sayHello() httpMethod="GET" produces="application/json" {
        return "Hello, World!";
    }
    
    remote string function sayHelloTo(
        required string name restArgSource="Path"
    ) httpMethod="GET" restPath="{name}" produces="application/json" {
        return "Hello, #arguments.name#!";
    }
}

2. Register Your REST Application

In your Application.cfc:

component {
    this.name = "MyRESTApp";
    
    // Register REST application on startup
    function onApplicationStart() {
        restInitApplication(
            expandPath("./services"),  // Directory containing REST CFCs
            "api"                       // Service mapping name
        );
    }
}

3. Access Your REST Endpoints

GET  /bxrest/public/RestController.bx?method=processAPIRequest&requestPath=/api/hello
GET  /bxrest/public/RestController.bx?method=processAPIRequest&requestPath=/api/hello/John

Architecture

Core Components

RestRegistryService.bx

The central registry that:

  • Discovers REST-enabled CFCs in registered directories
  • Parses component and function metadata
  • Builds and maintains the routing table
  • Matches incoming requests to registered routes
  • Supports route priorities and path parameters

RestController.bx

The front controller that:

  • Processes all incoming REST API requests
  • Delegates to the registry for route matching
  • Generates OpenAPI documentation via the docs() method
  • Handles errors and custom responses

RestMetadataParser.bx

Parses ColdFusion REST annotations:

  • rest / restPath on components
  • httpMethod on functions
  • produces / consumes for content negotiation
  • restArgSource / restArgName for parameter binding
  • Subresource and subresource locator detection

RestRequestHandler.bx

Handles request processing:

  • Extracts parameters from path, query, form, headers, cookies, body
  • Content negotiation (Accept header processing)
  • Request body deserialization
  • Response serialization
  • Component instantiation and method invocation

RestSerializer.bx

Provides serialization/deserialization:

  • JSON serialization using native BoxLang
  • XML serialization following CF format specifications
  • Form data parsing
  • Support for complex types (query, struct, array, CFC)

Supported Annotations

Component Level

  • rest="true" : Marks component as REST-enabled
  • restPath="path" : Base path for all functions in the component

Function Level

  • httpMethod="GET|POST|PUT|DELETE|..." : HTTP method(s) the function handles
  • restPath="path" : Subpath for the function (supports {param} placeholders)
  • produces="mime/type" : Response content types (comma-separated)
  • consumes="mime/type" : Request content types (comma-separated)
  • returnFormat="json|xml|plain" : Default return format

Parameter Level

  • restArgSource="Path|Query|Form|Header|Cookie|Body" : Where to extract parameter value
  • restArgName="name" : Name of the parameter in the source
  • required="true|false" : Whether the parameter is required
  • default="value" : Default value if not provided

Built-in Functions (BIFs)

restInitApplication()

Registers a REST application directory.

restInitApplication(
    rootPath,      // Required: Directory containing REST CFCs
    serviceName,   // Optional: Service name/mapping
    options        // Optional: Struct with host, useHost, isDefault
)

Example:

restInitApplication(expandPath("./api"), "myapi", {
    "host": "api.example.com",
    "isDefault": true
});

restSetResponse()

Sets a custom HTTP response with status, content, and headers.

restSetResponse({
    "status": 201,
    "content": {"id": 123, "message": "Created"},
    "headers": {"Location": "/api/resource/123"}
});

restDeleteApplication()

Removes a registered REST application.

restDeleteApplication("myapi");

OpenAPI Documentation

Access auto-generated OpenAPI 3.0 documentation:

GET /bxrest/public/RestController.bx?method=docs

The documentation includes:

  • All registered services and routes
  • HTTP methods and paths
  • Request parameters and their types
  • Response schemas
  • Content types (produces/consumes)

Advanced Features

Path Parameters

remote function getUser(
    required numeric id restArgSource="Path"
) httpMethod="GET" restPath="users/{id}" {
    return getUserById(arguments.id);
}

Access as: /api/users/123

Custom HTTP Status Codes

remote function createUser(
    required string name restArgSource="Form"
) httpMethod="POST" {
    var newUser = saveUser(arguments.name);
    
    restSetResponse({
        "status": 201,
        "content": newUser,
        "headers": {"Location": "/api/users/" & newUser.id}
    });
    
    return newUser;
}

Content Negotiation

The module automatically handles content negotiation based on:

  • Accept header for responses
  • Content-Type header for requests

Supported formats:

  • application/json, text/json
  • application/xml, text/xml
  • application/x-www-form-urlencoded
  • multipart/form-data
  • text/plain

Error Handling

Throw CF-compatible errors:

remote function getUser(required numeric id restArgSource="Path") {
    if (!userExists(id)) {
        throw(
            type="REST.NotFound",
            message="User not found",
            errorCode="404"
        );
    }
    return getUser By(id);
}

The module automatically returns appropriate HTTP status codes:

  • 200 OK - Successful response with body
  • 204 No Content - Successful response without body
  • 400 Bad Request - Missing required parameters
  • 404 Not Found - No matching route
  • 405 Method Not Allowed - HTTP method not supported for route
  • 406 Not Acceptable - Cannot produce requested content type
  • 415 Unsupported Media Type - Cannot consume request content type
  • 500 Internal Server Error - Exception during processing

Testing

The module includes comprehensive tests covering:

  • Service registration and discovery
  • Route matching with path parameters
  • Serialization/deserialization (JSON and XML)
  • HTTP method handling
  • Parameter extraction from all sources
  • Custom responses
  • OpenAPI documentation generation

Run tests:

gradle test

Rewrite Rule

CommandBox

Add the following servlet pass predicate to your server.json file ( changing the prefix to your configured prefix ):

path-prefix('/rest/') -> rewrite('/bxmodules/bxrest/public/RestController.bx?method=processAPIRequest&requestPath=%{RELATIVE_PATH}')

Compatibility

This module implements the ColdFusion RESTful services specification as documented in: https://helpx.adobe.com/coldfusion/developing-applications/changes-in-coldfusion/restful-web-services-in-coldfusion.html

Supported features:

  • ✅ REST component and function annotations
  • ✅ HTTP method binding
  • ✅ Path parameters and routing
  • ✅ Content negotiation
  • ✅ JSON and XML serialization
  • ✅ Custom responses
  • ✅ Parameter sources (Path, Query, Form, Header, Cookie, Body)
  • ✅ restInitApplication, restSetResponse, restDeleteApplication BIFs
  • ⚠️ Subresource locators (partial - basic implementation complete)
  • ⚠️ Custom serializers (not yet implemented)

Contributing

See CONTRIBUTING.md for guidelines.

License

Apache License 2.0 - See LICENSE file for details.

Support


Ortus Solutions, Corp https://www.ortussolutions.com

Changelog

All notable changes to this project will be documented in this file.

The format is based on Keep a Changelog, and this project adheres to Semantic Versioning.


[Unreleased]

  • First iteration of this module

$ box install bx-compat-rest

No collaborators yet.
     
  • {{ getFullDate("2026-02-21T16:16:10Z") }}
  • {{ getFullDate("2026-02-21T16:16:11Z") }}
  • 34
  • 2