Skip to main content

Triggers

The ballerina/graphql module provides a full GraphQL server framework. You define a Ballerina service with resource and remote functions, and the module automatically generates the GraphQL schema and serves it over HTTP. Subscriptions are served over WebSocket.

Three components work together:

ComponentRole
graphql:ListenerAn HTTP/WebSocket listener that serves the GraphQL API and routes incoming operations to the appropriate service functions.
graphql:ServiceA Ballerina service that defines GraphQL resolvers: resource functions for queries, remote functions for mutations, and subscribe resource functions for subscriptions.
graphql:ContextA per-request context object for passing data between interceptors and resolvers, and for managing DataLoaders and cache.

For action-based operations, see the Action Reference.


Listener

The graphql:Listener establishes the connection and manages event subscriptions.

Configuration

The listener supports the following connection strategies:

Config TypeDescription
ListenerConfigurationConfigures the underlying HTTP listener. Inherits all fields from http:ListenerConfiguration.

ListenerConfiguration fields:

FieldTypeDefaultDescription
hoststring"0.0.0.0"The network interface to bind to.
secureSocketListenerSecureSocket?()SSL/TLS configuration for HTTPS.
httpVersionHttpVersionHTTP_2_0HTTP protocol version.
timeoutdecimal60Request idle timeout in seconds.
serverstring?()Server header value.
requestLimitsRequestLimitConfigs{}Request size limit configuration.

Initializing the listener

Initialize with a port number:

import ballerina/graphql;

listener graphql:Listener graphqlListener = new (9000);

Initialize with HTTPS configuration:

import ballerina/graphql;

listener graphql:Listener graphqlListener = new (9000, secureSocket = {
key: {
certFile: "./cert.pem",
keyFile: "./key.pem"
}
});

Inline listener in service declaration:

import ballerina/graphql;

service /graphql on new graphql:Listener(9000) {
resource function get greeting() returns string {
return "Hello, World!";
}
}

Service

A GraphQL service is a standard Ballerina service attached to a graphql:Listener. The module maps your Ballerina functions directly to GraphQL schema fields: resource function get for Query fields, remote function for Mutation fields, and resource function subscribe for Subscription fields.

Callback signatures

FunctionSignatureDescription
Query resolverresource function get fieldName(args...) returns ReturnTypeDefines a Query field. The function name becomes the field name, parameters become field arguments, and the return type maps to the GraphQL output type.
Mutation resolverremote function mutationName(args...) returns ReturnTypeDefines a Mutation field. Remote functions are exposed as mutation operations in the schema.
Subscription resolverresource function subscribe fieldName(args...) returns stream<ReturnType, error?>Defines a Subscription field. Must return a stream: each value emitted by the stream is pushed to the subscribed client over WebSocket.
note

You do not need to write a GraphQL schema file. The module generates the schema automatically from your service definition, including all types, fields, arguments, and documentation.

Full usage example

import ballerina/graphql;
import ballerina/log;

// In-memory data store
type News record {|
string title;
string content;
string author;
|};

News[] newsTable = [];

@graphql:ServiceConfig {
graphiql: {
enabled: true
}
}
service /graphql on new graphql:Listener(9000) {
// Query: fetch all news articles
resource function get news() returns News[] {
return newsTable;
}

// Mutation: publish a new article
remote function publish(string title, string content, string author) returns News {
News news = {title, content, author};
newsTable.push(news);
log:printInfo("Published article", title = title);
return news;
}

// Subscription: receive real-time news updates
resource function subscribe news() returns stream<News, error?> {
return newsTable.toStream();
}
}
note

Use the @graphql:ServiceConfig annotation to configure features like GraphiQL (graphiql: {enabled: true}), authentication (auth), CORS (cors), interceptors (interceptors), caching (cacheConfig), query complexity limits (queryComplexityConfig), and introspection control (introspection).


Supporting types

GraphqlServiceConfig

FieldTypeDescription
maxQueryDepthint?Maximum allowed query depth. Queries exceeding this depth are rejected.
authListenerAuthConfig[]?Authentication configuration. Supports file user store, LDAP, JWT, and OAuth2 introspection.
contextInitContextInitA function that initializes the graphql:Context for each request. Receives the HTTP request context and request object.
corsCorsConfig?CORS configuration for the GraphQL endpoint.
graphiqlGraphiqlGraphiQL interactive IDE configuration. Set enabled: true to serve the GraphiQL interface.
interceptors(readonly & Interceptor)|(readonly & Interceptor)[]Global interceptors applied to all resolver executions.
introspectionbooleanEnable or disable schema introspection. Defaults to true.
validationbooleanEnable or disable server-side query validation. Defaults to true.
cacheConfigServerCacheConfig?Server-side response caching configuration with maxAge and maxSize settings.
queryComplexityConfigQueryComplexityConfig?Query complexity analysis with maxComplexity, defaultFieldComplexity, and warnOnly settings.

Context

FieldTypeDescription
set(key, value)methodStores a value in the context, accessible by resolvers and interceptors downstream.
get(key)methodRetrieves a previously stored value from the context by key.
remove(key)methodRemoves a value from the context by key.
registerDataLoader(key, dataLoader)methodRegisters a DataLoader instance for batch loading and caching.
getDataLoader(key)methodRetrieves a registered DataLoader by key.
invalidate(path)methodInvalidates the server-side cache for a specific field path.
invalidateAll()methodClears all entries from the server-side cache.

Upload

FieldTypeDescription
fileNamestringThe name of the uploaded file.
mimeTypestringThe MIME type of the uploaded file.
encodingstringThe encoding of the uploaded file.
byteStreamstream<byte[], io:Error?>A byte stream for reading the file content.