GraphQL Basics
What is GraphQL?
GraphQL is a query language for APIs that allows clients to request exactly the data they need.
GraphQL vs REST
| Feature | REST | GraphQL |
|---|---|---|
| Endpoints | Multiple | Single |
| Data Fetching | Fixed structure | Flexible |
| Over-fetching | Common | Prevented |
| Under-fetching | Common | Prevented |
GraphQL Endpoint
# Magento GraphQL endpoint
POST https://store.com/graphql
# With store code
POST https://store.com/{store_code}/graphql
Query Example
query {
products(filter: { sku: { eq: "SKU-123" } }) {
items {
name
sku
price {
regularPrice {
amount {
value
}
}
}
}
}
}
Response
{
"data": {
"products": {
"items": [
{
"name": "Test Product",
"sku": "SKU-123",
"price": {
"regularPrice": {
"amount": {
"value": 29.99
}
}
}
}
]
}
}
}
Schema and Types
GraphQL Schema
type Product {
id: ID!
name: String!
sku: String!
price: ProductPrice
description: String
image: ProductImage
}
type ProductPrice {
regularPrice: Price
finalPrice: Price
}
type Price {
amount: Money
}
type Money {
value: Float!
currency: String!
}
# Query type
type Query {
products(filter: ProductFilterInput): ProductSearchResult
product(sku: String!): Product
}
# Input types
input ProductFilterInput {
sku: FilterEqualTypeInput
name: FilterMatchTypeInput
}
input FilterEqualTypeInput {
eq: String
in: [String]
}
Scalar Types
| Type | Description |
|---|---|
Int |
Integer |
Float |
Decimal number |
String |
Text |
Boolean |
True/false |
ID |
Unique identifier |
Object Types
type Customer {
id: ID!
email: String!
firstname: String!
lastname: String!
addresses: [CustomerAddress]
}
type CustomerAddress {
id: ID!
street: [String]!
city: String!
region: Region!
postcode: String!
country: Country!
}
Queries
Basic Query
query {
products {
items {
name
sku
price {
regularPrice {
amount {
value
}
}
}
}
}
}
Query with Arguments
query {
product(sku: "SKU-123") {
name
sku
description
price {
regularPrice {
amount {
value
currency
}
}
}
}
}
Query with Filters
query {
products(
filter: {
name: { match: "shirt" }
price: { from: "10" to: "50" }
}
sort: { price: ASC }
pageSize: 10
currentPage: 1
) {
total_count
items {
name
sku
price {
regularPrice {
amount {
value
}
}
}
}
page_info {
page_size
current_page
}
}
}
Named Query
query GetProductBySku($sku: String!) {
product(sku: $sku) {
name
sku
price {
regularPrice {
amount {
value
}
}
}
}
}
# Variables
{
"sku": "SKU-123"
}
Mutations and Resolvers
Mutation Example
mutation {
addSimpleProductsToCart(
input: {
cartId: "cart123",
cartItems: [
{
data: {
quantity: 1
sku: "SKU-123"
}
}
]
}
) {
cart {
items {
product {
name
sku
}
quantity
}
}
}
}
Resolver Structure
<?php
namespace Vendor\Module\GraphQl\Resolver;
use Magento\Framework\GraphQl\Config\Element\Field;
use Magento\Framework\GraphQl\Schema\Type\ResolveInfo;
use Magento\Framework\GraphQl\Resolver\ResolverInterface;
class ProductResolver implements ResolverInterface
{
public function resolve(
Field $field,
$context,
ResolveInfo $info,
array $value = null,
array $args = null
) {
$productId = $value['product_id'];
$product = $this->productRepository->getById($productId);
return [
'name' => $product->getName(),
'sku' => $product->getSku(),
'price' => $product->getPrice()
];
}
}
Resolver Configuration
<!-- etc/schema.graphqls -->
<config>
<type name="Query">
<field name="product" resolver="Vendor\Module\GraphQl\Resolver\ProductResolver"/>
</type>
</config>
Resolver for Custom Type
public function resolve(
Field $field,
$context,
ResolveInfo $info,
array $value = null,
array $args = null
) {
return [
'id' => $value['id'],
'name' => $value['name'],
'email' => $value['email'],
'created_at' => $value['created_at']
];
}
Quiz
1. What is the GraphQL endpoint in Magento?
2. What does GraphQL prevent?
3. What is a GraphQL resolver?
Flashcards
Question
What is the GraphQL endpoint?
Click to reveal answer
Answer
/graphql
Question
What does GraphQL prevent?
Click to reveal answer
Answer
Over-fetching and under-fetching
Question
What is a resolver?
Click to reveal answer
Answer
A function that returns data for a field
Question
What are GraphQL scalar types?
Click to reveal answer
Answer
Int, Float, String, Boolean, ID
Question
How do you define a query?
Click to reveal answer
Answer
Use the Query type in schema
Revision Notes
Key Takeaways
- 1. GraphQL provides flexible data fetching
- 2. Schema defines types and operations
- 3. Queries read data, mutations write data
- 4. Resolvers provide data for fields
- 5. Variables allow parameterized queries
Interview Tips
- • Explain GraphQL vs REST differences
- • Know the GraphQL schema structure
- • Discuss query and mutation patterns
- • Be ready to write GraphQL queries
Cheat Sheet
Endpoint: POST /graphql
Query:
query {
products {
items {
name
sku
}
}
}
Mutation:
mutation {
addProductsToCart(input: {...}) {
cart { items { ... } }
}
}
Schema:
type Product {
name: String!
sku: String!
}