Back to Examples

GraphQL service - Record as output object

The Ballerina graphql module allows returning record types from the resource or remote methods of the graphql:Service. These record types are mapped to GraphQL output object types in the GraphQL schema in which the type name and the field names are mapped one-to-one from Ballerina to GraphQL. Use a record type to represent a GraphQL output object type only when all fields of that object type do not have any input arguments or the field resolution does not require any complex logic execution. The record type is preferred over the service object type in this case as it makes the code more concise.

import ballerina/graphql;

// Define the custom record types for the returning data.
public type Profile record {|
    string name;
    int age;
    Address address;
|};

public type Address record {|
    string number;
    string street;
    string city;
|};

service /graphql on new graphql:Listener(9090) {

    // Ballerina GraphQL resolvers can return `record` values. The record will be mapped to a
    // GraphQL output object type in the generated GraphQL schema with the same name and fields.
    resource function get profile() returns Profile {
        return {
            name: "Walter White",
            age: 51,
            address: {
                number: "308",
                street: "Negra Arroyo Lane",
                city: "Albuquerque"
            }
        };
    }
}

Run the service by executing the following command.

$ bal run graphql_returning_record_values.bal

Send the following document to the GraphQL endpoint to test the service.

{
    profile {
        name,
        address {
            city
        }
    }
}

To send the document, execute the following cURL command in a separate terminal.

$ curl -X POST -H "Content-type: application/json" -d '{ "query": "{ profile { name, address { city } } }" }' 'http://localhost:9090/graphql'{"data":{"profile":{"name":"Walter White", "address":{"city":"Albuquerque"}}}}

Tip: You can invoke the above service via the GraphQL client.

Related links

PreviousService as output object
NextInput types