The Ghost blogging software platform makes great use of top-of-the-line technologies, and with that comes a great public API that you can use to integrate Ghost with your current software. It does only take about half an hour to learn the basics, and could be a great new method for you to publish your content!
The demo project
To showcase the possibilities of Ghost, we need a little demo project to get the fire started with examples. This project will cover the following API related stuff:
- Logging into Ghost from the command line;
- Publishing a new page with automatically generated data.
Logging into Ghost from the command line
When you create an API request to a Ghost blog it expects a specially crafted so-called access token. An access token is used for authentication purposes on the API side and can be generated by sending your username and password to this location in an HTTP POST request:
/api/v0.1/authentication/token
It expects the following body data:
grant_type=password&username=dummyusername&password=dummypassword&client_id=ghost-admin&client_secret=dummyclientsecret
The client secret of your Ghost blog can be extracted from the login page of your website. You can search through the DOM of the login page or use curl together with grep to fetch it for you:
I also made a PowerShell wrapper to automate the API login process:
<#
.SYNOPSIS
Logs into a Ghost blog.
.DESCRIPTION
Ghost blog login from PowerShell, for demonstration purposes.
.LINK
https://bartsimons.me
#>
Function Invoke-GhostLogin {
[CmdletBinding()]
[OutputType(
[PSCustomObject]
)]
Param (
[Parameter(
Mandatory = $true
)]
[String]
$AdminURL,
[Parameter(
Mandatory = $true
)]
[String]
$User,
[Parameter(
Mandatory = $true
)]
[String]
$Password
)
$LoginPageContent = (Invoke-WebRequest $AdminURL).AllElements
$ClientID = ($LoginPageContent | where { $_.name -eq "env-clientId" } | Select-Object content).content
$ClientSecret = ($LoginPageContent | where { $_.name -eq "env-clientSecret" } | Select-Object content).content
If ($AdminURL[$AdminURL.length-1] -ne "/") {
$AdminURL+="/"
}
$LoginAPIResponse = (Invoke-WebRequest ($AdminURL+"api/v0.1/authentication/token") -Method Post -Body "grant_type=password&username=$User&password=$Password&client_id=$ClientID&client_secret=$ClientSecret").Content | ConvertFrom-Json
return New-Object PSObject -Property @{
access_token = $LoginAPIResponse.access_token
expires_in = $LoginAPIResponse.expires_in
refresh_token = $LoginAPIResponse.refresh_token
token_type = $LoginAPIResponse.token_type
}
}
And just for fun, I also made a wrapper for Bash if you need a automation solution for Linux and macOS:
#!/bin/bash
# Ghost Blog Login Script
# Usage: ./ghostlogin.sh url username password
# Example: ./ghostlogin.sh https://ghost-example.com/ghost/ admin 123456
if [[ $# -eq 3 ]]; then
url="$1"
length_url_end=${#1}
length_url_start=length_url_end-1
if [[ ${1:length_url_start:length_url_end} != "/" ]]; then
url="$url/"
fi
clientdata=($(curl -s $url | grep '<meta name="env-client' | cut -d '"' -f4))
eval "curl -s ${url}api/v0.1/authentication/token --data 'grant_type=password&username=$2&password=$3&client_id=${clientdata[0]}&client_secret=${clientdata[1]}'"
fi
And that makes up for the authentication part of this guide. All you need for you is the access_token token to authenticate all the API requests that require authentication. Now, the next step is to actually post something on your website by using the API. Weird enough, I was not able to find any information nor examples about the POST and PUT request methods in the Ghost official documentation. I found out about how to use it by inspecting the network traffic going out to my testing/demo server. This is how it works:
- You make a POST request with the necessary details/content, the draft gets created;
- The response data contains the body data that's needed for the next request;
- You make a PUT request with the response data from the response of the previous request and modify the needed stuffs;
Here's how to initially create a post via PowerShell:
<#
.SYNOPSIS
Creates a new post on a Ghost blog.
.DESCRIPTION
Create a new post on a Ghost blog, to
.LINK
https://bartsimons.me
#>
Function New-GhostPost {
[CmdletBinding()]
[OutputType(
[String]
)]
Param (
[Parameter (
Mandatory = $true
)]
[String]
$AccessToken,
[Parameter (
Mandatory = $true
)]
[String]
$Title,
[Parameter (
Mandatory = $true
)]
[String]
$AdminURL,
[Parameter (
Mandatory = $true
)]
[String]
$Slug,
[Parameter (
Mandatory = $true
)]
[String]
$Content,
[Parameter (
Mandatory = $true
)]
[Boolean]
$Public
)
If ($AdminURL[$AdminURL.length-1] -ne "/") {
$AdminURL+="/"
}
$NewPostDataTemplate = '{"posts":[{"title":"<%TITLE%>","slug":"<%SLUG%>","markdown":"<%CONTENT%>","image":null,"featured":false,"page":false,"status":"draft","language":"en_US","meta_title":null,"meta_description":null,"author":"1","publishedBy":null,"tags":[]}]}' -Replace "<%TITLE%>","$Title" -Replace "<%SLUG%>","$Slug" -Replace "<%CONTENT%>","$Content"
$PageCreationResponse = (Invoke-WebRequest ($AdminURL+"api/v0.1/posts/?include=tags") -Method Post -Headers @{"Authorization"="Bearer $AccessToken";"Content-Type"="application/json; charset=UTF-8"} -Body $NewPostDataTemplate).Content
If ($Public -eq $true) {
$PostID = ($PageCreationResponse | ConvertFrom-Json).posts.id
$PageCreationResponse = (Invoke-WebRequest ($AdminURL+"api/v0.1/posts/$PostID/?include=tags") -Method Put -Headers @{"Authorization"="Bearer $AccessToken";"Content-Type"="application/json; charset=UTF-8"} -Body ($PageCreationResponse -Replace "draft","published")).Content
}
return $PageCreationResponse
}
You can do the same thing in Bash if you feel more at home with UNIX tools just like me. The code on this one might be a bit messy but it works. And it's not PowerShell. 😉
#!/bin/bash
# Ghost Blog Post Script
# Usage: ./ghostmakepost.sh url accesstoken title slug content public
# Example: ./ghostmakepost.sh https://ghost-example.com/ghost/ "fEwkJhfew7j....fe31" "Just testing :)" "just-testing" "######It works!" true
if [[ $# -eq 6 ]]; then
url="$1"
length_url_end=${#1}
length_url_start=length_url_end-1
if [[ ${1:length_url_start:length_url_end} != "/" ]]; then
url="$url/"
fi
accesstoken="$2"
title="$3"
slug="$4"
content="$5"
public="$6"
conceptdata='{"posts":[{"title":"<%TITLE%>","slug":"<%SLUG%>","markdown":"<%CONTENT%>","image":null,"featured":false,"page":false,"status":"draft","language":"en_US","meta_title":null,"meta_description":null,"author":"1","publishedBy":null,"tags":[]}]}'
conceptdata="${conceptdata/<%TITLE%>/$title}"
conceptdata="${conceptdata/<%SLUG%>/$slug}"
conceptdata="${conceptdata/<%CONTENT%>/$content}"
conceptpostcommand="curl -s ${url}api/v0.1/posts/?include=tags -X POST -H 'Authorization: Bearer $accesstoken' -H 'Content-Type: application/json; charset=UTF-8' --data-binary '$conceptdata'"
conceptpostresult=$(eval $conceptpostcommand)
conceptpostid=($(echo $conceptpostresult | cut -d '"' -f5))
length_conceptpostid=${#conceptpostid}
length_conceptpostid_start=1
length_conceptpostid_end=length_conceptpostid-2
conceptpostid=${conceptpostid:length_conceptpostid_start:length_conceptpostid_end}
if [[ $public == "true" ]]; then
conceptpostresult="${conceptpostresult/\"status\":\"draft\"/\"status\":\"published\"}"
publicpostcommand="curl -s ${url}api/v0.1/posts/$conceptpostid/?include=tags -X PUT -H 'Authorization: Bearer $accesstoken' -H 'Content-Type: application/json; charset=UTF-8' --data-binary '$conceptpostresult'"
publicpostresult=$(eval $publicpostcommand)
echo $publicpostresult
else
echo $conceptpostresult
fi
fi
This is my take on working with the Ghost public API from a command-line and/or scripting perspective. I hope you learnt something from my write-up on Ghost and its beautiful backend work. If you haven't tried Ghost yet, go give it a try: it's open source and free + built on node.js 🙂