Usage
magento-2Headers, variáveis, fragments, erros e padrões práticos ao consumir o GraphQL.
/graphql?headers
Headers, variables, fragments, error handling
Important HTTP headers
Content-Type: application/json— sempre.Authorization: Bearer <token>— customer token (quando necessário).Store: <store_code>— escolhe o store view. Ex.:Store: pt_br.Content-Currency: <ISO>— sobrescreve a moeda padrão da store.X-Magento-Cache-Id— ID de cache para requests autenticados. Melhora hit rate do Varnish.Preview-Version— ativa preview de conteúdo agendado (staging).
Variables
Ao invés de interpolar valores na string da query, use variables. O request body:
{
"query": "query Product($sku: String!) { products(filter: { sku: { eq: $sku } }) { items { name price { regular_price { value } } } } }",
"variables": { "sku": "TSHIRT-001" }
}
Fragments
Reduza duplicação agrupando campos comuns em um fragment:
query {
products(search: "bag") {
items {
...ProductCard
}
}
}
fragment ProductCard on ProductInterface {
sku
name
price_range {
minimum_price { final_price { value currency } }
}
image { url label }
}
Error handling
GraphQL sempre retorna HTTP 200 (inclusive em erros). Os erros aparecem no array errors ao lado de data:
{
"errors": [
{
"message": "Field 'xxx' is not defined on type 'ProductInterface'.",
"locations": [{ "line": 2, "column": 5 }],
"extensions": { "category": "graphql" }
}
],
"data": null
}
Categorias comuns de erro:
graphql-authentication— token inválido/expirado.graphql-authorization— sem permissão.graphql-input— parâmetros inválidos.graphql-no-such-entity— recurso não encontrado.
Dica (PT-BR): sempre trate ambos data e errors — uma query pode ter sucesso parcial (retornar alguns itens mas errar em outros).
/graphql?auth
Authentication mutations (token, revoke, create account)
Authentication mutations
Generate customer token
mutation {
generateCustomerToken(
email: "john@example.com"
password: "SecurePass123"
) {
token
}
}
Revoke customer token
mutation {
revokeCustomerToken {
result
}
}
Create customer account
mutation {
createCustomerV2(
input: {
firstname: "John"
lastname: "Doe"
email: "john@example.com"
password: "SecurePass123"
is_subscribed: true
}
) {
customer {
firstname
lastname
email
}
}
}
Dica (PT-BR): createCustomer está deprecated desde o Magento 2.4.4 — use createCustomerV2.