Skip to content

RestService Examples

Dmytro Katashev edited this page Aug 13, 2024 · 2 revisions

REST Service Examples

Fetching JSON Data from an API

This example demonstrates how to perform a simple GET request to retrieve JSON data from a REST API.

var RestService = require('*/cartridge/scripts/webservice/RestService');

// Define a custom REST service
var OrderRestService = RestService.extend({
    SERVICE_CONFIGURATIONS: {
        default: 'order.rest.service',
    },

    /**
     * Fetch order details from the external API.
     *
     * @param {dw.order.Order} order - The order object.
     * @returns {dw.svc.Result} - The service result.
     */
    fetchOrderDetails: function (order) {
        return this.fetch({
            method: 'GET',
            pathPatterns: { orderId: order.orderNo }
        });
    }
});

// Perform the HTTP call
var result = OrderRestService.fetchOrderDetails(order);

Fetching Data and Saving to a File

In this example, the GET request retrieves data from an API and saves the response directly to a file.

var RestService = require('*/cartridge/scripts/webservice/RestService');
var File = require('dw/io/File');

// Define a custom REST service with file handling
var FileSavingRestService = RestService.extend({
    SERVICE_CONFIGURATIONS: {
        default: 'file.rest.service',
    },

    /**
     * Fetch order details and save to a file.
     *
     * @param {dw.order.Order} order - The order object.
     * @returns {dw.svc.Result} - The service result.
     */
    fetchOrderAndSaveToFile: function (order) {
        var filePath = [File.IMPEX, 'orders', order.orderNo + '.json'].join(File.SEPARATOR);
        var outFile = new File(filePath);

        return this.fetch({
            method: 'GET',
            outFile: outFile
        });
    }
});

// Perform the HTTP call
var result = FileSavingRestService.fetchOrderAndSaveToFile(order);

Sending JSON Data to an API

This example demonstrates how to send a POST request with JSON data.

var RestService = require('*/cartridge/scripts/webservice/RestService');

// Define a custom REST service for sending data
var OrderRestService = RestService.extend({
    SERVICE_CONFIGURATIONS: {
        default: 'order.rest.service',
    },

    /**
     * Send order details to the external API.
     *
     * @param {dw.order.Order} order - The order object.
     * @returns {dw.svc.Result} - The service result.
     */
    sendOrderDetails: function (order) {
        return this.fetch({
            method: 'POST',
            dataType: 'json',
            data: {
                orderId: order.orderNo,
                totalAmount: order.totalGrossPrice.value
            }
        });
    }
});

// Perform the HTTP call
var result = OrderRestService.sendOrderDetails(order);

Sending Form URL-encoded Data

This example shows how to send data as URL-encoded form data in a POST request.

var RestService = require('*/cartridge/scripts/webservice/RestService');

// Define a custom REST service for form submissions
var FormRestService = RestService.extend({
    SERVICE_CONFIGURATIONS: {
        default: 'form.rest.service',
    },

    /**
     * Send order details as form URL-encoded data.
     *
     * @param {dw.order.Order} order - The order object.
     * @returns {dw.svc.Result} - The service result.
     */
    sendOrderAsForm: function (order) {
        return this.fetch({
            method: 'POST',
            dataType: 'form',
            data: {
                orderId: order.orderNo,
                customerEmail: order.customerEmail
            }
        });
    }
});

// Perform the HTTP call
var result = FormRestService.sendOrderAsForm(order);

Sending Multipart Form Data

This example demonstrates how to send multipart form data, which can include files and form fields.

var RestService = require('*/cartridge/scripts/webservice/RestService');

// Define a custom REST service for multipart data
var MultipartRestService = RestService.extend({
    SERVICE_CONFIGURATIONS: {
        default: 'multipart.rest.service',
    },

    /**
     * Send order details and a file as multipart form data.
     *
     * @param {dw.order.Order} order - The order object.
     * @returns {dw.svc.Result} - The service result.
     */
    sendOrderWithFile: function (order) {
        var File = require('dw/io/File');
        var HTTPRequestPart = require('dw/net/HTTPRequestPart');

        var filePath = [File.IMPEX, 'orders', order.orderNo + '.xml'].join(File.SEPARATOR);
        var fileData = new File(filePath);

        return this.fetch({
            method: 'POST',
            dataType: 'multipart',
            data: [
                new HTTPRequestPart('orderId', order.orderNo),
                new HTTPRequestPart('orderXml', fileData)
            ]
        });
    }
});

// Perform the HTTP call
var result = MultipartRestService.sendOrderWithFile(order);

Sending Multipart Mixed Data

This example demonstrates sending multipart/mixed data, often used when mixing different types of content in a single request.

var RestService = require('*/cartridge/scripts/webservice/RestService');

// Define a custom REST service for mixed multipart data
var MixedMultipartRestService = RestService.extend({
    SERVICE_CONFIGURATIONS: {
        default: 'mixedmultipart.rest.service',
    },

    /**
     * Send order details and other data as multipart/mixed.
     *
     * @param {dw.order.Order} order - The order object.
     * @returns {dw.svc.Result} - The service result.
     */
    sendOrderWithMixedData: function (order) {
        var UUIDUtils = require('dw/util/UUIDUtils');

        var boundary = UUIDUtils.createUUID();
        var parts = [
            {
                headers: {
                    'Content-Type': 'application/json'
                },
                body: JSON.stringify({
                    orderId: order.orderNo,
                    totalAmount: order.totalGrossPrice.value
                })
            },
            {
                headers: {
                    'Content-Type': 'application/xml'
                },
                body: '<order><id>' + order.orderNo + '</id></order>'
            }
        ];

        return this.fetch({
            method: 'POST',
            dataType: 'mixed',
            data: {
                boundary: boundary,
                parts: parts
            }
        });
    }
});

// Perform the HTTP call
var result = MixedMultipartRestService.sendOrderWithMixedData(order);

Clone this wiki locally