Last updated Apr 19, 2024

Using the REST API

This tutorial teaches you how to make calls to the REST API in three contexts:

  • Using cURL to make ad-hoc REST API calls
  • In a Connect route handler
  • Using the JavaScript API in a Connect view

In this tutorial, you'll use the Search content REST API and a little CQL to determine which piece of content in your Confluence instance was updated most recently:

  • The REST endpoint is /wiki/rest/api/search
  • The CQL looks like this:
    1
    2
    id != 0 order by lastmodified desc
    
  • You'll use limit=1 to make sure you only get one result: the most recently updated piece of content.

Before you begin

Ensure you have installed all the tools you need for Confluence Connect app development by Getting set up with Atlassian Connect Express (ACE):

  1. Get a cloud development site.
  2. Enable development mode in your site.
  3. Install ACE.

You'll want to add some content to search and make sure you have cURL installed:

  1. Add pages, blog posts, and other content to your Confluence instance.

  2. Install cURL if necessary. You can check whether it is installed by typing:

    1
    2
    curl --version
    

Call the REST API using cURL

You can make REST API calls from the command line using cURL. This is a good way to get familiar with the behavior of the APIs.

Authentication

To make REST API calls using cURL or from a script, you must authenticate with your Atlassian email and API token encoded together in the base64 format. You can use an online tool or an application such as base64 (macOS/Linux) or certutil (Windows) to encode the string into base64 format.

  1. Generate an API token for your Atlassian account.

  2. Build a string with your Atlassian email address and the API token separated by a colon. Example:

    1
    2
    your_email@atlassian.net:1234567
    
  3. Use an online tool or an application to encode the string into base64 format. The result is a string of letters and numbers like this:

    1
    2
    eW91cl9lbWFpbEBhdGxhc3NpYW4ubmV0OjEyMzQ1Njc=
    

You'll use this encoded string in the Authorization header when you make the call.

Making the call

Once you have encoded your credentials, you can use cURL to make a call to the REST API. The syntax is:

1
2
curl --request <method> '<url>?<parameters>' \
--header 'Accept: application/json' \
--header 'Authorization: Basic <encoded credentials>'

You'll be making a GET request to the search REST API using parameters to specify a CQL query and a limit to the number of results. Here are the steps:

  1. Build a URL made up of your Atlassian site plus the path to the REST endpoint. For this tutorial, use the search endpoint. For example:
    1
    2
    https://your_site_name.atlassian.net/wiki/rest/api/search
    
  2. Add the limit and cql parameters to specify the results you want. Remember to URL-encode the spaces by changing them to %20 characters:
    1
    2
    ?limit=1&cql=id%20!=%200%20order%20by%20lastmodified%20desc
    
  3. Finally, build the entire cURL command using the URL, parameters, and your encoded credentials. Specify the GET request method. For example:
    1
    2
    curl --request GET 'https://your_site_name.atlassian.net/wiki/rest/api/search?limit=1&cql=id%20!=%200%20order%20by%20lastmodified%20desc' \
    --header 'Accept: application/json' \
    --header 'Authorization: Basic eW91cl9lbWFpbEBhdGxhc3NpYW4ubmV0OjEyMzQ1Njc='
    
    
    The lines have been broken here for readability using a backslash (\), but for now just put the entire command on a single line.
  4. Type or paste the command onto the command line and press Enter.

If you don't get the results you expect, check the syntax of the command. Spaces, line breaks, or typos can sometimes cause errors that look like authentication failures or other problems.

Create a new app

To make REST API calls from Connect, you'll use the "Hello, World" app that the Connect framework creates. You'll atlas-connect to create the app framework, which is a directory called rest-tutorial that contains all the basic components of a Connect app.

  1. From the command line, go into a directory where you'd like to work, and type:

    1
    2
    atlas-connect new rest-tutorial
    
  2. Select Confluence in the menu.

  3. When the command finishes, go into the rest-tutorial directory and run npm install to install any dependencies for the app.

  4. Add a credentials.json file in your app directory with your information:

    If you've already done the Getting started tutorial, you can just copy over the credentials.json file from that directory.

The "Hello world" app provided by atlas-connect includes a generalPages module, a route handler, and a view already. You'll use these existing components to make a REST API call and display some of the results. If you're not familiar with how the view displays variables from the route handler, you can learn by doing the Creating a general page tutorial.

Make a REST call from the route handler

In a Connect route handler, you can grab the clientKey from the context and use it to build an httpClient for making requests to the REST API. Connect builds headers for you and takes care of authentication using the credentials in credentials.json. In this example, you'll make the same REST API call you made in the cURL example, parse the JSON, and display the title of the updated page. You'll access the title using contents.results[0].title and store it in a variable called page_title for display by the view.

  1. Edit index.js (inside the routes directory), replacing the existing app.get() function with the following code:

    1
    2
     app.get('/hello-world', addon.authenticate(), (req, res) => {
    
             const clientKey = req.context.clientKey;
             const httpClient = addon.httpClient({
                 clientKey: clientKey  
             });
    
             httpClient.get(
                 '/rest/api/content/search?limit=1&cql= id != 0 order by lastmodified desc',
                 function(err, response, contents){
                     if(err || (response.statusCode < 200 || response.statusCode > 299)) {
                         console.log(err);
                         res.render('<strong>An error has occurred : '+ response.statusCode +'</strong>');
                     }
                     contents = JSON.parse(contents);
                     console.log(contents);
                  
                     let page_title;
                 
                     if(contents.size > 0){
                       page_title = contents.results[0].title;
                     }else{
                       page_title = "Error: no results";
                     }
    
                     res.render(
                       'hello-world.hbs', 
                       {
                         title: 'Atlassian Connect', 
                         updated_page: page_title
                       });
                 }
             );   
         });
    
  2. Edit hello-world.hbs (inside the views directory), adding the following line after the Welcome to {{title}} line:

    1
    2
          <p>The most recently updated page is: <b>{{updated_page}}</b>!</p>
    
  3. In the rest-tutorial directory, type npm start on the command line to start the app.

  4. Navigate to your Confluence instance and click on 'Hello World' under Apps. You should see the title of the most recently updated piece of content (and it should match the result you got with cURL).

Because Connect escapes the URL for you, you don't have to replace the spaces with %20 and the URL is much easier to read.

Make a REST call from the view

You can use the Atlassian JavaScript API to make REST calls directly from the view. In this part of the tutorial, you'll use the AP.request() function to make the call, grabbing
some information from the JSON response. You'll change the innerHTML of a <div> to display the information in the view.

  1. If the app is running, stop it.
  2. Edit hello-world.hbs and add the following code after the {{updated_page}} line that you added in the previous section:
    1
    2
      <div id="more_info"></div>
      <script>
         AP.request({
           url: '/rest/api/content/search?limit=1&cql=id!=0 order by lastmodified desc',
            success: function(response) {
              response = JSON.parse(response);
              if(response.size > 0){
                document.getElementById('more_info').innerHTML = 
                  '<ul><li>Type: ' + response.results[0].type + 
                  '</li><li>ID: ' + response.results[0].id + 
                  '</li></ul>'
                } else {
                  document.getElementById('more_info').innerHTML = "<b>No results found.</b>";
                }
            },
            error: function() {
              console.log(arguments);
            }  
          });
      </script>
    
  3. In the rest-tutorial directory, type npm start on the command line to start the app.
  4. Navigate to your Confluence instance and click on 'Hello World' under Apps. You should see additional information below the title of the content.

Conclusion

Now that you know the basic pattern, you can use these three methods to try some of the other REST API endpoints.

Rate this page: