Schema Of GraphQL

 In GraphQL, the schema serves as the contract between the client and the server, defining the types of data that can be queried and manipulated. Here's an example of a simple GraphQL schema:

type Query { hello: String user(id: ID!): User } type Mutation { createUser(name: String!, email: String!): User } type User { id: ID! name: String! email: String! }

Let's break down this schema:

  1. Query Type: The Query type defines the entry point for fetching data. In this example, there are two fields: hello and user. The hello field returns a String, and the user field accepts an id argument and returns a User object.

  2. Mutation Type: The Mutation type defines the entry point for modifying data. In this example, there is one mutation field: createUser. It accepts name and email arguments and returns a User object.

  3. User Type: The User type represents an object with three fields: id, name, and email. Each field has a scalar type (ID and String), and the exclamation mark (!) denotes that these fields are non-nullable.

This schema allows clients to perform queries to fetch data (Query type) and mutations to modify data (Mutation type) related to users (User type). The schema defines the structure and capabilities of the GraphQL API, enabling clients to interact with the server effectively.

Suppose you have a GraphQL server set up with the schema provided:

type Query { hello: String user(id: ID!): User } type Mutation { createUser(name: String!, email: String!): User } type User { id: ID! name: String! email: String! }


  1. Querying Data:

    • To query the hello field, you would send a GraphQL query like this:

      query { hello }

      And the server would respond with:

      { "data": { "hello": "Hello, world!" } }
    • To query a specific user by ID, you would send a query like this:

      query { user(id: "123") { id name email } }

      And the server would respond with:

    • { "data": { "user": { "id": "123", "name": "John Doe", "email": "john@example.com" } } }


  2. Mutating Data:

    • To create a new user, you would send a mutation like this:
    • mutation { createUser(name: "Alice", email: "alice@example.com") { id name email } }

    • And the server would respond with:
    • { "data": { "createUser": { "id": "456", "name": "Alice", "email": "alice@example.com" } } }

In these examples, we've performed queries to fetch data (hello and user) and a mutation to create a new user (createUser). The GraphQL server responds with the requested data or performs the mutation and returns the updated data, adhering to the schema defined earlier.

Post a Comment

0 Comments