7.3 Publishing REST Services
Key Takeaways
- Published REST Services in Mendix expose microflows and domain entities as standards-compliant HTTP endpoints structured under versioned resource paths.
- Operation path templates support dynamic parameter placeholders (such as /orders/{OrderId}) that automatically bind to identically named microflow input parameters.
- Custom HTTP status codes (e.g., 201 Created, 404 Not Found) and custom headers are returned programmatically by instantiating and returning a System.HttpResponse entity object.
- Mendix supports four authentication models for published services: None (public), Active Session, Basic Authentication, and Custom Authentication microflows that return a System.User.
- Studio Pro automatically generates OpenAPI (Swagger) documentation and interactive exploration interfaces accessible at /rest-doc/ for all published REST services.
7.3 Publishing REST Services
Exam Focus: Exposing application logic and data via Published REST Services is a core evaluation area on the Intermediate Developer exam. You must master the configuration of the Published REST Service document, URL path prefixing and versioning, path parameter binding (
{ParameterName}), request body handling via Import Mappings, programmatic HTTP response generation usingSystem.HttpResponse, authentication schemes (especially Custom Authentication microflows), and Swagger documentation generation.
While consuming REST services allows Mendix applications to ingest data from external systems, publishing REST services turns your Mendix application into an enterprise API provider. External consumers—such as mobile apps, partner portals, microservices, or integration middleware—can trigger Mendix business logic and read or update domain records via standard REST conventions.
Architecture of a Published REST Service Document
In Mendix Studio Pro, publishing a REST service begins by adding a Published REST service document (Add Other > Published REST service). The document editor organizes the service hierarchy into three distinct layers:
PUBLISHED REST SERVICE ARCHITECTURE
├── 1. Service Root (Service Name, Version 'v1', Path Prefix: /rest/orderservice/v1/)
├── 2. Resources (Entity/Concept collections, e.g. /orders, /customers)
└── 3. Operations (HTTP Verbs + Microflows + Routing Templates)
├── GET /orders/{OrderId} ──► Triggers MF_GetOrderDetails
├── POST /orders ──► Triggers MF_CreateOrder
└── DELETE /orders/{OrderId} ──► Triggers MF_DeleteOrder
1. Service Root & URL Prefix
- Service Name: The functional identifier of the API.
- Version: Explicit API version (e.g.,
v1,v2). Best practice is to version every published API to avoid breaking existing clients as the data contract evolves. - Path Prefix: The base URL path where the service is mounted. The default structure is
rest/<servicename>/<version>/(e.g.,https://myapp.mendixcloud.com/rest/crmservice/v1/).
2. Resources
Resources represent the primary business concepts exposed by your application (e.g., orders, invoices, products). Each resource forms a logical branch under the service prefix.
3. Operations
Operations represent the individual HTTP endpoints. Each operation defines:
- Method:
GET,POST,PUT,DELETE,PATCH, orHEAD. - Path: The relative URL path template, optionally including dynamic parameter placeholders (e.g.,
/orders/{OrderId}). - Microflow: The specific business logic executed when an incoming HTTP request matches the method and path.
Parameter Mapping: Path, Query, Header, & Body
When an HTTP request arrives, the Mendix Runtime routes the request and maps HTTP data directly into the operation microflow's input parameters:
INCOMING HTTP REQUEST ─────────────────────► MICROFLOW PARAMETERS
- Path: /orders/84920 - Long OrderId = 84920
- Query: ?includeDiscounts=true - Boolean includeDiscounts = true
- Header: X-Partner-ID: 'ACME' - String PartnerId = 'ACME'
- Body: { "status": "Shipped" } - OrderUpdate_NPE (via Import Mapping)
- Request Metadata - System.HttpRequest httpRequest
1. Path Parameters
- Declared in the operation's path template using curly braces:
/customers/{CustomerId}/invoices/{InvoiceId}. - Binding Rule: The microflow must declare input parameters whose names match the placeholder tokens exactly (
CustomerIdandInvoiceId). The runtime parses the URL segments, casts them to the parameter's type (e.g., String, Integer, Long), and injects them into the microflow.
2. Query Parameters
- Optional parameters appended to the URL query string (e.g.,
?status=pending&limit=25). - Studio Pro allows adding query parameters in the operation editor. Declaring a primitive microflow parameter (String, Boolean, Integer, DateTime) with the same name automatically binds the query value.
3. Header Parameters
- Incoming HTTP request headers (e.g.,
X-Correlation-ID) can be mapped directly to string microflow parameters.
4. Request Body Mapping
For POST, PUT, and PATCH operations, incoming payloads can be handled in three ways:
- Apply an Import Mapping: Automatically deserializes the JSON/XML body into an entity or Non-Persistable Entity (NPE) and passes it as a microflow parameter.
- Binary: Streams the payload directly into a
System.FileDocumentparameter. - String: Injects the raw JSON/XML text string into a string parameter for custom processing.
5. The System.HttpRequest Entity
Operations can optionally include an input parameter of type System.HttpRequest. This built-in system entity provides programmatic access to low-level HTTP metadata, including client IP addresses, cookies, and associated System.HttpHeader records.
Returning Custom HTTP Responses via System.HttpResponse
By default, a published REST operation returns an HTTP 200 OK status code with the payload generated by an Export Mapping or returned string. However, enterprise REST design demands accurate HTTP status codes (e.g., 201 Created upon resource instantiation, 204 No Content upon deletion, or 404 Not Found when a resource does not exist).
The System.HttpResponse Pattern
To take full programmatic control over the HTTP response, configure the operation's microflow to return an instance of System.HttpResponse:
// Microflow Logic to Return 201 Created:
1. Create Object -> System.HttpResponse ($NewResponse)
2. Set Attributes:
- StatusCode = 201
- ReasonPhrase = 'Created'
- Content = $ExportedOrderJsonString
3. Create Object -> System.HttpHeader ($ContentTypeHeader)
- Key = 'Content-Type'
- Value = 'application/json'
- Association: HttpHeader_HttpResponse = $NewResponse
4. Create Object -> System.HttpHeader ($LocationHeader)
- Key = 'Location'
- Value = '/rest/orderservice/v1/orders/' + $NewOrder/OrderId
- Association: HttpHeader_HttpResponse = $NewResponse
5. Microflow End Event returns $NewResponse
If an error occurs (e.g., the requested order ID does not exist in the database), the microflow can instantiate a System.HttpResponse with StatusCode = 404, ReasonPhrase = 'Not Found', and an error JSON body, giving API consumers immediate, standardized feedback.
Authentication Models for Published REST Services
Published REST services in Mendix support four distinct authentication mechanisms, configured on the Security tab of the service document:
| Authentication Method | Operational Mechanism | Recommended Use Case |
|---|---|---|
| Requires no authentication | Endpoints are completely public. Operations execute in the security context of the built-in Anonymous user role. | Public informational APIs (e.g., store locator, public product catalog). |
| Active session | Requires a valid browser session cookie (XASSESSIONID). Requests must originate from an already authenticated user session. | Internal AJAX / React widget calls originating within the Mendix web client. |
| Basic authentication | Checks incoming Authorization: Basic <base64> header against Mendix System.User records (username and password). | Server-to-server legacy integrations where simple service accounts are acceptable. |
| Custom authentication | Executes a custom microflow to inspect request headers, query tokens, or signatures and resolve an authenticated user. | Modern enterprise APIs using OAuth 2.0 Bearer tokens, API Keys, or JWT validation. |
The Custom Authentication Microflow Contract
When selecting Custom, Studio Pro requires a microflow adhering to a strict contract:
- Input Parameter: Receives an instance of
System.HttpRequestrepresenting the incoming network call. - Logic: The microflow inspects headers (e.g., looking for
Authorization: Bearer <token>orX-API-Key), validates the token against an external IDP or internal token table, and resolves the identity. - Return Type: Must return an instance of
System.User(or a specialization such asAdministration.Account).- If a valid
System.Useris returned, the Mendix Runtime executes the target operation within the security and entity access context of that user. - If the microflow returns an empty object (
null), the Mendix Runtime immediately terminates the connection and returns HTTP 401 Unauthorized.
- If a valid
Automated OpenAPI / Swagger Documentation
Mendix Studio Pro includes native support for the OpenAPI Specification (OAS):
- As you define resources, operations, parameters, and mappings, Studio Pro automatically generates an OpenAPI-compliant schema in the background.
- When the application runs, developers and external consumers can navigate to the Swagger UI portal hosted directly on the Mendix Runtime:
https://<app-url>/rest-doc/orhttps://<app-url>/rest-doc/<servicename>/<version>/ - External consumers can explore endpoints, view JSON schemas, and test API operations interactively using the built-in Swagger "Try it out" feature.
Practical Exam Scenarios & Architecture Pitfalls
Scenario 1: Path Parameter Case Mismatch
A developer configures an operation path as /invoices/{invoiceId}. In the microflow, the developer names the input parameter InvoiceID. When external clients call /invoices/1001, the microflow executes, but the parameter InvoiceID is always empty (0 or null).
- Root Cause: Path parameter names are strictly case-sensitive.
{invoiceId}does not matchInvoiceID. - Solution: Rename the microflow parameter to
invoiceIdto match the curly brace placeholder exactly.
Scenario 2: Service Fails in Production Security
A published REST service works perfectly during local testing. However, after deployment to Mendix Cloud with Production security, external requests consistently return HTTP 403 Forbidden or 401 Unauthorized.
- Root Cause: When Security Level is set to Production, published REST operations require explicit Module Role access. The developer forgot to assign access rights to the operation in the service document's security settings.
- Solution: Open the Published REST Service document, navigate to the operations table, and grant execution rights to the appropriate module roles.
When publishing a REST service in Mendix Studio Pro, how can a microflow operation return a custom HTTP status code, such as 201 Created or 404 Not Found, alongside custom response headers?
A Published REST service in Mendix requires Custom Authentication to validate incoming API tokens. What is the fundamental contract of the Custom Authentication microflow configured in the service?
In a Published REST service with base path '/rest/orderservice/v1', a developer defines a resource named 'orders' with an operation path template '/orders/{OrderId}' using the HTTP GET method. How does the underlying microflow access the dynamic OrderId segment?