乐闻世界logo
搜索文章和话题

How to Use Variables in GraphQL?

浏览0
2月7日 10:59

In GraphQL, variables are used to dynamically pass parameters in queries or mutations. This approach allows you to reuse the same query or mutation definition with different data values, making the query structure more readable and helping to prevent injection attacks.

How to Use Variables

  1. Define Variables: In queries or mutations, first declare variables and their types after the operation type. For example, if you want to retrieve user information by ID, you can write:
graphql
query GetUser($id: ID!) { user(id: $id) { name email } }

Here, $id is the variable, and ID! indicates it is a non-null ID type.

  1. Pass Variables: When sending a query, you need to provide specific variable values in the variables section of the request. For example, in the above query, you can pass the following JSON object:
json
{ "id": "123" }

This JSON object specifies that the variable $id has the value '123'.

By using variables, GraphQL queries can handle different data requirements more flexibly and securely.

标签:GraphQL