I'm a fan of Magento 2.3 its new GraphQL layer. However, I often hear that people are still waiting for things to be completed. Perhaps I'm not seeing those problems that they are facing, but to me, creating and extending GraphQL is easy and doable. To demonstrate this, here's a little simple Yireo_AdditionalEndpointsGraphQl module to get you going.
Creating a new GraphQL endpoint
To create a new endpoint, one needs to build a Magento 2 module: Simply create a registration.php
and etc/module.xml
file, run bin/magento module:enable Your_NewModule
and you are good to go. Next, an etc/schema.graphqls
file is needed, connecting your GraphQL schema to a PHP resolver class. I'm not going to mention how to do this - there's already plenty of tutorials out there to get you going.
The main point is that it is easy to create a new endpoint. The only danger is that it might be hard to include the right PHP dependencies in your PHP resolver, because not every Magento data entity is nicely hooked to repositories or data providers.
An example to get you going
The number of GraphQL endpoints that I have created for myself, Yireo extensions or third party projects is probably numbering over 30 already. I have bundled a couple of them together in a little module - Yireo_AdditionalEndpointsGraphQl
- that offers the following endpoints:
-
cmsBlock
- By default, Magento allows you to fetch a list of blocks viacmsBlocks
. But what if you only want to fetch a single CMS block? -
cmsPages
- By default, Magento allows you to fetch only a single page. This endpoint fetches all pages. Handy for generating menus. -
cmsWidget
- This new endpoint returns a Widget Instance, including its rendered HTML. There might be some dark magic in here that will not work with all widgets. -
productBySku
- Fetch a single product by its SKU. -
productById
- Fetch a single product by its database ID. -
validateCustomerToken
- This endpoint validates whether a customer token is still valid. Within a PWA environment, a customer token is best seen as a replacement of the customer session ID. Unfortunately, there was no way to validate the token once it expired (or simply is invalid). This endpoint fixes this and makes it easier to build PWA workflows with customer tokens.
Feel free to open a GitHub Issue if you bump into issues with these endpoints.
Which GraphQL endpoints are you missing?
There might be numerous endpoints that could be created. The main purpose of this blog is to share with you some of the endpoints I created - and the total amount of time invested into this is less than 4 hours. So, from my point of view at least, it is kind of easy to create new endpoints in GraphQL.
Which GraphQL endpoints are you missing?
About the author
Jisse Reitsma is the founder of Yireo, extension developer, developer trainer and 3x Magento Master. His passion is for technology and open source. And he loves talking as well.