-
Notifications
You must be signed in to change notification settings - Fork 0
Defining the schema
GraphQL works with schema definitions to serve client requests. Theses schemas have to be defined in files with extenstions .graphqls
and can be present anywhere on the classpath. Spring boot automatically locates these schema files.
GraphQL queries work on schemas for an API. For example, below schema represents Employee model.
type Employee {
employeeId: Int!
firstName: String
address: Address
}
Here, employeeId, firstName and address represents fields defined in Employee model. Address is a composite field which represents another type.
type Address{
city: String
state: String
country: String
zip: Int!
}
"!" means the field is required.
Queries are like the REST endpoints which cater user requests. However, GraphQL typically exposes only one endpoint http://<host>:<port>/graphql
. Client has to send more data(query) in body/query parameters for what it needs.
Sample query configurations:
type Query{
employee(employeeId: Int): Employee
city(city: String): Address
}
Here, employee is query name which accepts integer employeeId and returns Employee object. Same can be tested with below input in API call
query{
employee(employeeId: 1){
employeeId
address{
city
}
}
}
Above query returns employee with ID=1 with only selected elements to client i.e. employeeId and city from address. Sample response:
{
"data": {
"employee": {
"employeeId": 1,
"address": {
"city": "ABC"
}
}
}
}
GraphQL also provides a way to modify data through Mutations. For example, below mutation allows user to add new employee to database/collection.
type Mutation{
addEmployee(employeeId: Int!, firstName: String!, lastName: String!, department: String): Employee
}
Overall, with reference to above configuration, final schema file should look like
#Schema definition to map query and mutation to respective definitions.
schema {
query: Query
mutation: Mutation
}
type Employee {
employeeId: Int!
firstName: String
lastName: String
department: String
address: Address
}
type Address{
city: String
state: String
country: String
zip: Int!
}
type Query{
employee(employeeId: Int): Employee
employeeByFirstName(firstName: String): [Employee]
city(city: String): Address
}
type Mutation{
addEmployee(employeeId: Int!, firstName: String!, lastName: String!, department: String): Employee
}