A way to get the post body from the API using javascript

I am creating a custom integration and will be including a js script on each page of the site (via the footer) which would insert an extra element on the page. This is all good, except for the element is dependent on information within the page such as the title of the page and the body - so I need to extract these and I thought the best way would be using the content API.

However, my issue is that I can easily get content for ‘all posts’ from the site, using an API endpoint
eg. https://demo.ghost.io/ghost/api/v2/content/posts/?key=22444f78447824223cefc48062 …but I need to get the content of the current page (where the script is loading) and I can’t find an identifier (such as ID) within the markup to use…I could write some js to scrape the title and body on the page, but this seems messy and I would rather use the API, so I guess I am looking for a way to get the ID of my post from within the markup? (preferably without editing themes, as I want to make this custom integration available to anyone!)

Thanks for taking the time to read my question and hopefully you understand my issue!

Cheers!

Hi @Oli_C, this is an interesting case! Maybe you could use the page url / slug to query the Ghost Content API. This is pseudo code so please test it first:

api.posts.read(
	{ slug: `${window.location.pathname.replace(/\//g,"")}` },
	{ formats: ['html', 'plaintext'] }
);

The code above grabs the site pathname but strips the slashes out, which should hopefully match the slug of the post. This can then be used to query the API and get back the related post information. Let us know how you get on!

Ah thank you David - I was unaware of this way to query, but if it works then I think it is exactly what I need! I will give this a test today and post my results here.
Thanks again! :slight_smile:

1 Like

Offtopic, but I just realised it was you who did the BristolJS talk- very much enjoyed that!
I didn’t actually make the talk, but am a fellow Bristolian, so I will definitely say hello and buy you a drink if I bump into you at the future talks!

1 Like

Oh awesome! Glad to see you here :smile:

Just to update, it seems to be working fine from my initial testing, so thanks for the help :slight_smile:

One other thing - we would like to get the Custom Integration we are making listed on the website, so others may install it - is there a process for doing this? Cheers!

1 Like