I want to include some changes in default graphql response but no idea how can I do that and what is the right way to do that as there is not documentation available there. Do I have to create always new graphql APIs(without referencing old one) in order or extend prev. one.
Please let me know if anyone has already done this.
Thanks
Best Answer
If I am not wrong you meant to ask What if we’re adding a custom attribute, e.g., an attribute we’ve added to the database? And how we gonna deal with making that attribute available to GraphQL. So let's proceed with an example:
Let’s assume you want to add the parent_item_id as an attribute available through the GraphQL Quote Endpoint.Now, you may already be aware, parent_item_id is an existing field (it’s not a new database attribute). But currently, it’s not supported through the native GraphQL Quote Endpoint – so it’s not accessible via GraphQL responses. We’ll walk through a simple example to add it:
First, We’ll create a module:
Next, We’ll add our etc/schema.graphqls file:
Now, refresh your database / cache:
php bin/magento setup:upgrade
…That’s it! On the client side, We can send a GraphQL query that looks like this:
query { cart { items { parent_item_id } } }
(Obviously in a real-world scenario, you would request additional information).
Now, the only point that confusing at first glance is the interface definition in the schema.graphqls file. …Where did we get that? Well, if you look in the native Quote graphql module:
You can see above, that by default Magento 2 does several things:
Defines the fields available through GraphQL for each of them.
So, by default, the only available fields for an item are id, quantity, product — the last of which is a complex ProductInterface type
In our custom module, all we did was copy the interface definition and start adding new properties to it.