The Ghost Themes Developer Hub

Welcome to the Ghost Themes developer hub. You'll find comprehensive guides and documentation to help you start working with Ghost Themes as quickly as possible, as well as support if you get stuck. Let's jump right in!

Get Started    

Ghost API via Ajax: Fetching tags

Making ajax requests to the Ghost API inside your theme

Beta Feature

This recipe uses the ghost.url.api() utility, which comes from the Ghost SDK script. This is part of the Public API Beta feature and may change at any time.

From Ghost 1.0.0 the Public API is enabled by default. Once you've upgraded, it should remain fairly stable. Read more about what the Public API Beta means.

It is now possible to query the public Ghost API to fetch collections of posts, users or tags that match certain criteria. The API documentation, covers the full range of what is possible with the Ghost JSON API.

This recipe shows you step by step how to get started using the API via AJAX to fetch and display all of the tags for your blog, using the new ghost.url.api() utility, which makes it possible to build URLs for making API requests.

1. Check the requirements

Firstly, you must have the {{ghost_head}} helper in your theme, otherwise you will not get access to the ghost.url.api() utility. The best place to do this is in the default.hbs file.

Example snippet from default Casper theme:

<!DOCTYPE html>
<html>
<head>
    {{! Document Settings }}
    <meta charset="utf-8" />
    <meta http-equiv="X-UA-Compatible" content="IE=edge" />

    {{! Page Meta }}
    <title>{{meta_title}}</title>
...
    {{! Ghost outputs important style and meta data with this tag }}
    {{ghost_head}}
</head>

Secondly, you must have enabled the 'Public API' setting in your admin panel. this is enabled by default and is found on the labs page:

2. Get your theme ready

Next, you'll need to figure out where you want the data from your ajax request to be output and have some way to reference this location. There are far more elegant ways, but for this example we'll use an empty element with an ID.

<aside>
  <h3>Tag list</h3>
  <ol id="tag-list"></ol>
</aside> 

The final setup task is ensuring you have jQuery available in your theme. If you don't have jQuery included via the {{ghost_foot}} box in the code injection screen in your admin panel, then you'll need to add it to your default.hbs so that the bottom of the file looks a bit like this:

...
  <script type="text/javascript" src="https://code.jquery.com/jquery-1.11.3.min.js"></script>
  {{ghost_foot}}
...
</body>
</html>

Now that all of these pieces are in place, you can make an ajax request using ghost.url.api along with your query.

3. Adding your Ajax script

Back in default.hbs, add a script tag, beneath your {{ghost_foot}} helper and any other scripts you need (like jQuery).

{{ghost_foot}}
<script type="text/javascript">
 // your script goes here...
</script>

Next, lets build our query URL. We want to fetch all tags, including how many posts there are that has that tag. We also want to order the results so that the tag with the most posts comes first.

So, we want a URL that queries the tags endpoint and that sets the limit to 'all'. Then we want to tell it to include the field count.posts, and finally to order the query by count.posts DESC.

Putting all this together using the ghost.url.api() utility, we end up with URL building code that looks like this:

ghost.url.api('tags', {
  limit: 'all', 
  include: 'count.posts', 
  order: 'count.posts DESC'
});
<protocol>://<host>/ghost/api/<version>/tags/?limit=all&include=count.posts&order=count.posts%20DESC&client_id=<client_id>&client_secret=<client_secret>

All of these query parameters are explained in the API documentation.

If you click the 'URL' tab above the previous code example, you'll see that the output from ghost.url.api is the URL we need to query. Using jQuery, performing a 'GET' HTTP request via Ajax is super simple using the $.get() convenience method. We just have to pass our URL to $.get() and tell it what we want to do with the data when we're done:

$.get(
  ghost.url.api('tags', {
    limit: 'all', 
    include: 'count.posts', 
    order: 'count.posts DESC'
  }).done(function (data) {
    console.log('Success!', data);
  });
);

However, to get this to work correctly, we'll need to wrap this function in jQuery's document.ready function:

jQuery(document).ready(function () {
  $.get(
    ghost.url.api('tags', {
      limit: 'all', 
      include: 'count.posts', 
      order: 'count.posts DESC'
    })
  ).done(function (data) {
    console.log('Success!', data);
  });
});

Adding this to your default.hbs should now result in a working query, which outputs 'Success!' and the data that has been fetched into the browser's console.

Now let's do something more useful with the data...

4. Processing the data

First of all, rather than handling our data inline, let's quickly create a separate named function to make this easier to read:

function onSuccess(data) {
  console.log('Success!', data);
}  

jQuery(document).ready(function () {
  $.get(
    ghost.url.api('tags', {
      limit: 'all', 
      include: 'count.posts', 
      order: 'count.posts DESC'
    })
  ).done(onSuccess);
});

Now, all we have to do is update our onSuccess method so that it does something useful. To start with, lets grab our empty element that we setup earlier with var $result = $('#tag-list');

function onSuccess(data) {
  var $result = $('#tag-list');
}  

The data we get back from the API is a JSON object with a key which matches the resource we requested. So in our case, we need to iterate over data.tags.

function onSuccess(data) {
  var $result = $('#tag-list');
  $.each(data.tags, function (i, tag) {
    // do something with each tag
  });
}  

Finally, we're going to append the HTML for a list item and an anchor which points to the tag page for this particular tag.

function onSuccess(data) {
  var $result = $('#tag-list');
  $.each(data.tags, function (i, tag) {
    $result.append(
      '<li><a href="/tag/' + tag.slug + '/">' + tag.name + '</a></li>'
    );
  });
}  

You can find out more about the data you have available to you in the API docs for tags.

Note: For the time being, you need to manually construct the urls for blog pages like the tag or author page. Posts get their URL returned with them. The intention is to extend ghost.url to also allow for building other URLs in the near future.

Ghost API via Ajax: Fetching tags

Making ajax requests to the Ghost API inside your theme