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:
Query Type: The
Query
type defines the entry point for fetching data. In this example, there are two fields:hello
anduser
. Thehello
field returns aString
, and theuser
field accepts anid
argument and returns aUser
object.Mutation Type: The
Mutation
type defines the entry point for modifying data. In this example, there is one mutation field:createUser
. It acceptsname
andemail
arguments and returns aUser
object.User Type: The
User
type represents an object with three fields:id
,name
, andemail
. Each field has a scalar type (ID
andString
), 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! }
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" } } }
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.
0 Comments