How to post to a Cosmic Bucket directly from the Drafts app

Community Articles
Community Articles How to post to a Cosmic Bucket directly from the Drafts app

Introduction

Cosmic is a fantastic headless CMS for powering your website, but if you write regular articles or often update site text, you might find it challenging to always come into the backend and make those changes (especially when you're on the go).

If you use the Pro version of Drafts, then you're in luck. I'm going to talk you through how I set up a custom action extension in Drafts to allow you to create a blog post automatically using the Cosmic API. It's lightning-fast to set up and a delight to use. It gives you the power to quickly update a blog post from anywhere on your Mac, iPad or iPhone. So no more annoying typos that you can't fix until you get home.

Assumptions

This post assumes you already understand how to create a blog using your preferred programming language and have a basic understanding of APIs and particularly Cosmic's API. The documentation is great if you get lost though!

The setup

  1. So, to get started you'll need to have a Cosmic account with a Bucket set up
  2. You'll need access to the Drafts app (so sorry Android users!)
  3. You'll need to upgrade to their Pro subscription to enable the ability to add a custom Action Extension

Cosmic Bucket

  1. Start by naming your project, we're calling ours Post from Drafts Set up a Bucket

  2. Create a new Object and call it Blogs (you can of course call it what you like, but for the purpose of following along I'd recommend Blogs) Creating an Object type

  3. We're then going to add some additional metafields. One is a Date type for setting a publication date. This is deliberate as we may want to control the date shown as published rather than relying on Cosmic's record or when the button was pressed or when it was last modified etc. We also want one for a snippet, this allows us to pass in a short character limited version of the Draft to act as a teaser. Add some metafields

Now, we're ready to enter the land of APIs…

Cosmic API at the ready

  1. In order to pass in the right fields for our HTTP request, we need specific data from our Cosmic Bucket to give to the POST URI. Cosmic Bucket settings *note this Bucket has been deleted and these keys do not work, so don't attempt to use them

  2. Download the extension from Cosmic or grab the JS file directly from GitHub The GitHub repository

  3. Start by right clicking (if on a Mac) in the right hand Action Extensions panel and choose "Insert Action". You can also add this on iPad or iPhone by swiping from the right and tapping the small plus at the bottom to add a "New Action". Adding an action extension in Drafts

  4. Tap the drop down and select the "Script" action type then tap the plus button to create a new one, click or tap on it. Once you have it, click or tap the "Edit" button in the top right to start adding some code. Select Action type

  5. Define your Drafts variables (you can see all the available options from their extensive script reference library) but to follow along, use the below.

let title = draft.displayTitle;
let content = draft.processTemplate("%%[[body]]%%");
let date = draft.processTemplate("[[modified]]");
let snippet = draft.bodyPreview(140);

Variable code

  1. Create your API POST request
var http = HTTP.create(); // create HTTP object
var response = http.request({
  "url": "https://api.cosmicjs.com/v1/your_cosmic_bucket_slug/add-object", // Add your Cosmic Bucket slug, you can find it in your user settings
  "method": "POST",

Creating an API request

  1. Then add your data—this should match your previously set variables and should align with what your Cosmic bucket is expecting for consistency. But! Cosmic is clever so if a metafield doesn't exist, Cosmic will create it for you for that object and fill out the value!
  "data": {
  "title": title, // default Cosmic data point for the object title
  "content": content, // default Cosmic data point for the body content
  "type_slug": "your_object_slug", // find this in your Object's settings
  "metafields": [ // If these fields don't exist, Cosmic will create the metafields and fill the data for you... awesome
    {
      "key": "value", // e.g. published-date
      "title": "value", // e.g. Published on
      "type": "date",
      "value": date,
    },
    {
      "key": "value", // e.g. snippet
      "title": "value", // e.g. Content snippet
      "type": "text",
      "value": snippet,
    }
  ],
  1. Finally, set a status type, either draft or published. If you don't set anything here or delete this line then Cosmic will publish it by default. Then set your Cosmic write key to allow you to publish content from outside your Bucket. Get this from Bucket › Settings › Write Key
"status": "draft", // e.g. "draft" / "published"
  "write_key": "your_cosmic_write_key"
    },
});

Adding data in to create the request

  1. Putting it all together
let title = draft.displayTitle;
let content = draft.processTemplate("%%[[body]]%%");
let date = draft.processTemplate("[[modified]]");
let snippet = draft.bodyPreview(140);

var http = HTTP.create(); // create HTTP object
var response = http.request({
  "url": "https://api.cosmicjs.com/v1/post-from-drafts/add-object", // Add your Cosmic Bucket slug, you can find it in your user settings
  "method": "POST",
  "data": {
  "title": title, // default Cosmic data point for the object title
  "content": content, // default Cosmic data point for the body content
  "type_slug": "blogs", // find this in your Object's settings
  "metafields": [ // If these fields don't exist, Cosmic will create the metafields and fill the data for you... awesome
    {
      "key": "date", // e.g. published-date
      "title": "Date", // e.g. Published on
      "type": "date",
      "value": date,
    },
    {
      "key": "snippet", // e.g. snippet
      "title": "Snippet", // e.g. Content snippet
      "type": "text",
      "value": snippet,
    }
  ],
  "status": "draft", // e.g. "draft" / "published"
  "write_key": "s7htjEfu4I1lDTR8b6Q278ZoED2q2VDJsX1YccvPBlFoW2QiNw"
    },
});
  1. Once you hit save you'll see the following. Your Action Extension is now complete and ready to enjoy! Let's test it out. Saving the extension

  2. First create your Draft. You can use Markdown throughout in the body and Cosmic will accept that in as HTML to the Content block Creating a Draft

  3. Double click the action extension (or simply tap on mobile) to run. If all the data are right, you'll get a little success badge Action posted

  4. Check your Bucket, you'll now see a brand new post sitting there waiting. The Drafts variable passes in the Markdown of the header. It's a bit annoying, but you can either leave it off or let me know if there's a way to strip it out! [Edit: I’ve updated the script to include the new title variable which uses a draft function displayTitle to strip the markdown! Sweet.] Viewing the new post

  5. If you go into the new post now, you'll see firstly that it was successfully saved as a draft for us and that all the relevant fields were passed to Cosmic. If you add any variables and data in your Action Extension that Cosmic doesn't already have then it super cleverly creates them for you. How awesome is that! Viewing the new post entirely

Conclusion

And that's it. It's as simple as that. Obviously you'll need to have set up a Blog to accept all this in, I'd recommend following some of the examples in the community posts if you're just getting started.

You may also like


Build a documentation app in a afternoon leveraging the powered of Gatsby and Cosmic.
In addition to Import / Export Features and Revision History, Cosmic has added Automatic Bucket Backups to deliver even more peace of mind to you and your content editing team. To add daily Backups to your Buckets go to Your Bucket Dashboard > Settings > Backups.
Cosmic Extensions make it possible to extend the functionality of Cosmic for both the developer and editor. A recent example built by the Cosmic Community is the Google Analytics Extension, which allows team members to easily see analytics insights directly in their Cosmic Bucket.
Step by step guide to creating a Cosmic extension that imports data
In this short walk-through, I show you how to add localization to your Cosmic Object Types.
This is a quick example to show some of the powerful things you can do with the Cosmic NPM Module. This script will, add a Bucket to your Cosmic account, add an Object Type (Pages) and add a few Pages.

Get Started with Cosmic

Build personal projects for free. Add your team at unbeatable prices.
Start Building Talk to Sales