Forums

Articles
Create
cancel
Showing results for 
Search instead for 
Did you mean: 

What's the best practice to call RESTful APIs of Confluence?

NGPilot
Contributor
November 17, 2024

I'm new to atlassian and learning its APIs to build apps.

 

Ever I developed a MVP app for JIRA used RESTful API like:

```node.js

 

const res = await api.asUser().requestJira(route`/rest/api/2/issue/${key}/comment`, {
headers: {
'Accept': 'application/json'
}
});

const data = await res.json();
```
It works without any error.
Then I was trying to make an example code to work from official `Build a Confluence keyword extractor with Forge and OpenAI`

 

It uses RESTful APIs for Confluence: 

```node.js

const response = await asUser().requestConfluence(route`/wiki/api/v2/pages/${payload.contentId}?body-format=storage`, { headers: { 'Accept': 'application/json' } });

```

 

It does not work as before! I see the error throw in the console log:

```

Uncaught (in promise) Error: There was an error invoking the function - Error while getContent with contentId 12156995: 401 Unauthorized

```

 

After some searches from the community, seems like that if you want to use RESTful APIs you should put your AUTHENTATION headers in the APIs call.

 

But I'm confusing why JIRA's RESTful APIs don't need the `Authentation` header and Confluence RESTful APIs must have ?

 

If I'm wrong, so what's the best practice to make RESTful APIs call, and how to correct the `401` Unauthorized error.

 

Thanks in advance! :)

1 answer

0 votes
Humashankar VJ
Rising Star
Rising Star
Rising Stars are recognized for providing high-quality answers to other users. Rising Stars receive a certificate of achievement and are on the path to becoming Community Leaders.
November 18, 2024

Hi @NGPilot 

When calling Confluence RESTful APIs, consider the following key points. Authentication differences between Jira and Confluence setups often cause issues. Jira API calls may work seamlessly due to pre-configured authentication methods, such as the asUser() function. Besides that, Confluence API calls require explicit authentication, which is likely missing, resulting in 401 Unauthorized errors.

To ensure successful Confluence API calls, follow best practices: 

  • Use Atlassian SDK or Forge for app development, as they handle authentication complexities.
  • Include authentication in direct REST API calls using Basic Auth or OAuth 2.0 (recommended for production).
  • Utilize API tokens instead of username and password combinations. 

For the 401 Unauthorized error, modify your Confluence API call to include authentication: 

- Generate an API token and store it securely.

- Use Basic Auth with the API token and email address.

Consistency is crucial, include proper authentication in all API calls, even if some seem to work without it.

Environment differences and configurations may also impact API behavior. When using Atlassian Forge, ensure necessary permissions are set in your manifest file

To learn more on the - (API Capabilities, Authentication Methods, Best Practices, API Endpoints, Learning Path) - The Confluence Cloud REST API

Hope this helps - Happy to help further!!
Thank you very much and have a great one!
Warm regards

 

NGPilot
Contributor
November 20, 2024

Yeah, @Humashankar VJ Thanks for your reply, yes I'm using Forge to make my app, to go deeper there may be some details I can not explain clearly, but after I `forge install` more than once and remove the old version the `401` error disappeared :D

Like Humashankar VJ likes this
Humashankar VJ
Rising Star
Rising Star
Rising Stars are recognized for providing high-quality answers to other users. Rising Stars receive a certificate of achievement and are on the path to becoming Community Leaders.
November 20, 2024

@NGPilot  Thanks for the update, let me know if you need any additional assistance.

NGPilot
Contributor
November 20, 2024

Yes if you can help me find more details to solve this issue, let's start it over again.

You could use the official example code to reproduce this issue: https://bitbucket.org/atlassian/forge-ai-confluence-keyword-extractor.git

As our goal is not run the full example so just comment these lines of src/frontend/index.jsx:

 

// // Define a prompt to be used for the OpenAI API
// const prompt = `Here is the data:"${data}"
// Give me the 5 most important keywords from the text. Return the results in the form of a JavaScript array.
// The response shouldn't contain anything apart from the array. No extra text or JavaScript formatting.`

// // Call OpenAI API and store the result (keywords)
// useEffect(() => {
// if(prompt){
// invoke('callOpenAI', prompt).then(setKeywords);
// }
// }, [prompt]);

// console.log("Prompt response - " + keywords);

// // Use state to add the extracted keywords as labels to the current page
// useEffect(() => {
// if(keywords){
// invoke('addKeywordsToLabels', {keywords, contentId}).then(setResponse);
// }
// }, [keywords, contentId]);

// console.log(response)
so we focus on the `getContent` API calling.
after `npm install` and `forge deploy` then `forge install`
run it from the `content action` menu, you could see the error occurs from the console, this time the error is `There was an error invoking the function - Error while getContent with contentId 12156995: 404 Not Found`
I don't know how to make it. Could you help me out? Thanks in advance :)
Like Humashankar VJ likes this
Humashankar VJ
Rising Star
Rising Star
Rising Stars are recognized for providing high-quality answers to other users. Rising Stars receive a certificate of achievement and are on the path to becoming Community Leaders.
November 20, 2024

@NGPilot - Let me get back on this at the earliest.

Humashankar VJ
Rising Star
Rising Star
Rising Stars are recognized for providing high-quality answers to other users. Rising Stars receive a certificate of achievement and are on the path to becoming Community Leaders.
November 20, 2024

@NGPilot 

When calling Confluence's RESTful APIs using Forge, adhere to these best practices for optimal performance and security. Leverage the Forge API module to make HTTP requests to Confluence, ensuring seamless integration. Specifically, import the necessary modules and utilize the asApp() method to authenticate requests.

 

For example:

Import api, { route } from '@forge/api';

Const response = await api.asApp().requestConfluence(route`/wiki/rest/api/content/${contentId}`);

This approach enables secure and efficient interaction with Confluence's APIs.

 

As a next step,

Verify that your manifest file includes the necessary permissions

To read Confluence content summaries, include 'read:confluence-content.summary'. For full content access, add 'read:confluence-content.all'.

 

Your manifest file should resemble:

 

permissions:

scopes:

- 'read:confluence-content.summary'

- 'read:confluence-content.all'

 

This configuration ensures your app has the necessary permissions to interact with Confluence content.

  

Try to manage the errors as needed,

javascript

try {

  const response = await api.asApp().requestConfluence(route`/wiki/rest/api/content/${contentId}`);

  if (!response.ok) {

    throw new Error(`HTTP error! status: ${response.status}`);

  }

  const data = await response.json();

  // Process data

} catch (error) {

  console.error('Error fetching content:', error);

}

  

When interacting with Confluence content, it's crucial to use the correct content ID. Verify that the contentId you're using is valid and accessible to ensure successful API calls. To obtain the content ID, simply check the URL of the Confluence page you're targeting - the ID is typically embedded in the address.

All these steps should make you go without the error, give a try and keep me posted.

 

Best Regards

NGPilot
Contributor
November 20, 2024

Thanks for your continues replies! @Humashankar VJ 

Bad news for you :( After I try all your solutions it does not work as expected.

Could you try the official code by yourself, and I used it for the testing only removed some lines for OPENAI APIs to simplify the procedure, also it failed.

 

If you have time to test the code: https://bitbucket.org/atlassian/forge-ai-confluence-keyword-extractor.git 

 

Please let me know your result, thanks again, you're so kind :)

Like Humashankar VJ likes this
Humashankar VJ
Rising Star
Rising Star
Rising Stars are recognized for providing high-quality answers to other users. Rising Stars receive a certificate of achievement and are on the path to becoming Community Leaders.
November 21, 2024

@NGPilot - Thanks for the update and generosity, let me try on this from my end and will keep you posted.

Suggest an answer

Log in or Sign up to answer
DEPLOYMENT TYPE
CLOUD
PRODUCT PLAN
FREE
PERMISSIONS LEVEL
Product Admin
TAGS
AUG Leaders

Atlassian Community Events