What is difference between Mutation and Query ?
What is difference between Mutation and Query ?
The difference between a Mutation and a Query in GraphQL lies primarily in their purpose and execution behavior.
Query: A Query is used to fetch data from the server. It is analogous to a GET
request in REST APIs. Queries are read-only operations and do not modify the server's state. They are used when you need to retrieve specific data from the server without making any changes to it[2][4][7][14].
Mutation: A Mutation is used to modify data on the server. This includes creating, updating, or deleting data. Mutations are analogous to POST
, PUT
, PATCH
, and DELETE
requests in REST APIs. They are used when you need to change the state of the server or persist new data[1][2][5][6].
Query: The syntax for a query typically starts with the query
keyword, although this keyword is optional. Queries specify the fields to be fetched and can include arguments to filter or customize the data retrieval.
query {
user(id: "1") {
name
email
}
}
This query fetches the name
and email
of a user with a specific id
[4][7][14].
Mutation: The syntax for a mutation starts with the mutation
keyword. Mutations specify the operation to be performed and the data to be modified. They often include arguments to specify the data to be changed.
mutation {
createUser(name: "John Doe", email: "john.doe@example.com") {
id
name
}
}
This mutation creates a new user and returns the id
and name
of the newly created user[1][5][10].
Query: Queries can be executed in parallel. This means that multiple query fields can be resolved simultaneously, which can improve performance when fetching data[3][9].
Mutation: Mutations are executed serially, one after the other. This ensures that each mutation is completed before the next one begins, preventing race conditions and ensuring data consistency[3][9].
Query: Queries return the data specified in the request. The structure of the response mirrors the structure of the query, ensuring that clients receive exactly what they asked for[4][7][14].
Mutation: Mutations also return data, typically the new or updated st...
junior
Gợi ý câu hỏi phỏng vấn
Chưa có bình luận nào