Create
cancel
Showing results for 
Search instead for 
Did you mean: 
Sign up Log in

Creating a confluence page via rest api with a label

Dusan Spaic
Contributor
October 24, 2016

Hi everyone,

 

I can easily  create a confluence page via REST api.

In my example i use body

{"type":"page","space":{"key":"TES"},"title":"new-from-postman","ancestors":[{"id":"2129921"}]}


What I need is to create this page with 2 labels, for example 

[{"name":"label1"},{"name":"label2"}]

 

I saw (via get) that labels are kept inside the metadata so I tried to use the same structure in the post

{"type":"page","space":{"key":"TES"},"title":"new-postman2","ancestors":[{"id":"2129921"}], "metadata":{"labels":[{"name":"label1"},{"name":"label2"}]}}

 

but that is not working. I also tried to put the labels directly next to the "ancestors" , without results. In each case the page is created without the label.

 

Is it possible to set the label during the page creation?

 

 

Thank you

4 answers

1 accepted

Comments for this post are closed

Community moderators have prevented the ability to post new answers.

Post a new question

3 votes
Answer accepted
Dusan Spaic
Contributor
July 6, 2018

So to put the final point on this question: Creating a confluence page with a label in a single call is not possible. Two calls are necessary: one for creating a page and a second one for updating the page with the label(s). This is slow but unfortunately unavoidable.  

Allen LaBarge
Contributor
April 23, 2019

I would disagree. You can create a page and insert labels at the same time. This may be a new feature, as this post has a date of close to a year ago. @akiko_pusu had it correct by suggesting adding:

"metadata":{
"labels":[{"name":"sre"},{"name":"kpt"}]
}

 to the request. I can verify that it does work, and I use it regularly. I can also verify that it works with updating a page in confluence, but it will erase the previous labels.

I will however add that unlike the Add Labels to Content API call, you must have NO spaces, commas, periods, etc. in the name parameter.

Like # people like this

@Allen LaBarge  Can you please share your entire json. I'm trying the same thing which you have just said and unfortunately, its creating a new page with no labels. Here is my jason and please do let me know if I'm missing something, TIA.

{"type":"page","title":"This is another child page of the Demo page","space":{"key":"ds"},"ancestors":[{"id":819212}],"metadata":{"labels":[{"name":"label1"},{"name":"label2"},{"name":"label3"}]}}



Allen LaBarge
Contributor
May 17, 2019

Following is the full json you can use in Postman to create content with labels. I have altered the space and ancestor here, for your case. I just ran it to make sure that it does work still. You never know when they will make an unassociated change to the api, which will change how some things work. :)

{
"type": "page",
"title": "Page Title",
"space": {
"key": "ds"
},
"body": {
"storage": {
"value": "Page Content",
"representation": "storage"
}
},
"ancestors": [{
"id": "819212"
}],
"metadata": {
"labels": [{
"name": "label1"
}, {
"name": "label2"
}, {
"name": "label3"
}, {
"name": "label4"
}]
}
}  

This also works programmatically in php, as I use it for client runbooks. 

Like # people like this
Allen LaBarge
Contributor
May 17, 2019

One thing that I did notice in all of the examples that did not work, is that there is no body section. I tried this code without the body section, and it still creates the page correctly, with tags.

We are using the Cloud version of Confluence. This may be a difference between the cloud and server versions.

@Allen LaBarge , I can confirm it now that the above code doesn't work for confluence server. I tried it with body as well but still the same result. Anyways, thanks for your help mate :) 

Like Ike Castillo likes this
1 vote
ganeshkumar patil
I'm New Here
I'm New Here
Those new to the Atlassian Community have posted less than three times. Give them a warm welcome!
August 20, 2018

I have created page and calling function to set labels as below:

---------------------------------------------

from atlassian import Confluence

confluence = Confluence(
    url='https://url1/confluence',
    username='username',
    password='password')

payload = {
    "title":"S6-HW-ENG-CHANGE-0003",
    "body":{
        "storage":{
            "value" : "This is a body",
            "representation":"storage"
        }
    },
    "metadata":{
        "labels":[{"name":"sre"},{"name":"kpt"}]
    }
}
addlabelStatus=confluence.set_page_labels(page_id=662809016,
                                          labels=payload)

----------------------------------------------------------

set_page_labels function is as below:

   def set_page_labels(self, page_id, labels):
        headers = { "content-type": "application/json" }
        try:
            response = requests.post(
                "https://url1/confluence/rest/api/content/{0}/label".format(page_id),
                data = json.dumps(labels),
                headers = headers)
            response.raise_for_status()
            result = response.json()
            page_url = "https://stamp.gs.ec.ge.com/confluence/pages/viewpage.action?pageId={0}".format(page_id)
            return {'status': 'success', 'message': 'labels added', 'url': page_url}
        except Exception as err:
            return {'status': 'fail', 'message': "add label failed: {0}".format(err)}

-----------------------------------------------------------------

I am not able to add labels. I am getting below error:

HTTPError: 400 Client Error: Bad Request for url: https://url1/confluence/rest/api/content/662809016/label

 

Can anybody tell me how to fix this issue please..

0 votes
akiko_pusu
Contributor
December 28, 2017

Hi, I could create a page / blogpost with labels in a single call.

You can pass labels with "metadata" attributes.

Hope this would be any help.

content = "<p>your blog content.</p>"
payload = {
"type":"blogpost",
"title":"blog title",
"space":{"key":"YOUR SPACE KEY"},
"body":{
"storage":{
"value" : content,
"representation":"storage"
}
},
"metadata":{
"labels":[{"name":"sre"},{"name":"kpt"}]
}
}
return payload
Alexander Franke June 21, 2018

sorry, but does not work. Doesnt output an error and creates the blog post but the labels are simply not added 

(Confluence 6.1.1.)

akiko_pusu
Contributor
June 21, 2018

@Alexander Franke

The endpoint to add label is:

  • https://YOUR_CONFLUENCE_URL/rest/api/content/PAGE_ID/label

Now I create (copy) page first, then add label to the created page with using its page id like this.
(Python Script)


import requests
import json

# --- Snip ----

#
# Pass confluence page_id and labels (array)
#
# exp. post https://example.com/wiki/rest/api/content/PAGE_ID/label
#
#
def
add_labels(page_id, labels):
# exp. https://example.com/wiki
base_url = YOUR_CONFLUENCE_URL
auth = (ACCOUNT, PASSWORD_OR_API_KEY)
headers = { "content-type": "application/json" }


try:
response = requests.post(
base_url + "/rest/api/content/{0}/label".format(page_id),
auth = auth,
data = json.dumps(labels),
headers = headers)
response.raise_for_status()

result = response.json()

page_url = base_url + '/pages/viewpage.action?pageId={0}'.format(page_id)
return {'status': 'success', 'message': 'labels added', 'url': page_url}
except requests.exceptions.HTTPError as err:
return {'status': 'fail', 'message': "add label failed: {0}".format(err)}
except:
return {'status': 'fail', 'message': "Unexpected error: {0}".sys.exc_info()[0]} 

 Hope this would be any help.

Alexander Franke June 21, 2018

Thank you for the clarification. I think Kyle Gershman already pointed that out in the first answer. But your script is still a good example.

But coming back to the original question:

Is it possible to set the label during the page creation?

It is not possible to do it during page creation or at least nobody knows how. Two (not-synchronous) calls to the server is slow and not good practice but in this case unavoidable.

Like # people like this
0 votes
KyleGershman October 25, 2016

In my experience, I had to first create the page, then add the labels in two different rest calls.

You'll call rest/api/content to create the page and then rest/api/content/{id}/label.

You parse the result of the create page to get the pageid to pass into the next rest call.

This was my JSON body for the label call, but I only was tagging with one label.  Not sure of the structure for multiple labels, however.

[
    {
        "prefix": "global",
        "name": "@label"
    }
]

 


Dusan Spaic
Contributor
October 25, 2016

thanks, updating an existing page is not a problem, that is working great with one or multiple labels. But creating a page with a label is not documented so Im not sure that it is possible... 

KyleGershman October 25, 2016

Yeah, I haven't been able to add the label at the same time as creating the page.  Doesn't make a lot of sense, but I've learned to just make a subsequent rest call right after page creation.

Elier Delgado November 7, 2017

Did you manage to create a page with labels in a single call? Thanks

Dusan Spaic
Contributor
November 8, 2017

No, I dont think that this is currently possible. You must execute 2 calls :(

@KyleGershman and @Dusan Spaic Can you please share your code for parse the result of the create page to get the pageid to pass into the next rest call I am using the following functions to create a parent page and the fetch the id of it but I want to do that in one function rather than having 2 different functions. 

public static boolean createParentPage(String pageTitle, String confluenceSpace)
throws IOException, AuthenticationException {
CloseableHttpClient client = HttpClients.createDefault();
HttpPost httpPost = new HttpPost("http://localhost:1990/confluence/rest/api/content");
String json;
UsernamePasswordCredentials credentials = new UsernamePasswordCredentials("*****", "**********");
json = "{\"type\":\"page\", \"title\":\""+pageTitle+"\", \"space\":{\"key\":\""+confluenceSpace+"\"}}";
StringEntity entity = new StringEntity(json);
httpPost.addHeader(new BasicScheme().authenticate(credentials, httpPost, null));
httpPost.setEntity(entity);
httpPost.setHeader("Accept", "application/json");
httpPost.setHeader("Content-type", "application/json");
CloseableHttpResponse response = client.execute(httpPost);
int responseCode = response.getStatusLine().getStatusCode();
if(responseCode == HttpURLConnection.HTTP_OK) {
client.close();
return true;
}
else {
client.close();
return false;
}
}

====================================================

public static int getPageId(String pageUrl) throws IOException {
URL urlForGetRequest = new URL(pageUrl);
HttpURLConnection connection = (HttpURLConnection) urlForGetRequest.openConnection();
connection.setConnectTimeout(4000);
connection.setRequestMethod("GET");
byte[] encodedPassword = ( "*******" + ":" + "*********" ).getBytes();
BASE64Encoder encoder = new BASE64Encoder();
connection.setRequestProperty( "Authorization", "Basic " +encoder.encode( encodedPassword ) );
String readLine;
int pageID = 0;
int responseCode = connection.getResponseCode();
if (responseCode == HttpURLConnection.HTTP_OK) {
BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(connection.getInputStream()));
StringBuffer response = new StringBuffer();
while ((readLine = bufferedReader .readLine()) != null) {
response.append(readLine);
}
pageID = Integer.valueOf(response.toString().replaceFirst("[\\S\\s]*<meta name=\"ajs-page-id\" content=\"(\\d*)\">[\\S\\s]*", "$1"));
System.out.println("page id id: " +pageID);
bufferedReader .close();
return pageID;
} else {
System.out.println("Get request not working");
return pageID;
}

Is there a way to improve this operation.  I know there is a way to do it by getting page by tittle and then parsing the id but I don't know how exactly to do that in Java.  

Comments for this post are closed

Community moderators have prevented the ability to post new answers.

Post a new question

TAGS
AUG Leaders

Atlassian Community Events