GraphQL is a query language for APIs that allows clients to request exactly the data they need. Unlike REST, which has multiple endpoints for different resources, GraphQL operates on a single endpoint. This flexibility makes testing GraphQL APIs essential for developers.
New
> Request
.GET
to POST
, as GraphQL typically uses POST requests.https://api.example.com/graphql
).To fetch data from a GraphQL API, you need to structure your query as follows:
{
"query": "{ users { id name email } }"
}
Body
tab, select raw
and choose JSON
from the dropdown menu.Send
to execute the request.You should receive a response similar to this:
{
"data": {
"users": [
{ "id": "1", "name": "Alice", "email": "alice@example.com" },
{ "id": "2", "name": "Bob", "email": "bob@example.com" }
]
}
}
GraphQL allows the use of variables to make your queries more dynamic. Here’s how to do that in Postman:
{
"query": "query GetUser(\(id: ID!) { user(id: \)id) { name email } }",
"variables": { "id": "1" }
}
Body
type to raw
and JSON
.Send
to execute the request.This will return data for the user with the specified ID:
{
"data": {
"user": { "name": "Alice", "email": "alice@example.com" }
}
}
GraphQL also supports mutations for creating or updating data. Here’s how to test a mutation:
{
"query": "mutation CreateUser(\(input: UserInput!) { createUser(input: \)input) { id name } }",
"variables": { "input": { "name": "Charlie", "email": "charlie@example.com" } }
}
Body
tab, select raw
and choose JSON
.Send
to execute the request.You should receive a confirmation response:
{
"data": {
"createUser": { "id": "3", "name": "Charlie" }
}
}
Testing GraphQL APIs with Postman is straightforward and efficient. By following the examples provided, you can easily create queries and mutations, allowing you to interact with your GraphQL endpoints effectively. As you become more familiar with GraphQL, you’ll find that Postman is a powerful tool for API testing.