graphql
Modules
Module graphql
API
Declarations
Definitions

ballerina/graphql Ballerina library
Functions
__addError
function __addError(Context context, ErrorDetail errorDetail)
Adds an error to the GraphQL response. Using this to add an error is not recommended.
Parameters
- context Context - The context of the GraphQL request.
- errorDetail ErrorDetail - The error to be added to the response.
getSdlString
Obtains the schema representation of a federated subgraph, expressed in the SDL format.
Parameters
- encodedSchemaString string - Compile time auto generated schema
Classes
graphql: Context
The GraphQL context object used to pass the meta information between resolvers.
set
Sets a given value for a given key in the GraphQL context.
get
Retrieves a value using the given key from the GraphQL context.
string userId = check context.get("userId").ensureType();
Parameters
- 'key string -
Return Type
remove
Removes a value using the given key from the GraphQL context.
string userId = check context.remove("userId").ensureType();
Parameters
- 'key string -
Return Type
registerDataLoader
function registerDataLoader(string key, DataLoader dataloader)
Register a given DataLoader instance for a given key in the GraphQL context.
dataloader:DataLoader userDataLoader = new dataloader:DefaultDataLoader(batchUsers); check context.registerDataLoader("user", userDataLoader);
Parameters
- key string - The key for the DataLoader to be registered
- dataloader DataLoader - The DataLoader instance to be registered
getDataLoader
function getDataLoader(string key) returns DataLoader
Retrieves a DataLoader instance using the given key from the GraphQL context.
dataloader:DataLoader userDataLoader = check context.getDataLoader("user");
Parameters
- key string - The key corresponding to the required DataLoader instance
Return Type
- DataLoader - The DataLoader instance if the key is present in the context otherwise panics
invalidate
Remove cache entries related to the given path.
Parameters
- path string - The path corresponding to the cache entries to be removed (Ex: "person.address.city")
Return Type
- error? - The error if the cache invalidateion fails or nil otherwise
invalidateAll
function invalidateAll() returns error?
Remove all cache entries.
Return Type
- error? - The error if the cache invalidateion fails or nil otherwise
resolve
function resolve(Field 'field) returns anydata
Parameters
- 'field Field -
graphql: Field
Represents the information about a particular field of a GraphQL document.
getName
function getName() returns string
Returns the name of the field.
Return Type
- string - The name of the field
getAlias
function getAlias() returns string
Returns the effective alias of the field.
Return Type
- string - The alias of the field. If an alias is not present, the field name will be returned
getPath
Returns the current path of the field. If the field returns an array, the path will include the index of the element.
getSubfields
function getSubfields() returns Field[]?
Returns the subfields of this field as a Field
object array.
Return Type
- Field[]? - The subfield objects of this field
getSubfieldNames
function getSubfieldNames() returns string[]
Returns the names of the subfields of this field as a string array.
Return Type
- string[] - The names of the subfields of this field
getType
function getType() returns __Type
Returns the type of the field.
Return Type
- __Type - The type of the field
getLocation
function getLocation() returns Location
Returns the location of the field in the GraphQL document.
Return Type
- Location - The location of the field
Clients
graphql: Client
The Ballerina GraphQL client that can be used to communicate with GraphQL APIs.
Constructor
Gets invoked to initialize the connector
.
init (string serviceUrl, *ClientConfiguration clientConfig)
- serviceUrl string - URL of the target service
- clientConfig *ClientConfiguration - The configurations to be used when initializing the
connector
executeWithType
function executeWithType(string document, map<anydata>? variables, string? operationName, map<string|string[]>? headers, typedesc<GenericResponse|record {}|json> targetType) returns targetType|ClientError
Executes a GraphQL document and data binds the GraphQL response to a record with data and extensions which is a subtype of GenericResponse.
Parameters
- document string - The GraphQL document. It can include queries & mutations.
For example
query OperationName($code:ID!) {country(code:$code) {name}}
.
- variables map<anydata>? (default ()) - The GraphQL variables. For example
{"code": "<variable_value>"}
.
- operationName string? (default ()) - The GraphQL operation name. If a request has two or more operations, then each operation must have a name. A request can only execute one operation, so you must also include the operation name to execute.
- targetType typedesc<GenericResponse|record {}|json> (default <>) - The payload, which is expected to be returned after data binding. For example
type CountryByCodeResponse record {| map<json?> extensions?; record {| record{|string name;|}? country; |} data;
Return Type
- targetType|ClientError - The GraphQL response or a
graphql:ClientError
if failed to execute the queryDeprecated
This method is now deprecated. Use theclient->execute()
API instead
Deprecated
This method is now deprecated. Use the client->execute()
API instead
execute
function execute(string document, map<anydata>? variables, string? operationName, map<string|string[]>? headers, typedesc<GenericResponseWithErrors|record {}|json> targetType) returns targetType|ClientError
Executes a GraphQL document and data binds the GraphQL response to a record with data, extensions and errors which is a subtype of GenericResponseWithErrors.
Parameters
- document string - The GraphQL document. It can include queries & mutations.
For example
query countryByCode($code:ID!) {country(code:$code) {name}}
.
- variables map<anydata>? (default ()) - The GraphQL variables. For example
{"code": "<variable_value>"}
.
- operationName string? (default ()) - The GraphQL operation name. If a request has two or more operations, then each operation must have a name. A request can only execute one operation, so you must also include the operation name to execute.
- targetType typedesc<GenericResponseWithErrors|record {}|json> (default <>) - The payload (
GenericResponseWithErrors
), which is expected to be returned after data binding. For exampletype CountryByCodeResponse record {| map<json?> extensions?; record {| record{|string name;|}? country; |} data; ErrorDetail[] errors?; |};
Return Type
- targetType|ClientError - The GraphQL response or a
graphql:ClientError
if failed to execute the query
Service types
graphql: Service
Represents a GraphQL service.
graphql: Interceptor
Represent a GraphQL interceptor
execute
Constants
graphql: AUTH_SCHEME_BASIC
The prefix used to denote the Basic authentication scheme.
graphql: AUTH_SCHEME_BEARER
The prefix used to denote the Bearer authentication scheme.
graphql: COMPRESSION_ALWAYS
Always set accept-encoding/content-encoding in outbound request/response.
graphql: COMPRESSION_AUTO
When service behaves as a HTTP gateway inbound request/response accept-encoding option is set as the outbound request/response accept-encoding/content-encoding option.
graphql: COMPRESSION_NEVER
Never set accept-encoding/content-encoding header in outbound request/response.
Enums
graphql: __TypeKind
Represents a GraphQL type kind. This is used to represent the kind of a GraphQL type.
Members
Listeners
graphql: Listener
Represents a Graphql listener endpoint.
Constructor
Invoked during the initialization of a graphql:Listener
. Either an http:Listener
or a port number must be
provided to initialize the listener.
init (int|Listener listenTo, *ListenerConfiguration configuration)
- listenTo int|Listener - An
http:Listener
or a port number to listen to the GraphQL service endpoint
- configuration *ListenerConfiguration - The additional configurations for the GraphQL listener
attach
Attaches the provided service to the Listener.
Parameters
- s Service - The
graphql:Service
object to attach to the listener
Return Type
- Error? - A
graphql:Error
if an error occurred during the service-attaching process or the schema generation process or else()
detach
Detaches the provided service from the Listener.
Parameters
- s Service - The service to be detached from the listener
Return Type
- Error? - A
graphql:Error
if an error occurred during the service detaching process or else()
'start
function 'start() returns Error?
Starts the attached service.
Return Type
- Error? - A
graphql:Error
, if an error occurred during the service starting process, otherwise nil
gracefulStop
function gracefulStop() returns Error?
Gracefully stops the graphql listener. Already accepted requests will be served before the connection closure.
Return Type
- Error? - A
graphql:Error
, if an error occurred during the service stopping process, otherwise nil
immediateStop
function immediateStop() returns Error?
Stops the service listener immediately.
Return Type
- Error? - A
graphql:Error
if an error occurred during the service stopping process or else()
Annotations
graphql: ID
Represents the annotation of the ID type.
graphql: InterceptorConfig
The annotation to configure a GraphQL interceptor.
graphql: ResourceConfig
The annotation to configure a GraphQL resolver.
graphql: ServiceConfig
The annotation to configure a GraphQL service.
Records
graphql: __EnumValue
Represents a GraphQL enum value.
Fields
- name string - The name of the enum value
- description string?(default ()) - The description of the enum value
- isDeprecated boolean(default false) - Whether the enum value is deprecated
- deprecationReason string?(default ()) - The reason for deprecation of the enum value
graphql: __Field
Represents a GraphQL field.
Fields
- name string - The name of the field
- description string?(default ()) - The description of the field
- args __InputValue[] - The arguments of the field
- 'type __Type -
- isDeprecated boolean(default false) - Whether the field is deprecated
- deprecationReason string?(default ()) - The reason for deprecation of the field
graphql: __InputValue
Represents a GraphQL input value.
Fields
- name string - The name of the input value
- description string?(default ()) - The description of the input value
- 'type __Type -
- defaultValue string?(default ()) - The default value of the input value, if there is one
graphql: __Type
Represents a GraphQL schema type.
Fields
- kind __TypeKind - The
__TypeKind
of the type
- name string?(default ()) - The name of the type. This can be nil if the type is
NON_NULL
orLIST
- description string?(default ()) - The description of the type
- fields __Field[]?(default ()) - The fields of the type. This only applies if the
kind
isOBJECT
orINTERFACE
. Otherwise, this will be nil.
- interfaces __Type[]?(default ()) - The interfaces of the type. This only applies if the
kind
isOBJECT
orINTERFACE
. Otherwise, this will be nil.
- possibleTypes __Type[]?(default ()) - The possible types of the type. This only applies if the
kind
isUNION
orINTERFACE
. Otherwise, this will be nil.
- enumValues __EnumValue[]?(default ()) - The enum values of the type. This only applies if the
kind
isENUM
. Otherwise, this will be nil.
- inputFields __InputValue[]?(default ()) - The input fields of the type. This only applies if the
kind
isINPUT_OBJECT
. Otherwise, this will be nil.
- ofType __Type?(default ()) - The type of the type. This only applies if the
kind
isNON_NULL
orLIST
. Otherwise, this will be nil.
graphql: BearerTokenConfig
Represents token for Bearer token authentication.
graphql: CacheConfig
Provides a set of configurations for controlling the caching behaviour of the endpoint.
graphql: CircuitBreakerConfig
Provides a set of configurations for controlling the behaviour of the Circuit Breaker.
graphql: ClientConfiguration
Provides a set of configurations for controlling the behaviour of the GraphQL client when communicating with the GraphQL server that operates over HTTP.
Fields
- http1Settings ClientHttp1Settings(default {}) - Configurations related to HTTP/1.1 protocol
- timeout decimal(default 60) - The maximum time to wait (in seconds) for a response before closing the connection
- forwarded string(default "disable") - The choice of setting
forwarded
/x-forwarded
header
- followRedirects FollowRedirects?(default ()) - Configurations associated with Redirection
- poolConfig PoolConfiguration?(default ()) - Configurations associated with request pooling
- cache CacheConfig(default {}) - HTTP caching related configurations
- compression Compression(default COMPRESSION_AUTO) - Specifies the way of handling compression (
accept-encoding
) header
- auth ClientAuthConfig?(default ()) - Configurations related to client authentication
- circuitBreaker CircuitBreakerConfig?(default ()) - Configurations associated with the behaviour of the Circuit Breaker
- retryConfig RetryConfig?(default ()) - Configurations associated with retrying
- cookieConfig CookieConfig?(default ()) - Configurations associated with cookies
- responseLimits ResponseLimitConfigs(default {}) - Configurations associated with inbound response size limits
- secureSocket ClientSecureSocket?(default ()) - SSL/TLS-related options
- proxy ProxyConfig?(default ()) - Proxy server related options
- validation boolean(default true) - Enables the inbound payload validation functionality which provided by the constraint package. Enabled by default
graphql: ClientHttp1Settings
Provides settings related to HTTP/1.x protocol.
graphql: ClientSecureSocket
Provides configurations for facilitating secure communication with a remote GraphQL endpoint.
graphql: CookieConfig
Client configuration for cookies.
graphql: CorsConfig
Represent CORS configurations for internal HTTP service
graphql: CredentialsConfig
Represents credentials for Basic Auth authentication.
graphql: ErrorDetail
Represents an error in GraphQL.
Fields
- Fields Included from *ErrorDetail
graphql: FileUserStoreConfig
Represents file user store configurations for Basic Auth authentication.
graphql: FileUserStoreConfigWithScopes
Represents the auth annotation for file user store configurations with scopes.
Fields
- fileUserStoreConfig FileUserStoreConfig - File user store configurations for Basic Auth authentication
graphql: FollowRedirects
Provides configurations for controlling the endpoint's behaviour in response to HTTP redirect related responses.
graphql: GenericResponse
Represents the target type binding record with data and extensions of a GraphQL response for executeWithType
method.
Fields
- extensions? map<json?> - Meta information on protocol extensions from the GraphQL server
- data? record { anydata... }|map<json?> - The requested data from the GraphQL server
graphql: GenericResponseWithErrors
Represents the target type binding record with data, extensions and errors of a GraphQL response for execute
method.
Fields
- Fields Included from *GenericResponse
- errors? ErrorDetail[] - The errors occurred (if present) while processing the GraphQL request.
graphql: Graphiql
Represent GraphiQL client configurations
Fields
- enabled boolean(default false) - Status of the client
- path string(default "graphiql") - Path for the client
- printUrl boolean(default true) - Enable/disable printing the GraphiQL client URL to the stdout
graphql: GraphqlInterceptorConfig
Provides a set of configurations for the GraphQL interceptors.
Fields
- global boolean(default true) - Scope of the interceptor. If
true
, the interceptor will be applied to all the resolvers.
graphql: GraphqlResourceConfig
Provides a set of configurations for the GraphQL resolvers.
Fields
- interceptorsreadonly (readonly & Interceptor)|(readonly & Interceptor)[](default []) - GraphQL field level interceptors
- prefetchMethodName? string - The name of the instance method to be used for prefetching
- cacheConfig? ServerCacheConfig - The cache configurations for the fields
- complexity? int - The complexity value of the field
graphql: GraphqlServiceConfig
Provides a set of configurations for the GraphQL service.
Fields
- maxQueryDepth? int - The maximum depth allowed for a query
- auth? ListenerAuthConfig[] - Listener authentication configurations
- contextInit ContextInit(default initDefaultContext) - Function to initialize the context. If not provided, an empty context will be created
- cors? CorsConfig - The cross origin resource sharing configurations for the service
- graphiql Graphiql(default {}) - GraphiQL client configurations
- schemaStringreadonly string(default "") - The generated schema. This is auto-generated at the compile-time. Providing a value for this field will end up in a compilation error.
- interceptorsreadonly (readonly & Interceptor)|(readonly & Interceptor)[](default []) - GraphQL service level interceptors
- introspection boolean(default true) - Whether to enable or disable the introspection on the service
- validation boolean(default true) - Whether to enable or disable the constraint validation
- cacheConfig? ServerCacheConfig - The cache configurations for the operations
- fieldCacheConfigreadonly ServerCacheConfig?(default ()) - The field cache config derived from the resource annotations. This is auto-generated at the compile time
- queryComplexityConfig? QueryComplexityConfig - The query complexity configuration for the service.
graphql: JwtIssuerConfig
Represents JWT issuer configurations for JWT authentication.
graphql: JwtValidatorConfig
Represents JWT validator configurations for JWT authentication.
Fields
- scopeKey string(default "scope") - The key used to fetch the scopes
graphql: JwtValidatorConfigWithScopes
Represents the auth annotation for JWT validator configurations with scopes.
Fields
- jwtValidatorConfig JwtValidatorConfig - JWT validator configurations for JWT authentication
graphql: LdapUserStoreConfig
Represents LDAP user store configurations for Basic Auth authentication.
graphql: LdapUserStoreConfigWithScopes
Represents the auth annotation for LDAP user store configurations with scopes.
Fields
- ldapUserStoreConfig LdapUserStoreConfig - LDAP user store configurations for Basic Auth authentication
graphql: ListenerConfiguration
Provides a set of configurations for configure the underlying HTTP listener of the GraphQL listener.
graphql: ListenerHttp1Settings
Provides settings related to HTTP/1.x protocol, when using HTTP 1.x as the underlying protocol for the GraphQL service.
graphql: ListenerSecureSocket
Configures the SSL/TLS options to be used for the underlying HTTP service used in GraphQL service.
graphql: Location
Represents a location in a GraphQL document.
Fields
- Fields Included from *Location
graphql: OAuth2ClientCredentialsGrantConfig
Represents OAuth2 client credentials grant configurations for OAuth2 authentication.
graphql: OAuth2IntrospectionConfig
Represents OAuth2 introspection server configurations for OAuth2 authentication.
Fields
- scopeKey string(default "scope") - The key used to fetch the scopes
graphql: OAuth2IntrospectionConfigWithScopes
Represents the auth annotation for OAuth2 introspection server configurations with scopes.
Fields
- oauth2IntrospectionConfig OAuth2IntrospectionConfig - OAuth2 introspection server configurations for OAuth2 authentication
graphql: OAuth2JwtBearerGrantConfig
Represents OAuth2 JWT bearer grant configurations for OAuth2 authentication.
graphql: OAuth2PasswordGrantConfig
Represents OAuth2 password grant configurations for OAuth2 authentication.
graphql: OAuth2RefreshTokenGrantConfig
Represents OAuth2 refresh token grant configurations for OAuth2 authentication.
graphql: PoolConfiguration
Configurations for managing GraphQL client connection pool.
graphql: ProxyConfig
Proxy server configurations to be used with the GraphQL client endpoint.
graphql: QueryComplexityConfig
Defines the query complexity configuration for the GraphQL service.
Fields
- maxComplexity int(default 100) - Maximum allowed query depth
- defaultFieldComplexity int(default 1) - Default complexity for a field
- warnOnly boolean(default false) - Whether to only log a warning or return an error when the complexity exceeds the limit
graphql: RequestLimitConfigs
Provides inbound request URI, total header and entity body size threshold configurations.
graphql: ResponseLimitConfigs
Provides inbound response status line, total header and entity body size threshold configurations.
graphql: RetryConfig
Provides configurations for controlling the retrying behavior in failure scenarios.
graphql: ServerCacheConfig
Represent the cache configurations of GraphQL server.
Fields
- enabled boolean(default true) - State of the caching
- maxAge decimal(default 60) - TTL of the cache in seconds
- maxSize int(default 120) - Maximum number of cache entries
graphql: Upload
The input parameter type used for file uploads in GraphQL mutations.
Fields
- fileName string - Name of the file
- mimeType string - File mime type according to the content
- encoding string - File stream encoding
Errors
graphql: AuthnError
Represents the authentication error type.
graphql: AuthzError
Represents the authorization error type.
graphql: ClientError
Represents GraphQL client related generic errors.
graphql: Error
Represents any error related to the Ballerina GraphQL module.
graphql: HttpError
Represents network level errors.
graphql: InvalidDocumentError
Represents GraphQL errors due to request validation.
graphql: PayloadBindingError
Represents client side data binding error.
graphql: RequestError
Represents GraphQL client side or network level errors.
graphql: ServerError
Represents GraphQL API response during GraphQL API server side errors.
Deprecated
This error type will be removed along with the executeWithType()
API
Union types
graphql: ListenerAuthConfig
ListenerAuthConfig
Defines the authentication configurations for the GraphQL listener.
graphql: ClientAuthConfig
ClientAuthConfig
Defines the authentication configurations for the GraphQL client.
graphql: OAuth2GrantConfig
OAuth2GrantConfig
Represents OAuth2 grant configurations for OAuth2 authentication.
graphql: Scalar
Scalar
Represents the Scalar types supported by the Ballerina GraphQL module.
graphql: Compression
Compression
Options to compress using gzip or deflate.
Function types
graphql: ContextInit
function(RequestContext, Request) returns (Context|error)
ContextInit
Function type for initializing the graphql:Context
object.
This function will be called with the http:Request
and the http:RequestContext
objects from the original request
received to the GraphQL endpoint.
Import
import ballerina/graphql;
Metadata
Released date: 8 days ago
Version: 1.15.0
License: Apache-2.0
Compatibility
Platform: java21
Ballerina version: 2201.11.0
GraalVM compatible: Yes
Pull count
Total: 91158
Current verison: 61
Weekly downloads
Keywords
gql
network
query
service
Contributors