7.1 Consuming REST Services
Key Takeaways
- The 'Call REST service' activity is microflow-only, supports GET, POST, PUT, PATCH, DELETE, HEAD, and OPTIONS, and organizes configuration across the General, HTTP Headers, Request, and Response tabs.
- Dynamic URLs should be constructed using positional parameter tokens (such as {1} and {2}) anchored to project Constants for hostnames, rather than ad-hoc string concatenation.
- Query parameters must be sanitized and formatted using the urlEncode() function to avoid malformed requests, special character truncation, and injection vulnerabilities.
- Token-based authentication (OAuth 2.0 Bearer) requires obtaining an access token in a prerequisite call and injecting it via a custom HTTP Header as 'Bearer ' + $Token.
- The General tab exposes a single request timeout — 'Use timeout on request' (default Yes) with 'Timeout (s)' (default 300) — and lowering it prevents an unresponsive endpoint from starving Mendix runtime worker threads.
7.1 Consuming REST Services
Exam Focus: Consuming REST APIs is a core competency tested on the Mendix Certified Intermediate Developer exam. Expect questions evaluating your knowledge of the
Call REST serviceactivity's configuration tabs, proper HTTP method selection (GET, POST, PUT, DELETE, PATCH), URL parameterization using tokens{1}versus string concatenation, header configuration (Content-Type,Authorization), Bearer token workflows, request timeout configuration, and proxy and certificate settings.
Modern enterprise architectures rely heavily on decoupled microservices and external SaaS integrations. In Mendix Studio Pro, consuming third-party RESTful APIs is accomplished primarily through the Call REST service microflow activity. Rather than writing low-level HTTP client code in Java, Mendix developers configure declarative properties that govern the network transport, payload formatting, authentication, and response handling.
Anatomy of the 'Call REST Service' Activity
When a developer drags a Call REST service activity into a microflow, the configuration dialog exposes four primary tabs:
CALL REST SERVICE DIALOG
├── 1. General (HTTP Method, Location URL with {1} tokens, Timeout settings)
├── 2. HTTP Headers (Standard & Custom headers, Key-Value expressions)
├── 3. Request (Request body type: Export mapping, Form-data, Binary, or String)
└── 4. Response (Handling: Apply import mapping, Store in string, File document, or Ignore)
1. General Tab
- HTTP Method: Defines the REST verb to execute (
GET,POST,PUT,DELETE,PATCH,HEAD,OPTIONS). - Location: The target endpoint URL. Studio Pro allows developers to specify a template string containing parameter tokens (e.g.,
'https://api.logistics.com/v2/shipments/' + {1} + '/tracking'). - Parameters Table: Declares the expressions that populate the numbered placeholders (
{1},{2}, etc.) in the Location URL. - Use timeout on request:
Yesby default. Mendix recommends keeping it on, because cloud infrastructure silently closes idle HTTP connections and an activity with no timeout can then wait forever. - Timeout (s): The number of seconds to wait for the endpoint to respond, defaulting to 300. When it elapses an exception occurs and the microflow rolls back or follows its custom error handler.
- Proxy configuration: Use app settings (default), Override, or No proxy.
- Client certificate: Use app settings (default) or Override with a client certificate identifier, for endpoints that require mutual TLS.
2. HTTP Headers Tab
Allows specifying HTTP request headers transmitted to the remote server. Common headers include:
Content-Type: application/json(informs the server of the payload format).Accept: application/json(notifies the server of the desired response format).Authorization: Bearer <token>orBasic <base64-credentials>.- Custom enterprise headers (e.g.,
X-Correlation-ID,X-API-Key).
3. Request Tab
Active when using HTTP methods that transmit a body (POST, PUT, PATCH). Developers choose how the payload is generated:
- Export mapping for the entire request: Serializes domain entities or non-persistable entities into JSON or XML.
- Custom request template: Allows assembling a raw JSON string using template parameters.
- Binary / Form-data: Used for file uploads, multi-part form submissions, or streaming binary content.
4. Response Tab
Defines how the Mendix Runtime processes the payload returned by the remote server:
- Apply import mapping: Automatically parses the incoming JSON/XML response into Mendix entities (persistable or non-persistable).
- Store in a string: Captures the raw response body into a microflow String variable. This is especially useful for inspecting payloads during debugging or applying conditional mapping.
- Store in a file document: Streams the response directly into a
System.FileDocument(e.g., downloading a PDF invoice). - Ignore: Discards the response body, standard for HTTP
DELETEoperations or204 No Contentresponses.
HTTP Methods & Semantic Usage
The intermediate certification requires a thorough understanding of standard HTTP verbs and their appropriate architectural usage:
| HTTP Method | Primary Purpose | Carries Request Body? | Idempotent? | Typical Response Code |
|---|---|---|---|---|
| GET | Retrieve an existing resource or collection | ❌ No | ✅ Yes | 200 OK |
| POST | Create a new subordinate resource or initiate an action | ✅ Yes | ❌ No | 201 Created / 200 OK |
| PUT | Completely replace an existing resource (or create if absent) | ✅ Yes | ✅ Yes | 200 OK / 204 No Content |
| PATCH | Apply partial modifications to an existing resource | ✅ Yes | ❌ No | 200 OK / 204 No Content |
| DELETE | Remove a specified resource | ❌ No | ✅ Yes | 200 OK / 204 No Content |
Exam Trap: Remember that PUT is idempotent, whereas POST is not. Calling a PUT operation multiple times with the exact same payload leaves the resource in the exact same state. In contrast, calling a POST operation repeatedly will create multiple duplicate records unless the remote service implements explicit deduplication keys.
Location URL Configuration: Constants vs. Tokens vs. String Concatenation
A critical best practice in enterprise Mendix engineering is avoiding hardcoded endpoint URLs. Applications migrate through environments (Local Development → Test → Acceptance → Production), each communicating with distinct external service instances.
1. Using Project Constants for Hostnames
Always define a project Constant for the base API URL (e.g., @IntegrationModule.ERP_EndpointBaseUrl with default value 'https://sandbox.erp.company.com/api/v1'). In staging or cloud environments, administrators override this constant in the Mendix Developer Portal or environment configuration without rebuilding the deployment package.
2. Positional Parameter Tokens {1}, {2}
Rather than concatenating URL segments manually (which easily introduces missing slashes or formatting errors), configure the Location using positional tokens:
Location:
@IntegrationModule.ERP_EndpointBaseUrl + '/orders/{1}/items/{2}'
Parameters:
{1} -> $Order/OrderNumber
{2} -> $OrderItem/LineItemId
Studio Pro automatically validates that parameters are supplied and cleanly substitutes them into the URL string at runtime.
3. Query Parameters & URL Encoding
When passing filter, pagination, or sorting parameters in a GET request, construct query strings cleanly:
Location:
@IntegrationModule.WeatherApi_BaseUrl + '/forecast?city=' + urlEncode($SearchCity) + '&units=metric'
The built-in urlEncode() function is essential. If $SearchCity contains spaces or special characters (e.g., 'San Francisco' or 'São Paulo'), unencoded URLs will result in HTTP 400 Bad Request or malformed request errors from the target gateway.
Authentication Strategies in Consumed REST Services
External APIs protect their resources through various authentication standards. Mendix supports these directly or via microflow logic:
AUTHENTICATION ARCHITECTURES
├── 1. None (Public open APIs)
├── 2. Basic Authentication (Username & Password -> Base64 encoded)
├── 3. API Key / Header Authentication (Custom header, e.g. X-API-Key: 'secret_key')
└── 4. OAuth 2.0 / Bearer Token (Sub-microflow fetches token -> Authorization: Bearer <token>)
1. Basic Authentication
- Configured directly on the HTTP Headers tab by selecting Use HTTP authentication or manually adding an
Authorizationheader. - Transmits credentials formatted as
Basic base64(username:password). - Limitation: Should only be transmitted over encrypted HTTPS connections to prevent credential interception.
2. OAuth 2.0 & Token-Based Authentication (Bearer Tokens)
Most enterprise APIs require OAuth 2.0 token authentication. Mendix applications implement this pattern using a modular microflow flow:
- Token Retrieval Microflow: Executes a
POSTrequest to the identity provider's token endpoint (e.g.,/oauth/v2/token) passing client credentials (client_id,client_secret, andgrant_type=client_credentials). - Token Caching: The resulting access token and expiration timestamp are stored in a non-persistable entity or session cache to prevent requesting a new token for every subsequent API call.
- Token Injection: In the target API call, a custom header is configured:
- Header Name:
'Authorization' - Header Value:
'Bearer ' + $CachedOAuthToken/AccessToken
- Header Name:
Timeouts, Proxies & Certificates
Robust integrations must account for network latency, server degradation, and transport security.
1. One Request Timeout, Not Two
Studio Pro does not expose separate connection and socket timeouts on the Call REST service activity. The General tab has exactly two related properties:
- Use timeout on request —
Yesby default. Mendix explicitly recommends leaving it on: most cloud infrastructure (including Mendix Cloud) closes HTTP connections that go quiet for a few minutes, and the activity is never told. With the timeout off, the microflow waits indefinitely for data that will never arrive. - Timeout (s) — the number of seconds to wait for a response, default 300. When the endpoint has not responded within that window an exception occurs and the microflow rolls back or routes into your custom error handler.
Exam Best Practice: 300 seconds is a safety net, not a production setting. If an external service hangs, concurrent user requests pile up on blocked runtime worker threads and the whole app becomes unresponsive. Set a realistic value (often 10–30 seconds), always attach an error handler to the activity, and push long-running integrations onto a task queue instead of a user-facing microflow.
A related troubleshooting note worth knowing: java.net.SocketException – Connection reset means the infrastructure closed an idle pooled connection. Mendix documents two remedies — lower the http.client.CleanupAfterSeconds runtime setting below the infrastructure's connection timeout so the client builds a fresh connection, or handle the error in the microflow and retry a bounded number of times.
2. Proxy Configuration
Each activity can inherit app-level proxy settings (Use app settings, the recommended default), Override them with an explicit host, port, username, and password, or force No proxy for that call even when the app has one configured.
3. Certificates: Client Certificates vs. Trusted CAs
Two different certificate problems get confused on the exam:
- Presenting a client certificate (mutual TLS). Set Client certificate on the General tab to Override and supply a Client certificate identifier. In Mendix Cloud that identifier is matched to the Web Service Call name configured for the uploaded certificate; elsewhere it is set through the
ClientCertificateUsagescustom setting. - Trusting the remote server's certificate. If the API is signed by a private, enterprise, or self-signed CA, the handshake fails with
javax.net.ssl.SSLHandshakeException: PKIX path building failed. The fix is to add the remote CA's public certificate to the app's Certificates settings, and to upload it to the environment when deploying to Mendix Cloud. Public CAs such as DigiCert, Let's Encrypt, and GlobalSign are trusted out of the box.
4. SSRF: The Security Consideration Mendix Calls Out
Because Location is a string template, a URL segment can come from user input — which opens a Server Side Request Forgery hole where a user makes your app fetch an internal endpoint they could never reach directly. Mendix's guidance is explicit: never call a URL supplied by the user; if that is unavoidable, validate and sanitise the input, keep an allow-list of permitted domains, and never hand the raw response back to the user.
Practical Exam Scenarios & Architecture Pitfalls
Scenario 1: Malformed Query Parameter with Spaces
A developer builds an address lookup integration. When searching for 'New York', the REST call fails with an HTTP 400 Bad Request error, but searching for 'Boston' succeeds.
- Root Cause: The developer concatenated
'?city=' + $Search/Citydirectly into the Location URL without escaping the space. - Solution: Wrap the variable in
urlEncode($Search/City). This translates spaces to%20(or+), ensuring valid HTTP URI syntax.
Scenario 2: Exhausting Runtime Worker Threads
During peak morning hours, an external shipping API slows down from 200ms responses to 45-second responses. Within 10 minutes, the entire Mendix customer portal becomes completely unresponsive to all users.
- Root Cause: The
Call REST serviceactivity was left on the default Timeout (s) of 300. Hundreds of concurrent user clicks spawned microflow threads that blocked waiting for the shipping API, exhausting the Mendix Runtime worker thread pool. - Solution: Lower Timeout (s) to a realistic value such as 5–10 seconds, add custom error handling so the flow degrades gracefully, and offload shipping calculations to a background task queue.
When configuring the Location URL for a 'Call REST service' activity in Mendix Studio Pro, which approach represents best practice for inserting dynamic path parameters?
An external REST API requires authentication using an OAuth 2.0 Bearer token. How is this standard token-based authentication pattern implemented in a Mendix microflow when calling the REST service?
In Mendix Studio Pro's 'Call REST service' activity, how is the request timeout configured, and what is its default?