POST API

While POST requests are traditionally associated with creating or updating resources in external systems, in CodeFusion, POST is not used to persist or save data to external systems. CodeFusion POST requests are exclusively designed for fetching data from APIs that require complex or nested input payloads, such as advanced search, reporting, or analytics endpoints.

This pattern is common in:

  • Search endpoints

  • Reporting APIs

  • Advanced filter-based data queries

These APIs require POST requests because the data being sent (filters, arrays, nested parameters, etc.) cannot be efficiently or securely included in a query string. However, no data is being created or modified—the intent is purely to retrieve data.

Syntax

Copy
var res = api.post(url)
    .putHeader("Accept", "application/json")
    .setBody(body)
    .invoke();

Note: Always use .invoke() or .invokeForJson() to execute the request.

Method Description

Method

Description

Example

api.post(url)

Initiates a POST request to the specified URL for data retrieval.

api.post("https://api.example.com/submit")

.putHeader(name,value)

Adds a custom HTTP header to the request.

.putHeader("Accept", "application/json")

.setBody(body)

Attaches a request payload (string or form-encoded) to the request.

.setBody('{"key":"value"}')

.enableCache(n)

Enables caching of the response for n minutes.

.enableCache(60)

.withReqTimeOut(t)

Sets request timeout (in seconds; default & max: 2).

.withReqTimeOut(2)

.invoke()

Executes the request and returns the raw response as a string.

 

.invokeForJson()

Executes the request and returns the response parsed as JSON.

 

Function Examples

Example 1: Search Endpoint with Advanced Filters

Copy
// Fetches search results from an external system using complex filters.
function searchProducts_main(criteria) {
  var output = {};
  var apiUrl = "https://api.example.com/product/search";

  try {
    var apiResponse = api.post(apiUrl)
      .putHeader("Content-Type", "application/json")
      .putHeader("Accept", "application/json")
      .setBody(JSON.stringify(criteria))
      .invokeForJson();

    output = apiResponse.json || {};
  } catch (error) {
    console.log("[searchProducts_main] API call failed:"+ error);
    output = {
      status: "failed",
      message: "Unable to fetch products",
      error: error && error.message ? error.message : String(error)
    };
  }
  return output;
}

Example Payload:

Copy
{
  "category": "electronics",
  "priceRange": { "min": 1000, "max": 5000 },
  "tags": ["new", "featured"],
  "sortBy": "popularity"
}

Example 2: Reporting API Query

Copy
// Retrieves a report using a POST request with nested filters.
function fetchReport_main(reportQuery) {
  var output = {};
  var apiUrl = "https://api.example.com/report/generate";

  try {
    var apiResponse = api.post(apiUrl)
      .putHeader("Content-Type", "application/json")
      .setBody(JSON.stringify(reportQuery))
      .invokeForJson();

    output = apiResponse.json || {};
  } catch (error) {
    console.log("[searchProducts_main] API call failed:"+ error);
    output = {
      status: "failed",
      message: "Unable to fetch report data",
      error: error && error.message ? error.message : String(error)
    };
  }
  return output;
}

Example Payload:

Copy
{
  "dateRange": { "from": "2024-01-01", "to": "2024-03-31" },
  "metrics": ["sales", "returns"],
  "groupBy": "region"
}

Handling Different Content Types in POST Requests

When using POST requests in CodeFusion to fetch data from external APIs, it is essential to match the structure of your request body to the Content-Type header. This ensures that the receiving API can correctly parse and process your request.

Below are the most commonly used content types with POST in CodeFusion, along with their characteristics and use cases:

1. JSON Data (Content-Type: application/json)

Description:

JSON is the most widely used format for submitting structured and hierarchical data. It supports nested objects, arrays, numbers, strings, and booleans—all in a single payload.

When to use:

  • When your API expects filters, parameters, or configuration in a rich, structured form.

  • For search, analytics, or reporting endpoints that accept complex query definitions.

Example:

Copy
var payload = ‘{
  "category": "books",
  "priceRange": { "min": 10, "max": 100 },
  "tags": ["bestseller", "new"],
  "sortBy": "rating"
}’

api.post("https://api.example.com/product/search")
  .putHeader("Content-Type", "application/json")
  .setBody(payload)
  .invokeForJson();

Typical response: A filtered array of results, based on the payload criteria.

2. URL-Encoded Form Data (Content-Type: application/x-www-form-urlencoded)

Description:

This format encodes key-value pairs in the style of query parameters (for example: key1=value1&key2=value2). It’s useful for simple, flat structures but doesn’t support nested objects or arrays.

When to use:

  • When the API expects data in standard form submission format.

  • For simple filter or parameter passing without hierarchical structure.

Example:

Copy
let urlData = api.urlSearchParams();
urlData.append("query", "data science");
urlData.append("sort", "desc");

api.post("https://api.example.com/search")
  .putHeader("Content-Type", "application/x-www-form-urlencoded")
  .setBody(urlData.toString())
  .invokeForJson();

Typical response: Usually a JSON object or array, depending on the API.

Tip: This format does not handle nested objects or arrays. For more complex data, use JSON.

3. Multipart Form Data (Content-Type: multipart/form-data)

Description:

This format is mainly used when you need to send files along with key-value pairs. Each part of the form is separated by a unique boundary defined by the API framework.

When to use:

  • If an API requires file attachments as part of the search or reporting process.

  • When both files and additional form fields must be submitted together.

Example:

Copy
let formData = api.formData();
formData.append("reportType", "summary");

api.post("https://api.example.com/report/search")
  .putHeader("Content-Type", "multipart/form-data")
  .setBody(formData.toString())
  .invokeForJson();

Typical response: Usually a JSON object or a download link, depending on the API.

Tip: If you need to handle file uploads, confirm the API’s required field names and use the correct encoding.

Summary Table

Content-Type

Description

Best For

application/json

Structured, nested JSON payloads

Advanced filtering, analytics, reporting

application/x-www-form-urlencoded

URL-encoded key-value pairs

Simple search or form data

multipart/form-data

Key-value pairs and file uploads

Submitting files and additional parameters

Best Practice Tips

  • Always match your Content-Type with the structure of your request body.

  • Use JSON.stringify() for JSON payloads.

  • Use api.urlSearchParams() for URL-encoded or multipart data.

  • Test your requests with sample payloads to verify the correct server response.

Handling API Responses

Efficient response handling is essential for robust integration. Always check for and process both success and error responses.

Success Response Example

A successful POST request typically returns a response like:

Copy
{
  "apidata": {
    "rawResponse": "{\"results\":[{\"id\":1,\"name\":\"Example\"}]}",
    "json": {
      "results": [
        { "id": 1, "name": "Example" }
      ]
    },
    "responseCode": 200
  }
}
  • rawResponse: The original string response returned by the API.

  • json: The parsed JSON object from the API response (when using .invokeForJson()).

  • responseCode: The HTTP status code (e.g., 200 for success).

Failure Response Example

If the request fails, you’ll typically see:

Copy
{
  "message": "Invalid or missing parameters",
  "status": 400
}
  • message: Description of the error.

  • status: HTTP error code.

Handling Responses in Your Script

  • Always use try/catch for error management.

  • Use .invokeForJson() to work directly with JSON responses.

  • Check for json, rawResponse, or message to determine success or failure.

Important:

  • In CodeFusion, POST is only used for fetching data from external APIs that require rich, structured request bodies.

  • It is not used for creating, updating, or persisting data in any external system.