How to set Permalink when creating content through Confluence Rest Api

Comments

1 comment

  • Avatar
    Renato Pereira (Edited )

    So for whoever has the same problem, this was how I approached:

    1. Attempt to create a content in confluence
    2. If there's a bad request related to duplicate title
    3. add 5 random characters to the title and attempt to create again
    4. make a PUT call to change the ScrollPageTitle

    This will make sure the permalink is unique and the title is the one you want.

    Here's the code in nodejs:

    async function createContent(title, ancestorId) {  
    console.log(`Creating content ${title} in confluence...`);
    var pageWithAttachmentMacro = { "type":"page", "ancestors": [{ "type":"page", "id": ancestorId }], "title": title, "space": { "key": space }, "body": { "storage": { "value":'<ac:structured-macro ac:name=\"attachments\"> <\/ac:structured-macro>', "representation": "storage" } } };
    try {
    const response = await postContent(pageWithAttachmentMacro);
    return response.data.id;
    } catch (error) {
    if (error.response) {
    if (error.response.data.statusCode == 400 && error.response.data.message.includes("A page with this title already exists")) {
    let newTitle = title + (+new Date).toString(36).slice(-5);
    let id = await createContent(newTitle, ancestorId);
    await changeScrollPageTitle(id, title);
    return id;
    }
    }

    throw error;
    }
    }
    async function postContent(content) {
    return await axios({
    method: 'post',
    url: `${confluenceRootUri}/rest/api/content`,
    headers: {
    'Content-Type': 'application/json; charset=utf-8',
    "Authorization": "Basic " + Buffer.from(username + ":" + password).toString('base64')
    },
    data: content
    });
    }

    async function changeScrollPageTitle(contentId, pageTitle) {
    await axios({
    method: 'put',
    url: `${confluenceRootUri}/rest/scroll-versions/1.0/metadata/scroll-page-title/${contentId}`,
    headers: {
    'Content-Type': 'application/json; charset=utf-8',
    "Authorization": "Basic " + Buffer.from(username + ":" + password).toString('base64')
    },
    data: { 'scrollPageTitle': pageTitle }
    });
    }

Please sign in to leave a comment.

Powered by Zendesk