Skip to content
Jennifer Programming Language

graphql - a thin GraphQL client

Import with import "graphql.j" as graphql;. A small GraphQL client over http / rest: point a Client at one endpoint, then query POSTs {"query": ..., "variables": ...} and returns the decoded JSON response as a json.Value. Default jennifer binary only (net-backed).

jennifer
import "graphql.j" as graphql;
use json;
use io;
use os;

def token as string init os.getEnv("GITHUB_TOKEN");
def gql as graphql.Client init graphql.bearer(
    graphql.client("https://api.github.com/graphql"), $token);

def vars as json.Value init json.set(json.map(), "/login", "octocat");
def resp as json.Value init graphql.query($gql,
    'query($login:String!){ user(login:$login){ name } }', $vars);

io.printf("%s\n", json.asString($resp, "/data/user/name"));

The query is an opaque string you supply (the module does not parse GraphQL), and a mutation is a query string too, so there is no separate verb. variables is a json.Value object (an empty json.map() when the operation takes none). Write a document in a single-quoted string ('{ viewer { login } }'): in a double-quoted one, { starts an interpolation.

Runnable: examples/modules/graphql_demo.j.

The client

graphql.Client wraps a rest.Client, so it carries the endpoint URL, per-request headers, and TLS options. It is value-semantic: each builder returns a new client, nothing is mutated.

CallReturnsNotes
graphql.client(endpoint)ClientA client for one endpoint URL. The URL is POSTed to verbatim - pass the complete GraphQL URL (e.g. https://host/graphql); no path is appended.
graphql.bearer(c, token)ClientAdd Authorization: Bearer <token>.
graphql.basic(c, user, pass)ClientAdd HTTP Basic Authorization.
graphql.header(c, name, value)ClientSet an arbitrary request header.
graphql.withCA(c, pem)ClientTrust a private-CA / self-signed certificate (PEM); verification stays on, against this CA.
graphql.withSkipVerify(c)ClientSkip TLS verification - a trusted network or a local test server only.
graphql.withTimeout(c, ms)ClientThe idle timeout for each read, in milliseconds (0 = the 30 s default).
graphql.withRetries(c, n)ClientRetry a query answered 429 or 5xx up to n times, with exponential backoff honouring Retry-After. Mutations are never retried.
graphql.withBackoff(c, ms)ClientThe first retry's backoff (doubled each time; 0 = 250 ms).

Every GraphQL operation is a POST, so the client tells reads from writes by the document: one that starts with { or query (after whitespace and comments), or whose operationName names a query (text inside strings and comments does not count), may be retried. A mutation, a subscription and a document that starts with a fragment are sent once, because the server may already have done the write. Redirects are not followed: a redirected POST would come back as a GET without its body.

Each request sends Accept: application/graphql-response+json, application/json (the GraphQL-over-HTTP media type first) unless you set your own with header.

A client carrying an Authorization or Proxy-Authorization header (from bearer, basic or header) refuses an http:// endpoint on a host other than loopback (127.0.0.0/8, [::1], localhost): the request raises a GraphqlError with reason "insecure" before connecting, so the credential is never sent in the clear. For plain HTTP on a trusted LAN, set the client's allowInsecureHttp field:

jennifer
def lan as graphql.Client init graphql.bearer(
    graphql.client("http://hasura.home.lan/v1/graphql"), $token);
$lan.allowInsecureHttp = true;

Builders compose left to right - each takes a Client and returns one:

jennifer
def gql as graphql.Client init graphql.header(
    graphql.bearer(graphql.client("https://host/graphql"), $token),
    "X-Api-Version", "2");

Running a query

CallReturnsNotes
graphql.query(c, query, variables)json.ValuePOST the operation; raise on GraphQL / HTTP errors; return the full decoded response (result under /data).
graphql.queryNamed(c, query, variables, operationName)json.Valuequery, selecting one operation from a multi-operation document by name.
graphql.tryQuery(c, query, variables)json.ValueLike query but does not raise on GraphQL errors - returns the envelope so you inspect /errors yourself. Still raises on a non-2xx HTTP status that carries no errors envelope.
graphql.tryQueryNamed(c, query, variables, operationName)json.ValuetryQuery with an operationName.
graphql.hasErrors(resp)boolWhether a returned envelope carries a non-empty errors array.
graphql.errorMessages(resp)stringThe envelope's error messages, joined with ; .
graphql.errorCodes(resp)list of stringEach error's extensions.code, in order, "" where an error has none.
jennifer
def resp as json.Value init graphql.query($gql, '{ viewer { login } }', json.map());
def login as string init json.asString($resp, "/data/viewer/login");

The response is the whole GraphQL envelope, so read the payload under /data (and /data/<field>/...) with the json accessors.

Named operations

When a document defines more than one named operation, pass the one to run as operationName (some servers require it in that case):

jennifer
def q as string init 'query Me { viewer { login } } query Repos { viewer { repositories { totalCount } } }';
def resp as json.Value init graphql.queryNamed($gql, $q, json.map(), "Repos");

A single-operation document needs no name - use plain query / tryQuery.

Errors

In GraphQL an execution error is an HTTP 200 with a top-level errors array, not a non-2xx status. query inspects the payload as well as the status line and raises a graphql.GraphqlError (kind "graphql") in two cases:

  • GraphQL errors - the response carries a non-empty errors array. The error's message is graphql: followed by every entry's message, each with its extensions.code in brackets when it has one, joined with ; and cut at 2000 characters: graphql: denied [FORBIDDEN]; and y. A response with partial data and errors still raises. Many servers answer an invalid query or a refused credential with a 4xx that carries such an envelope; it is read the same way, with the status in front: graphql: HTTP 400: Cannot query field nope [GRAPHQL_VALIDATION_FAILED].
  • HTTP failure - any other non-2xx status (a transport, auth, or server problem). The message carries the status code and the start of the response body, at most 200 characters with control characters flattened to spaces, so a proxy's error page does not fill a log.

A 2xx body that is not a GraphQL response raises it too: not JSON (one past json's decoding caps is kind "limit"), not a JSON object, an object with neither data nor errors, data that is not an object or null, or an errors that is not a non-empty list of objects each with a string message (locations and path lists and extensions an object, when present). This holds for tryQuery as well, so an envelope it returns is well-formed. A non-2xx body is only read as an envelope when it is well-formed; any other is an HTTP failure. Every error of kind "graphql" is a GraphqlError, so its fields are safe to read once the kind matches:

FieldMeaning
kindalways "graphql"
messageas above
reason"graphql" (an errors array, at any status), "http" (a non-2xx without one), "json" (a 2xx body that is not a GraphQL response) or "insecure" (credentials refused over plain http://; nothing was sent)
statusthe HTTP status (0 for "insecure")
codeseach error's extensions.code, "" where an error has none; empty unless reason is "graphql"
errorsthe server's errors array (message, path, locations, extensions); JSON null unless reason is "graphql"

A successful return has no errors, so /data is present and complete. Catch with try / catch:

jennifer
try {
    def resp as json.Value init graphql.query($gql, $q, $vars);
    # ... use $resp ...
} catch (e) {
    io.eprintf("query failed: %s\n", $e.message);   # e.kind == "graphql"
}

Handling GraphQL errors yourself

The thrown GraphqlError carries the codes and the errors array, but not the response's partial data. To read partial data, or to handle errors without try, use tryQuery: it returns the envelope instead of raising on GraphQL errors (it still raises on a non-2xx HTTP status without an envelope):

jennifer
def resp as json.Value init graphql.tryQuery($gql, $q, $vars);
if (graphql.hasErrors($resp)) {
    if (lists.contains(graphql.errorCodes($resp), "RATE_LIMITED")) {
        # ... back off and retry ...
    } else {
        io.eprintf("graphql: %s\n", graphql.errorMessages($resp));
    }
} else {
    def login as string init json.asString($resp, "/data/viewer/login");
    # ...
}

The envelope is a plain json.Value, so everything under /errors is reachable with the json accessors.

TLS to a self-signed host

The TLS builders (from rest) reach a homelab / private-CA endpoint (Hasura, a self-hosted API):

jennifer
def pem as bytes init fs.readBytes("ca.pem");
def gql as graphql.Client init graphql.withCA(
    graphql.client("https://hasura.home.lan/v1/graphql"), $pem);

Use graphql.withSkipVerify(c) only on a trusted network or against a local test server - it accepts any certificate.

See also

  • rest.md - the REST layer the client wraps (auth + TLS options).
  • http.md - the underlying HTTP/1.1 client.
  • json.md - reading the response and building variables.
  • modules/index.md - the module catalog and import rules.

Academy talks

TalkWhat it shows
Invoicing with web services: VAT, SOAP and GraphQLpaged GraphQL queries and errors returned with HTTP 200

API reference

Every exported function, struct and constant of graphql, with its signature, generated from the module's doc comments: the graphql API reference.