Back to Examples

GraphQL client - Handle partial response

The graphql:Client allows handling cases where a GraphQL service responds with partial data along with errors. To retrieve the partial data, define the fields as nilable types in the expected response type where applicable. Use this approach when the response with partial data is considered to be valid or the partial data needs to be retrieved.

Hint: When defining field types as nilable, check the corresponding GraphQL schema to check the nilable fields.

import ballerina/graphql;
import ballerina/io;

// The `ProfileResponse` is a sub-type of `graphql:GenericResponseWithErrors`.
// The `graphql:GenericResponseWithErrors` record represents the generic shape of the GraphQL
// response. The `graphql:GenericResponseWithErrors` record contains `data`, `errors`,
// and `extensions` fields of which `data` represents the requested data from the GraphQL server,
// `errors` represents the field errors raised during the execution, and `extensions` represents
// the meta information on the protocol extensions from the GraphQL server.
type ProfileResponse record {|
    *graphql:GenericResponseWithErrors;
    record {|Profile profile;|} data;
|};

// The following record type defines the shape of the response from a GraphQL service, which allows
// the `age` field to have a `null` value.
type Profile record {|
    string name;
    int? age;
|};

public function main() returns error? {
    // Creates a new client with the backend URL.
    graphql:Client graphqlClient = check new ("localhost:9090/graphql");

    string document = "{ profile(id: 1) { name, age } }";
    ProfileResponse response = check graphqlClient->execute(document);

    // Access the data from the response.
    io:println(response.data);

    if response.errors !is () {
        // Access the field errors from the response.
        io:println(response.errors);
    }
}

Prerequisites

Run the client program by executing the following command.

$ bal run graphql_client_handle_partial_response.bal{"profile":{"name":"Walter White","age":null}}[{"message":"Error occurred while retrieving age","locations":[{"line":1,"column":26}],"path":["profile","age"]}]

Related links

PreviousQuery GraphQL endpoint
NextHandle error response