I need to get blog articles from my storefront in JSON format, as the limited amount of articles you can fetch on any single page request is 50 . A bonus would be to be able filter articles based on tag.
Getting JSON from the Shopify storefront is possible through the AJAX API, but is only limited to products
and cart
. I know you can create an alternate template for everything else, but how do you do it for the blog?
I've tried this but it won't work:
https://domain.myshopify.com/admin/blogs/blog_id/articles.json
You talk about Storefront, but you are giving Admin API URL's. You can't request the admin from the storefront without using GraphQL or the Rest API!
You are limited by 50 articles if you don't overwrite the paginate on the storefront.
But if you overwrite it you can get as much as you like. ( have in mind that the larger the article pool the longer the DOM will load )
Example:
{% paginate blog.articles by 9999 %}
{% for article in blog.articles %}
{% endfor %}
{% endpaginate %}
You can create a separate blog template and request it with AJAX and add the tag to the end as well.
So if you create a blog template called blog.ajax.liquid
your request will be something like so: /blogs/news/tagged/featured?view=ajax
and it will return the html for the new template filtered by the tag featured
.
The other way is to use the storefront GraphQL in order to get the articles.
You will need to create a private app and allow Read content like articles, blogs, and comments
in order to use this.
Example query:
{
blogByHandle(handle:"news"){
articles(first: 50, query:"tag:featured") {
edges {
node {
title
}
}
}
}
}
Where this will return 50 article titles which have a tag called featured
, you can add more fields that you like the query to return of course.
The other way is to use the REST API.
You still need to create a private app, but you must allow only the Blog & Article reading rights, no writing permissions. In addition all other rights should be disabled, so that you don't allow other to modify your store data.
The AJAX url will be something like this: https://API_KEY:API_PASSWORD@YOUR_STORE.myshopify.com/admin/api/2020-01/blogs/BLOG_ID/articles.json?tag=featured
I don't recommend this approach, but it will still work.
From there you choose what way you like to go.
Great answer. Thanks for going into such depth. This is honestly better than the Shopify docs. I solved it using your recommendation for the Liquid page.
@Modermo No problem. Please have in mind if you have many post (1000+) this request may increase in time quite a lot ( up to 5-10sec or even more ). The other approaches doesn't have this issue but it will require understanding of the GraphQL or Rest API. Good luck!