Introduction to GraphQL & BigCommerce
Do you know about GraphQL?
Perhaps some people will say “YES,” but the majority will have the NO answer. Regarded as an alternative to REST API, GraphQL possesses plenty of features to help developers make it easier to manage and develop their eCommerce store. This is also the reason why BigCommerce, one of the most popular platforms for online stores, develops and introduces this feature to their merchants.
So, what exactly is GraphQL? What can it bring to users? How is GraphQL used in BigCommerce? All will be answered in this post! Also, you will see an example of GraphQL on this platform.
About GraphQL
GraphQL is a type of programming language which is known as an open-source data queries and manipulation language for APIs. Initially developed by Facebook in 2012, GraphQL’s owner then was changed to Lux Foundation in 2018. After nearly 10 years of development, this programming language has become a strong competitor of REST and other web service architectures.
With GraphQL, clients will be able to request exactly what they need via HTTP protocol. IT enables users to set a certain structure of data needed, and then the system will return the data with the same structure as had been set. This helps clients avoid the case of too much data returned and work with the data more efficiently.
More than that, GraphQL can be used in plenty of languages, such as JavaScript, Haskell, Perl, Python Development Company, Java, C++, and more.
How to access & use the BigCommerce GraphQL Playground
Step 1: Access the playground
First, log in to your store to use the GraphQL Storefront API Playground and check out its documentation. Then, go to Settings, API, and Storefront API Playground.
Once you click on that, the GraphQL Storefront API Playground will pop up, ready for you to explore.
Note: If you can’t see the link for the Storefront API Playground, your store isn’t using a Stencil theme. To fix this, apply a Stencil theme, and you’ll be good to go, ready to delve into the GraphQL Storefront API.
Step 2: Use the playground
The GraphQL Playground is a handy tool for interacting with GraphQL APIs. To utilize its features, you start by entering your queries on the left side of the interface. These queries specify the data you want to retrieve from the API.
Once you’ve crafted your query, click the Play button near the top-left corner. This action sends your query to the API, and the results are displayed on the right side of the Playground. This real-time feedback loop lets you quickly test your queries and see the corresponding data.
Here’s a basic example of a query you might run in the GraphQL Playground: In this query, we’re asking for a list of products, and each product, we’re requesting its ID, name, and price.
query MyQuery {
site {
settings {
storeName
}
products {
edges {
node {
name
sku
prices {
retailPrice {
value
currencyCode
}
price {
value
currencyCode
}
}
}
}
}
}
}
If you’re not sure what queries are available or how to structure them, you can explore the GraphQL schema using the Docs and Explorer tabs on the right side of the Playground. The Docs tab provides detailed documentation for the API’s available types, fields, and operations.
Additionally, BigCommerce provides a GraphQL Explorer tool, allowing you to explore your data’s graph visually. This tool can be particularly useful for understanding the relationships between different data types and discovering available query options.
Step 3: Authentication process
Authentication with the GraphQL Storefront API involves JWT (JSON Web Token) bearer tokens sent via the HTTP Authorization header. This ensures that only authorized requests are accepted by the API. Token Creation To access the GraphQL Storefront API, you must generate a token through the “Create a storefront token” REST endpoint. This endpoint requires a token creation scope, which you can add to your store-level or app-level API account. These tokens act as keys to authenticate your requests to the API. By specifying the necessary parameters, such as the expiration time and allowed CORS origins, you can tailor the token to your specific authentication requirements.
→ Example request: Create a GraphQL Storefront API token
POST https://api.bigcommerce.com/stores//v3/storefront/api-token
x-auth-token:
accept: application/json
content-type: application/json
{
"channel_id": 1, // An integer representing the channel ID on the store where the token will be used. It must be a valid channel ID.
"expires_at": 86400000, // The expiration time of the token, specified as an integer Unix timestamp (in seconds).
"allowed_cors_origins": [ // An array of origins specifying the CORS (Cross-Origin Resource Sharing) origins that are allowed to use the token. Up to two origins per token are allowed. In this example, only https://mydomain.com is allowed.
"https://mydomain.com"
]
}
Related Posts
Auto-Generated Token Utilization in Stencil Themes
In Stencil themes, integrating tokens is made easier through auto-generation. These tokens are automatically passed to client code during theme rendering using Handlebars properties. You don’t have to manually generate tokens through the Admin API before utilizing the Storefront API in your Stencil theme. The auto-generated tokens typically have an expiry period of 24-48 hours and periodically rotate before expiration, ensuring continued access to the API.
Customer Impersonation Token Generation
Customer Impersonation Tokens are crucial in server-to-server and headless interactions with the GraphQL Storefront API. These tokens allow you to authenticate requests on behalf of any customer, enabling you to access store information from their perspective. However, handling these tokens carefully is important, as they are sensitive and should never be publicly exposed. They should be treated like other application secrets to maintain security. → Example request: Create a customer impersonation token
POST https://api.bigcommerce.com/stores//v3/storefront/api-token-customer-impersonation
x-auth-token:
accept: application/json
content-type: application/json
{
"channel_id": 1, // An integer representing the channel ID on the store where the token will be used. It must be a valid channel ID.
"expires_at": 86400000 // The expiration time of the token, specified as an integer Unix timestamp (in seconds).
}
Customer Login Process
The Customer Login mutation authenticates customer accounts. This mutation enables customers to sign in to their accounts using their email address and password. Upon successful authentication, a session cookie is set in the browser, authenticating subsequent requests to the storefront. Customer login provides a seamless and secure authentication mechanism for shoppers accessing the storefront, enhancing their user experience.
Step 4: Apply the GraphQL API to the BigCommerce storefront
To apply the GraphQL API to your BigCommerce storefront, you have a couple of options: you can make API calls directly from within a Stencil theme, or you can use scripts in the store’s Script Manager. Here’s an example of how you can make a GraphQL request using a Stencil auto-generated token and JavaScript’s Fetch API:
<script>
fetch('/graphql', {
method: 'POST',
credentials: 'same-origin',
headers: {
'Content-Type': 'application/json',
'Authorization': 'Bearer ' // use auto-generated token
},
body: JSON.stringify({
query: `query MyFirstQuery {
site {
settings {
storeName
}
products {
edges {
node {
name
sku
defaultImage {
url(width: 1280)
}
}
}
}
}
}`
})
})
.then(res => res.json())
.then(data => console.log(data)) // will log JSON result to browser console
.catch(error => console.error(error));
</script>
This script sends a GraphQL query to the specified endpoint (/graphql). It includes the necessary headers, such as the authorization token obtained from settings.storefront_api.token. The query fetches information about the site settings, including the store name and product details, such as their names, SKUs, and default image URLs. If you’re dealing with pagination for nodes that return multiple items, you can limit the number of items retrieved. You can find more information about pagination in the BigCommerce documentation. Additionally, consider using client libraries like Apollo, which offer features to simplify GraphQL implementations. These libraries provide declarative data fetching, state management, and caching, which can lead to more consistent UI components. Check out examples of adding Apollo Client to specific BigCommerce themes on GitHub if interested.
Benefits of GraphQL
Easy to expand query
In GraphQL, it is pretty simple to create a request. For example, you can make a request to retrieve a heroine like this:
{
heroine {
name
}
}
But, what can you do if your boss then requires her family members? Create one more call to the endpoint of her family members like heroines/family
as in RESTful API?
Actually, the key for it is much simpler, GraphQL empowers users to add more data required in their query. Hence, instead of getting another all, the query can be lengthened like:
{
heroine {
name
family members {
name
}
}
}
Strict in values
In fact, GraphQL is considered a strongly-typed language which means it will be harder for the data to be accepted. In addition, its explanation about the error is also understandable so that users can quickly find out the errors and fix them.
Access data in only one endpoint
There is only one endpoint for all requests in GraphQL. When you make changes to your front end, the back end will no longer need to be re-architectured every time, which helps users provide their customers the latest news in a rapid manner. It allows them to update the market trends and satisfy customer feedback without wrangling and tweaking the models and controllers.
About BigCommerce GraphQL
GraphQL in BigCommerce enables users to request storefront data from the Stencil theme or remote sites. Thus, you now can access data (that are unavailable via the Stencil objects) from the frontend Javascript instead of opening the backend from the template logic as before. As a result, you can implement multiple tasks, such as accessing product options, querying product images, getting customers’ information, seeking brands, constructing front-end apps, etc.
More than that, GraphQL can streamline the workflows and improve store’s performance by exploiting data from an API call. Users will be provided with all the benefits from the BigCommerce backend without compromising on the technology that can be used on the frontend. Thus, they will have more time and money to enhance the customer experience in their store.
Besides, you should keep in mind that BigCommerce GraphQL storefront API is still being developed so that only when reaching the necessary features to offer a full shopping experience do we remove its’ early access status. Also, you can see all the new functionalities in the Developer Changelog. Additionally, the GraphQl API is recently not supported in Blueprint themes.
GraphQL BigCommerce samples
To get the first three levels of category tree, users can use this:
query CategoryTree3LevelsDeep {
` site {`
` categoryTree {`
` …CategoryFields`
` children {`
` …CategoryFields`
` children {`
` …CategoryFields`
` }`
` }`
` }`
` }`
}
` `
fragment CategoryFields on CategoryTreeItem {
` name`
` path`
` entityId`
}
The response will be:
{
` “data”: {`
` “site”: {`
` “categoryTree”: [`
` {`
` “name”: “Kitchen”,`
` “path”: “/kitchen/”,`
` “entityId”: 27,`
` “children”: []`
` },`
` {`
` “name”: “Publications”,`
` “path”: “/publications/”,`
` “entityId”: 26,`
` “children”: []`
` },`
` {`
` “name”: “Shop All”,`
` “path”: “/shop-all/”,`
` “entityId”: 23,`
` “children”: []`
` },`
` {`
` “name”: “Utility”,`
` “path”: “/utility/”,`
` “entityId”: 25,`
` “children”: []`
` },`
` {`
` “name”: “Garden”,`
` “path”: “/garden/”,`
` “entityId”: 19,`
` “children”: [`
` {`
` “name”: “Bath”,`
` “path”: “/garden/bath/”,`
` “entityId”: 24,`
` “children”: []`
` }`
` ]`
` }`
` ]`
` }`
` }`
}
Final thoughts
In conclusion, it can’t be denied that GraphQL is a useful way to help people get the necessary data in a short time. In fact, GraphQL is still a feature-incomplete in BigCommerce, but it can help you a lot to develop your business. BigCommerce users will save lots of time for accessing information and use this amount of time for other essential things.