How to Get Customer Details Using GraphQL in Magento 2?
Magento 2’s GraphQL API allows you to easily retrieve customer details such as their name, email, and addresses. This tutorial shows you how to do it with a simple GraphQL query.
Prerequisites:
- Magento 2.3.x or higher
- A customer logged in
Step 1: Get the Customer Token
To access customer data, you first need a customer token for authentication. You can generate it with the customer’s email and password.
Generate Customer Token:
mutation {
generateCustomerToken(
email: "[email protected]"
password: "customer_password"
) {
token
}
}
Step 2: Query Customer Details
Once you have the token, use it to request customer data. Here’s a simple GraphQL query to get the customer’s name, email, and address:
query {
customer {
firstname
lastname
email
addresses {
id
street
city
postcode
country {
code
}
}
}
}
Step 3: Send the Request
Now, send a POST request to the /graphql
endpoint, passing the token in the Authorization header.
curl -X POST https://yourmagentostore.com/graphql \
-H "Authorization: Bearer {customer_token}" \
-H "Content-Type: application/json" \
-d '{"query": "query { customer { firstname lastname email addresses { id street city postcode country { code } } } }"}'
Step 4: Response
The response will look like this:
{
"data": {
"customer": {
"firstname": "John",
"lastname": "Doe",
"email": "[email protected]",
"addresses": [
{
"id": 1,
"street": ["123 Main St"],
"city": "Los Angeles",
"postcode": "90001",
"country": { "code": "US" }
}
]
}
}
}
Conclusion
By using GraphQL, you can quickly fetch customer details with minimal effort. Simply generate the token, run a query, and you’ll have the data you need in a clean format.