Skip to content

Instantly share code, notes, and snippets.

@ftdysa
Created September 14, 2014 19:15
Show Gist options
  • Save ftdysa/61db917ecfbdbe8a33ba to your computer and use it in GitHub Desktop.
Save ftdysa/61db917ecfbdbe8a33ba to your computer and use it in GitHub Desktop.
Example of accessing ghost's api. Check out core/server/routes/api.js for more routes you can hit.
var querystring = require('querystring');
var http = require('http');
var fs = require('fs');
var requester = require('request');
var postData = querystring.stringify({
grant_type: "password",
username: "your_email",
password: "password",
client_id: "ghost-admin"
});
var uriBase = '/ghost/api/v0.1/';
var requestOptions = {
host: '127.0.0.1',
port: 2368,
path: uriBase + 'authentication/token',
method: 'POST',
headers: {
'Content-Type': 'application/x-www-form-urlencoded',
'Content-Length': postData.length,
'Accept': 'application/json, text/javascript, */*; q=0.01',
'X-Requested-With': 'XMLHttpRequest'
}
};
var request = http.request(requestOptions, function(response) {
response.setEncoding('utf8');
var authData = '';
response.on('data', function(chunk) {
authData += chunk;
})
response.on('end', function() {
console.log('Auth data');
var authObject = JSON.parse(authData);
console.log(authObject);
var apiQuery = querystring.stringify({
include: "roles"
});
requestOptions.headers.Authorization = authObject.token_type + ' ' + authObject.access_token;
requestOptions.headers['User-Agent'] = 'Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/35.0.1916.114 Safari/537.36';
requestOptions.headers.Referer = 'http://127.0.0.1:2368/ghost/4/';
delete requestOptions.headers['Content-Type'];
delete requestOptions.headers['Content-Length'];
var apiOptions = {
url: 'http://' + requestOptions.host + ':' + requestOptions.port + uriBase + '/tags',
headers: requestOptions.headers
};
function callback(error, response, body) {
if (!error && response.statusCode == 200) {
var info = JSON.parse(body);
console.log(info);
}
}
requester(apiOptions, callback);
});
});
request.write(postData);
request.end();
@jgauna
Copy link

jgauna commented Sep 18, 2014

Hello,

Could you help me? after executing it, I get an error:

events.js:72
throw er; // unhandlded event
getaddrinfo ENOTFOUND

Thanks a lot for this code!

@ftdysa
Copy link
Author

ftdysa commented Sep 18, 2014

You probably need to configure your url correctly. getaddrinfo throwing an error is something network related / url not found.

@sgoodwin
Copy link

sgoodwin commented Jan 5, 2015

This was very helpful. Thank you!

@SantoshSrinivas79
Copy link

Thanks works great. Any idea how I could update an existing post using the api? Also, create a new post.
Edit: Will look at core/server/routes/api.js :-)

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment