Module graphql

ballerina/graphql
Overview
This module provides APIs for connecting and interacting with GraphQL endpoints.
GraphQL is an open-source data query and manipulation language for APIs. GraphQL allows clients to define the structure of the data required and the same structure of the data is returned from the server, preventing the returning of excessively large amounts of data.
The Ballerina GraphQL implementation is using HTTP as the underlying protocol.
Listener
The graphql:Listener
is used to listening to a given IP/Port. To create a graphql:Listener
, an http:Listener
or a port number can be used.
Create a standalone graphql:Listener
Create a graphql:Listener
using an http:Listener
Additional configurations
When initializing the Ballerina GraphQL listener, a set of additional configurations can be provided to configure the listener including security and resiliency settings.
The configurations that can be passed for this are defined in the graphql:ListenerConfiguration
record.
Service
The Ballerina GraphQL service represents the GraphQL schema. When a service is attached to a graphql:Listener
, a GraphQL schema will be auto-generated.
The GraphQL services are exposed through a single endpoint. The path of the GraphQL service endpoint can be provided via the service path of the GraphQL service. The endpoint of the following Ballerina GraphQL service will be /graphql
.
The GraphQL service endpoint URL will be <host>:<port>/graphql
.
Alternatively, a Ballerina graphql service can not have a path, in which case the endpoint will be the host URL and the port as the following example.
The GraphQL service endpoint URL will be <host>:<port>
Query type
The resource
functions inside the GraphQL service can represent the resolvers of the Query
root type.
When a resource
function is defined inside a GraphQL service with the get
accessor, the generated schema will have a Query
root type and the resource
function will be a field of the Query
object.
Note: A GraphQL service must have at least one resource function defined. Otherwise, it will result in a compilation error.
The accessor of the resource
function should always be get
for a field to be considered as a Query
field. The resource
function name will become the name of the particular field in the GraphQL schema. The return type of the resource
function will be the type of the corresponding field.
The above can be queried using the GraphQL document below:
The result will be the following JSON.
Mutation type
The remote
functions inside the GraphQL service represent the resolvers of the Mutation
root type.
When a remote
function is defined inside a GraphQL service, the schema will have a Mutation
operation and the remote
function will be a field of the Mutation
object.
For example, consider the following service that has a Person
record named person
. It has a Query
field named profile
, which returns the person
record. It also has two remote
functions named updateName
and updateCity
, which are used as mutations.
This will generate the following schema:
Note: A GraphQL schema must have a root
Query
type. Therefore, a Ballerina GraphQL service must have at least oneresource
function defined.
This can be mutated using the following document.
Note: This document uses two mutations and each mutation requests the same fields from the service using a fragment (
ProfileFragment
).
Result:
See how the result changes the Person
record. The first mutation changes only the name and it populates the result of the updateName
field. Then, it will execute the updateCity
operation and populate the result. This is because the execution of the mutation operations will be done serially in the same order as they are specified in the document.
Subscription Type
The subscription type can be used to continuously fetch the data from a GraphQL service.
The resource
functions inside the GraphQL service with the subscribe
accessor can represent the resolvers of the Subscription
root type.
When a resource
function is defined inside a GraphQL service with the subscribe
accessor, the generated schema will have a Subscription
root type and the resource
function will be a field of the Subscription
object.
The accessor of the resource
function should always be subscribe
for a field to be considered as a Subscription
field. The resource
function name will become the name of the particular field in the GraphQL schema. The return type of the resource
function will be the type of the corresponding field.
The resource
functions that belongs to Subscription
type must return a stream of any
type. Any other return type will result in a compilation error.
The return type
The above can be queried using the GraphQL document below:
When a subscription type is defined, a websocket service will be created to call the subscription. The above service will create the service as follows:
This can be accessed using a websocket client. When the returned stream has a new entry, it will be broadcasted to the subscribers.
Additional configurations
Additional configurations of a Ballerina GraphQL service can be provided using the graphql:ServiceConfig
.
These configurations include security-related configurations for the GraphQL service.
Security configurations
A GraphQL service can be secured by setting the auth
field in the graphql:ServiceConfig
. Ballerina GraphQL services support Basic Authentication, JWT Authentication, and OAuth2 Authentication.
Maximum query depth
When a maximum query depth is provided, all the queries exceeding that limit will be rejected at the validation phase and will not be executed.
The above service only accepts queries of less than 2 levels. For an example, consider the following document:
The result for the above query is the following JSON:
Context init
This field is used to initialize the graphql:Context
object. Usage of the graphql:Context
will be described in a separate section.
Context
The graphql:Context
can be used to pass meta-information among the graphql resolver (resource
/remote
) functions. It will be created per each request, with a defined set of attributes. Attributes can be stored in the graphql:Context
object using key-value pairs. The key should always be a string
. The type of the value is value:Cloneable|isolated object {}
. This means the values can be any immutable type, readonly
value, or an isolated object. These attributes can be set using a function, which can be given as a service configuration parameter.
Context init
The graphql:Context
can be initialized using a function. The function signature is as follows:
The values from the http:RequestContext
and the http:Request
can be set as attributes of the graphql:Context
since they are passed as arguments for this function. Then the function should be provided as a graphql:ServiceConfig
parameter.
Following are examples for providing the context init function.
Provide the init function directly
Provide the init function as a function pointer
Note: Even if the context init function is not provided, a default, empty context will be created per each request.
Use the context in resolver functions
If the graphql:Context
needs to be accessed, the resolver function has to add it as the first parameter of the function.
Following is an example:
This is similar to any remote
function, or a resource
function inside a service object used as a GraphQL object type.
Retrieve attributes from the context
There are two methods to retrieve attributes from the graphql:Context
.
get()
function
This will return the value of the attribute using the provided key. If the key does not exist, it will return a graphql:Error
.
remove()
function
This function will remove the attribute for a provided key, and return the value. If the key does not exist, it will return a graphql:Error
.
Note: Even though this is supported, destructive-modification of the
graphql:Context
is discouraged. This is because these modifications may affect the parallel executions in queries.
Types
The Ballerina GraphQL resources can return the following types:
Return types
Scalar types
The following Ballerina types are considered as Scalar types:
int
string
boolean
float
This can be queried using the following document:
Result:
Enums
When a resource
or a remote
function returns an enum
value, it will be mapped to a GraphQL ENUM
type.
The above service will generate the following GraphQL schema.
Record types
When a resource
function is returning a record
type, each field of the record can be queried separately.
Each record
type is mapped to a GraphQL OBJECT
type and the fields of the record
type are mapped to the fields of the OBJECT
type.
This will generate the following schema.
This can be queried using the following document:
Result:
Each field can be queried separately as shown in the following document:
Result:
Service types
When a resource
function returns a service type, the service type is mapped to a GraphQL OBJECT
type and the resource
functions of the service type will be mapped as the fields of the OBJECT
.
When a service type is returned from a graphql:Service
, the returning service type should also follow the rules of the graphql:Service
explained above.
This will generate the following schema:
This can be queried using the following document:
The above will result in the following JSON:
Arrays
A GraphQL resource
function can return an array of the types mentioned above. When a resource
function is returning an array, the result will be a JSON array.
This will generate the following schema:
This can be queried using the following document:
Result:
Note: Each element in the array consists only of the required
name
field.
Optional types
A Ballerina GraphQL resource
function can return an optional type. When the return value is ()
, the resulting field in the JSON will be null
.
This will generate the following schema:
This can be queried using the following document:
Result:
If the following document is used:
This will be the result:
Union types
The Ballerina GraphQL service can return a union of distinct service types. This will be mapped to a GraphQL UNION
type.
Note: Since Ballerina supports union types by nature, directly returning a union type is also allowed (but not recommended). The recommended way is to define a union type name separately and then use that type name as shown in the following example. If a union type is returned directly without providing a type name (
returns T1|T2|T3
), the type name will beT1_T2_T3
.
This will generate the following schema:
This can be queried using the following document:
The result will be:
If the following document is used:
The result will be:
Errors
A Ballerina GraphQL resource
function can return an error
with the union of the types mentioned above.
Note: A
resource
or aremote
function cannot return only anerror
, any subtype of anerror
, or, anerror?
, which will result in a compilation error.
This can be queried using the following document:
Result:
Hierarchical resource paths
A resource
function inside a GraphQL service can have hierarchical paths.
When a hierarchical path is present, each level of the hierarchical path maps to the GraphQL field of the same name, and the type of that field will be mapped to an OBJECT
type with the same name.
The above service will create the following schema:
Note: The field name and the type names are equal.