import ballerina/graphql;

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

    // Ballerina GraphQL resolvers can return `record` values. The record will be mapped to an `OBJECT` type.
    resource function get profile() returns Person {

        return {
            name: "Walter White",
            age: 51,
            address: {
                number: "308",
                street: "Negra Arroyo Lane",
                city: "Albuquerque"
            }
        };
    }
}

// Define the custom record types for the returning data.
public type Person record {
    string name;
    int age;
    Address address;
};
public type Address record {
    string number;
    string street;
    string city;
};

Returning Record Values

In Ballerina GraphQL, a service represents the GraphQL endpoint. Each resource function inside the service represents a resolver function for a field in the root Query type.

For more information on the underlying package, see the GraphQL package.

This example shows a GraphQL endpoint, which has a field profile of type Person. A GraphQL client can query on this service to retrieve specific fields or subfields of the Person object.

import ballerina/graphql;
service /graphql on new graphql:Listener(4000) {
    resource function get profile() returns Person {

Ballerina GraphQL resolvers can return record values. The record will be mapped to an OBJECT type.

        return {
            name: "Walter White",
            age: 51,
            address: {
                number: "308",
                street: "Negra Arroyo Lane",
                city: "Albuquerque"
            }
        };
    }
}
public type Person record {
    string name;
    int age;
    Address address;
};
public type Address record {
    string number;
    string street;
    string city;
};

Define the custom record types for the returning data.

bal run graphql_returning_record_values.bal
[ballerina/http] started HTTP/WS listener 0.0.0.0:4000
# Send a query to the GraphQL endpoint using a cURL command.
# The query used: { profile { name, address { city } } }
curl -X POST -H "Content-type: application/json" -d '{ "query": "{ profile { name, address { city } } }" }' 'http://localhost:4000/graphql'
{"data":{"profile":{"name":"Walter White", "address":{"city":"Albuquerque"}}}}