GET API
The api.get(url) method is used to perform a GET request to an external API and fetch data. This is the most common pattern for real-time data retrieval in personalization and dynamic content use cases.
Syntax
var res = api.get(url);
Method Description
Method |
Description |
Example |
---|---|---|
api.get(url) |
Initiates a GET request to the given URL. |
api.get("https://api.example.com/data") |
putHeader() |
Sets request headers in name-value format. |
.putHeader("Accept", "application/json") |
enableCache(n) |
Caches the response for ‘n’ minutes (default: 30 min, min: 1, max: 1440). |
.enableCache(60) |
withReqTimeOut(t) |
Sets the request timeout (default & max: 2 seconds). |
.withReqTimeOut(2) |
.invoke() |
Executes the request, returning the raw response. |
|
.invokeForJson( |
Executes the request and parses the response as JSON. |
|
Note: Either .invoke() or .invokeForJson() must be called at the end of the request chain.
Function Example
Example: Fetching Products by Category and Status
This script demonstrates a typical retail scenario: dynamically retrieving product data by category and status for use in a personalized campaign or content block.
// Fetches filtered product data based on category and status.
function getProductData_main(category, status) {
var output = [];
// Build the API URL using the function parameters
var apiUrl = "https://api.example.com/products"
+ "?category=" + encodeURIComponent(category)
+ "&status=" + encodeURIComponent(status);
try {
// Fetch products matching the category and status
var apiResponse = api.get(apiUrl)
.putHeader("Accept", "application/json")
.enableCache(60)
.invokeForJson();
// Extract products array from the API response if present
output = apiResponse.json && apiResponse.json.products
? apiResponse.json.products
: [];
} catch (error) {
// Log the error if the API call fails
console.log("[getProductData_main] API call failed:", error);
}
console.log("[getProductData_main] Output:", output);
return output;
}
-
Calls the API endpoint https://api.example.com/products, using category and status as dynamic query parameters (these could be any business-relevant filters).
-
Sets the Accept: application/json header and enables caching for 60 minutes.
-
Parses the API response as JSON and extracts the products array.
-
Returns the filtered product list as the output.
-
Input arguments are fully dynamic and can be changed for your use case.
-
Stores the output in the res object for further processing.
Note: The function arguments (here: category, status) are placeholders, adapt them to your actual API requirements, such as user ID, date, location, etc.
Handling API Responses
When working with external APIs, CodeFusion supports two main invocation methods:
-
.invoke() for raw (string) responses
-
.invokeForJson() for structured JSON responses
Understanding the structure and handling of each type ensures your scripts remain robust and your business logic is reliable.
Success Response Example:
A typical success response using .invokeForJson():
{
"apidata": {
"rawResponse": "{\"rcs\":\"eF5j4cotK8lME\"}",
"json": {
"rcs": "eF5j4cotK8lME"
},
"responseCode": 200
}
}
Note: If you use .invoke() with .putHeader("Accept", "application/json"), the json property is also available—provided the API returns a valid JSON response.
Response Behavior Based on Invocation Method
Invocation Method |
Response Type |
Description |
---|---|---|
.invoke() |
Raw response |
Returns the unprocessed API response as a string. Use .putHeader("Accept", "application/json") if you expect a JSON response. The json property will be available when the response is valid JSON and the Accept header is set. |
.invokeForJson() |
JSON response |
Parses and returns the API response as a structured JSON object in the json property. Preferred for most integrations. |
Example: Raw Response with .invoke()
{
"apidata": {
"rawResponse": "{\"token\":\"0bdade22744ae00\"}",
"json": {
"token": "0bdade22744ae00"
},
"responseCode": 200
}
}
Example: JSON Response with .invokeForJson()
{
"apidata": {
"rawResponse": "{\"token\":\"0bdade22744ae00\"}",
"json": {
"token": "0bdade22744ae00"
},
"responseCode": 200
}
}
Key Attributes in API Response
-
rawResponse: The raw API response body as a string, regardless of content type.
-
json: The parsed JSON object from the response.
Available when using .invokeForJson(), or when using .invoke() with .putHeader("Accept", "application/json") and the API returns valid JSON.
-
responseCode: The HTTP status code, such as 200 (success), 400 (bad request), or 401 (unauthorized).
-
status: (in some APIs) This property typically matches the HTTP response code.
Tip: For most scenarios, use .invokeForJson() so you can easily access response fields in your script. Use .invoke() if you need to handle non-JSON or custom formats, and always add .putHeader("Accept", "application/json") if you expect a JSON response.