---
title: "Scaffolding REST API code examples"
canonical: "https://support.appfire.com/space/SCAFS/477598143/Scaffolding%20REST%20API%20code%20examples"
format: markdown
---
> Macro (aura-html)

## Using the API

To use this API from scratch, there are 3 basic steps.

![image](media://50072669-5ff0-489d-8b28-9d698aef48f1)

> ℹ️ If you already have the Confluence pages and Scaffolding structure created, then you can go directly to step 3.

> Macro (excerpt)
> 
> For a full example of code, visit our [GitHub repo](https://github.com/ServiceRocket/scaffolding-api-sample).

## Resources

The following Atlassian resources can help you with the following examples.

- [Confluence REST API examples](https://developer.atlassian.com/confdev/confluence-server-rest-api/confluence-rest-api-examples)
- [How to get Confluence page ID](https://confluence.atlassian.com/confkb/how-to-get-confluence-page-id-648380445.html)

## Example - Import CSV

This example imports the contents of a CSV file ([employees.csv](https://github.com/ServiceRocket/scaffolding-api-sample/blob/master/nodejs/sample_data/employees.csv)) into an existing table on a Scaffolding form.

```javascript
// Fetching Scaffolding form
restClient.fetchForm(basicAuthCredentials, pageId)
    .then(res => {
        const form = res.data.find(f => f.macro === 'table-data' && f.name === 'Employees');
        const fields = form.rows;

        // Read from CSV file
        readCsv('./sample_data/employees.csv', (csvData) => {

            // Crafting payload
            const values = csvData.map(record => {
                return fields.map(f => {

                    // Parse date into acceptable format
                    if (f.macro === 'date-data') {
                        return Object.assign({}, f, {value: parseDate(record[f.name])})
                    }
                    // `list-data` value must be an array
                    if (f.macro === 'list-data') {
                        return Object.assign({}, f, {value: [record[f.name]]})
                    }
                    return Object.assign({}, f, {value: record[f.name]})
                })
            });

            // Convert array into object
            form.value = values.reduce((acc, val, index) => {
                return Object.assign(acc, {[index]: val})
            }, {});

            // Payload must be an array
            const payload = [form];

            // Insert data from CSV to Scaffolding table-data form.
            restClient.createRecord(basicAuthCredentials, pageId, payload)
                .then((res) => console.log('result >>', res))
                .catch((err) => console.error('>>', err))
        })
    })
    .catch((err) => console.log('this is error', err));
```

> Macro (excerpt)
> 
> For the rest of the example code, look at [import_csv.js](https://github.com/ServiceRocket/scaffolding-api-sample/blob/master/nodejs/import_csv.js) on our GitHub repo.

## Example - Import product list

In this example: 

- Data from a CSV file ([products.csv](https://github.com/ServiceRocket/scaffolding-api-sample/blob/master/nodejs/sample_data/products.csv)) is extracted.
- Pages with an existing LiveTemplate ([product-details-storage-format.xml](https://github.com/ServiceRocket/scaffolding-api-sample/blob/master/nodejs/sample_data/product-details-storage-format.xml)) with a Scaffolding form are created.
- Then the macro injects data into the Scaffolding forms on each created page.

```javascript
// Event handler for `row` event.
ev.on('row', (row) => {
    const pageTitle = `${row['Product No']} - ${row['Product Name']}`

    // Create page within 'TEST' space using constructed page title and live-template macro
    restClient.createPageWithTemplate(basicAuthCredentials, template, 'TEST', pageTitle).then(async (res) => {
        if (res.statusCode !== 200) {
            console.error(">> Fail to create page.")
            console.error(`>> Error ${res.statusCode}:`, res.data.message)
            return
        }

        // Get page id for newly created page
        const pageId = res.data.id

        // Fetch Scaffolding form and construct payload using the form
        const payload = await restClient.fetchForm(basicAuthCredentials, pageId)
            .then(form => {
                return form.data.map(field => {
                    const value = row[field.name]
                    return Object.assign(field, {value})
                })
            })
            .catch(err => console.error(err))

        // Insert data to the form.
        restClient.createRecord(basicAuthCredentials, pageId, payload)
            .then((res) => {
                console.log(res)
            })
            .catch((err) => console.error(err))
    })
})
```

> Macro (excerpt)
> 
> For the rest of the example code, look at [import_product_list.js](https://github.com/ServiceRocket/scaffolding-api-sample/blob/master/nodejs/import_product_list.js) on our GitHub repository.

## Example - Upload attachments

This example uploads attachments into an existing Scaffolding form on a page.

```javascript
// Fetch Scaffolding form
restClient.fetchForm(basicAuthCredentials, pageId)
    .then(res => {
        const form = res.data.find(f => f.macro === 'table-data' && f.name === 'Applicants');
        const fields = form.rows;

        // Upload attachment to Confluence page
        restClient.uploadAttachment(basicAuthCredentials, pageId, './products.csv', 'reuaae.docx')
            .then((res) => {
                if (res.statusCode !== 200) {
                    console.error(">> Fail to upload attachment")
                    console.error(`>> Error ${res.statusCode}:`, res.data.message)
                    return
                }

                // Retrieve the attachment title
                const attachmentId = res.data.results[0].title

                // Craft a single record to be inserted to table-data
                const record = fields.map(f => {
                    if (f.name === 'Name') {
                        return Object.assign({}, f, {value: 'Ted Mahsun'});
                    }
                    if (f.name === 'Resume') {
                        return Object.assign({}, f, {value: attachmentId});
                    }
                });

                // Craft values for table-data. Only 1 record for this example
                const tableDataValues = [record];

                form.value = tableDataValues.reduce((acc, value, index) => {
                    return Object.assign(acc, { [index]: value })
                }, {});

                // Payload must be in array
                const payload = [form];

                // Insert data to Scaffolding form
                restClient.createRecord(basicAuthCredentials, pageId, payload)
                    .then(res => console.log('>>', res))
                    .catch(err => console.error(">> Fail to insert data.", err))
            })
            .catch((err) => console.error(err))
    })
    .catch(err => console.error(err));
```

> Macro (excerpt)
> 
> For the rest of the example code, look at [upload_attachment.js](https://github.com/ServiceRocket/scaffolding-api-sample/blob/master/nodejs/upload_attachment.js) on our GitHub repository.

## See also

- [Using the Scaffolding REST API with ScriptRunner for Confluence](https://appfire.atlassian.net/wiki/spaces/SCAFS/pages/477598722)