Hey there, fellow dev! Ready to dive into the world of Ghost API integration? If you're looking to harness the power of Ghost's content in your JavaScript projects, you're in the right place. We'll be using the @tryghost/content-api
package to make our lives easier. Let's get started!
Before we jump in, make sure you've got:
First things first, let's get our project off the ground:
mkdir ghost-api-integration cd ghost-api-integration npm init -y npm install @tryghost/content-api
Now, let's set up our Ghost API client. Create an index.js
file and add this:
const GhostContentAPI = require('@tryghost/content-api'); const api = new GhostContentAPI({ url: 'https://your-ghost-site.com', key: 'your-content-api-key', version: 'v3' });
Replace the URL and key with your own. You know the drill!
Time to grab some content! Here's how to fetch posts:
api.posts .browse({limit: 5}) .then((posts) => { console.log(posts); }) .catch((err) => { console.error(err); });
Want authors or tags? Just swap posts
with authors
or tags
. Easy peasy!
Got a ton of content? No sweat. Here's how to handle pagination:
async function getAllPosts() { let posts = []; let page = 1; let hasNextPage = true; while (hasNextPage) { const response = await api.posts.browse({page, limit: 100}); posts = posts.concat(response); hasNextPage = response.meta.pagination.next; page++; } return posts; }
Always wrap your API calls in try-catch blocks. And hey, be nice to the API – implement some rate limiting if you're making lots of requests!
try { const posts = await api.posts.browse({limit: 5}); console.log(posts); } catch (err) { console.error(err); }
Want to get fancy? Try filtering and sorting:
api.posts .browse({filter: 'tag:nodejs', order: 'published_at DESC'}) .then((posts) => { console.log(posts); });
Using React or Vue? No problem! Here's a quick React example:
import React, { useState, useEffect } from 'react'; import GhostContentAPI from '@tryghost/content-api'; const api = new GhostContentAPI({...}); // Your config here function BlogPosts() { const [posts, setPosts] = useState([]); useEffect(() => { api.posts .browse({limit: 5}) .then((fetchedPosts) => { setPosts(fetchedPosts); }) .catch((err) => { console.error(err); }); }, []); return ( <ul> {posts.map(post => ( <li key={post.id}>{post.title}</li> ))} </ul> ); }
And there you have it! You're now equipped to integrate Ghost's powerful content API into your JavaScript projects. Remember, this is just the tip of the iceberg – there's so much more you can do with Ghost's API. So go forth and create something awesome!
Need more info? Check out the official Ghost API docs. Happy coding!