GraphQL API
GraphQL API
Configuration
The URL and credentials the examples on this page use
Setup Guide
Where to run the examples on this page
To run the examples on this page, you need a RESTHeart instance.
Option 1: Use Ulabase (Recommended)
The fastest way to get started is with Ulabase. Create a free service in minutes:
-
Sign up at ulabase.com
-
Create a free API service
-
Set up your root user following the Root User Setup guide
-
Use the configuration panel above to set your service URL and credentials
|
Tip
|
All code examples on this page will automatically use your configured Ulabase credentials. |
Option 2: Run RESTHeart Locally
If you prefer local development, follow the Setup Guide to install RESTHeart on your machine.
|
Note
|
Local instances run at http://localhost:8080 with default credentials admin:secret
|
The restheart-graphql plugin exposes a read-only (no mutations and subscription) GraphQL API for inquiring MongoDB resources.
The GraphQL API works side by side with the REST API to build modern applications.
Configuration
The default configuration for the graphql plugin is as follows.
graphql:
uri: /graphql
db: restheart
collection: gql-apps
# app cache can be disabled if needed, such as during testing or development
app-cache-enabled: true
# app cache entries are automatically revalidated every TTR milliseconds
app-cache-ttr: 60_000 # in msecs
# default-limit is used for queries that don't not specify a limit
default-limit: 100
# max-limit is the maximum value for a Query limit
max-limit: 1000
# The time limit in milliseconds for processing queries. Set to 0 for no time limit.
query-time-limit: 0
# How deep a query may nest and how many fields it may select, nested ones weighed. A query over
# either cap is refused before any resolver runs, 400 with the error. 0 means no cap.
max-query-depth: 0
max-query-complexity: 0
# Arguments are values: an argument with operators is refused, and a string argument starting
# with $ is bound in $literal where MongoDB would read it as a field path or a variable.
check-operators: true
verbose: false
|
Note
|
check-operators is available from v9.17. See Arguments are values.
|
|
Note
|
max-query-depth and max-query-complexity are available from v9.12.3. They bound the shape of a query, where query-time-limit bounds how long it runs: a query nested beyond the depth, or selecting more fields than the complexity allows (nested fields weigh more), is refused with 400 before any data is fetched. On a server that many tenants share, 10 and 1000 are a sound start.
|
|
Note
|
app-cache-enabled and app-cache-ttr are available from v8.0.9 and v8.0.11, respectively. Earlier versions use an expiring cache policy with TTL configurable via the now-deprecated graphql/app-def-cache-ttl option. See issue #523.
|
GraphQL App Definition
Each GraphQL application requires a GraphQL App Definition, a JSON document typically stored in the /gql-apps collection.
GraphQL applications can be dynamically created or updated by modifying the corresponding document in MongoDB.
A GraphQL application definition is composed by three sections:
{
"descriptor": "...",
"schema": "...",
"mappings": "..."
}
Descriptor
The descriptor is the header section of your GraphQL app definition, where you configure the application’s identity and basic settings: its name (via _id), description, and the URI endpoint where it will be accessible.
|
Note
|
v9 has simplified the descriptor section to reduce configuration redundancy and make it more intuitive. |
Required Fields
-
_id: The document identifier, which also serves as the application name
Optional Fields
-
descriptor.description: GraphQL application description -
descriptor.enabled: can betrueorfalse(default:true) -
descriptor.uri: Custom endpoint path. If omitted, uses/_idas the URI
Simplified Configuration (v9)
Minimal Example:
{
"_id": "myapp",
"schema": "...",
"mappings": "..."
}
This creates a GraphQL application accessible at /graphql/myapp.
With Custom URI:
{
"_id": "user-api",
"descriptor": {
"uri": "/v1/users",
"description": "User management API",
"enabled": true
},
"schema": "...",
"mappings": "..."
}
This creates a GraphQL application accessible at /graphql/v1/users.
Key Changes from v8
RESTHeart v9 streamlines the GraphQL App Definition:
-
Removed
descriptor.name- The_idfield now serves as the sole identifier -
Optional URI - When
descriptor.uriis omitted, the URI auto-generates as/{_id} -
String
_idrequired - When not using a custom URI,_idmust be a string -
URI collision prevention - Validation prevents
_idvalues from matching existing custom URIs and vice versa
Migration from v8:
If migrating from v8, remove the descriptor.name field from your GraphQL app definitions:
// v8 (old)
{
"_id": "507f1f77bcf86cd799439011",
"descriptor": {
"name": "myapp", // Remove this field
"uri": "/myapp"
}
}
// v9 (new)
{
"_id": "myapp", // Use meaningful string IDs
"descriptor": {
"uri": "/myapp" // Optional - will default to /myapp
}
}
|
Important
|
The _id field must be a string when relying on automatic URI generation. Custom URIs can use any _id format.
|
Schema
This section must contain GraphQL application’s schema written with Schema Definition Language (SDL). For example:
{
"descriptor": "...",
"schema": "type User{name: String surname: String email: String posts: [Post]} type Post{text: String author: User} type Query{users(limit: Int = 0, skip: Int = 0):[User]}",
"mappings": "..."
}
|
Note
|
In order the schema to be a valid, it must contain the type Query. |
Mappings
GraphQL types are connected to MongoDB data through mappings.
Mappings are applicable to a range of types, including Object, Query, enum, interfaces, and union.
Field to Field mapping
You can map a GraphQL Object field with a specific MongoDB document field or with an element of a MongoDB array. To map nested fields use the dot-notation.
An example follows:
{
"descriptor": "...",
"schema": "...",
"mappings":{
"User": {
"name": "firstName",
"phone": "contacts.phone",
"email": "contacts.emails.0",
},
"Post": "...",
"Query": "..."
}
}
In this configuration:
The name field is linked to the MongoDB document’s firstName field.
The phone field is associated with the phone field within the nested contacts document.
The email field is connected to the first element of the emails array within the nested contacts document.
|
Note
|
if you don’t explicitly define a mapping for a field, RESTHeart will automatically map it to the MongoDB document field with the same name. |
Field to Query mapping
You can establish a mapping between a GraphQL Object field and a MongoDB query using the following parameters:
-
db(String): The name of the database. -
collection(String): The name of the collection. -
find(Document): The selection filter using query operators such as$in,$and,$or, and others. -
sort(Document): The order in which the query returns matching documents. -
skip(Document or Integer): The number of documents to skip among those resulting from the query. -
limit(Document or Integer): The maximum number of documents to return among those resulting from the query.
|
Note
|
Every query has a limit. A query without a limit gets the default-limit of the service configuration, and a limit cannot be higher than max-limit.
|
|
Note
|
Since v9.17 the find and the sort, with their arguments bound, go through the aggregationSecurity blacklists, as the stages of an aggregation mapping do. $where, $function and $accumulator never reach MongoDB from a mapping. See Aggregation Pipeline Security.
|
Field to Aggregation mapping
You can link a GraphQL Object field with a MongoDB aggregation using the following parameters:
-
db(String): The name of the database. -
collection(String): The name of the collection. -
stages(Array): An array of aggregation stages.
The stages can use the $arg and $fk operators, as a field-to-query mapping does. For example:
"Query": {
"countPostsByCategory": {
"db": "restheart",
"collection": "users",
"stages": [
{ "$group": { "_id": "$category", "count": { "$count": {} } } }
]
}
}
And the Query in the GraphQL schema will now have the following field:
type Stats {
_id: String
count: Int
}
type Query {
countPostsByCategory: [Stats]
}
Predefined variables
Mappings can reference server-resolved variables through $arg, in both field-to-query and field-to-aggregation mappings. The value comes from the server, never from the client: a caller cannot supply it as a GraphQL argument or a query parameter.
| Variable | Resolves to |
|---|---|
|
the authenticated account. Its properties depend on how the caller authenticated: |
|
the authenticated user’s roles, as an array |
|
|
|
the request; |
|
the request’s |
|
one query parameter by name |
|
the current timestamp |
|
a cryptographically secure random hex string |
|
the permissions applying to the request, e.g. |
A variable that a plugin registers through the VarResolver SPI works here too, such as the @subscription of the Stripe module.
|
Note
|
Before RESTHeart 9.9 only @user resolved inside a mapping; every other variable failed with variable … not bound.
|
For example, filtering by the authenticated user:
type User {
_id: String,
name: String
}
type Query {
me: User
}
# Mapping: 'me' always returns the authenticated user
"Query": {
"me": {
"db": "restheart",
"collection": "users",
"stages": [
{
"$match": {
"$or": [
{ "_id": { "$arg": ["@user._id", null] } },
{ "_id": { "$arg": ["@user.sub", null] } }
]
}
}
]
}
}
With this configuration, the me query will return the User object corresponding to the authenticated user.
The $or handles the two kinds of caller: an account read from MongoDB users has @user._id, and one carried by a token has @user.sub.
Each $arg has null as its default, so the branch of the other kind of caller matches nothing. Without a default, a name the account does not carry fails the query with variable not bound (since 9.8.2).
Optional Stages
Field-to-aggregation mapping can include optional stages that are executed only when one or more arguments are specified. This feature enables the handling of optional GraphQL arguments.
They work as the optional stages of an aggregation, with the operator $ifarg in place of $ifvar: see Optional stages.
Mappings operators
Field to Query and Field to Aggregation mappings can use two operators:
-
$arg: the value of a GraphQL argument, bound into the query or the aggregation. -
$fk: It allows the specification of the document field responsible for holding a relation. It enables traversing related documents.
For instance, consider the following GraphQL schema:
type User {
id: Int!
name: String
posts: [Post]
}
type Post {
id: Int!
text: String
category: String
author: User
}
type Query {
usersByName(_name: String!, _limit: Int = 0, _skip: Int = 0): [Users]
}
with MongoDB data organized in the two collections users and posts:
USERS
{
"_id": "foo",
"firstName": "Foo",
"lastName": "Bar",
"contacts": { "phone": "+39113", "emails": ["foo@domain.com", "f.bar@domain.com"] },
"posts_ids": [ 1, 2 ]
}
POSTS
[
{ "_id": 1,
"text": "Lorem ipsum dolor sit amet",
"category": "front-end",
"author_id": "foo"
},
{ "_id": 2,
"text": "Lorem ipsum dolor sit amet",
"category": "back-end",
"author_id": "foo"
}
]
The possible mappings are:
{
"descriptor": "...",
"schema": "...",
"mappings": {
"User": {
"posts": {
"db": "restheart",
"collection": "posts",
"find": { "_id": { "$in": { "$fk": "posts_ids" } } }
}
},
"Post": {
"author": {
"db": "restheart",
"collection": "user",
"find": { "_id": { "$fk": "author_id" } }
}
},
"Query": {
"usersByName": {
"db": "restheart",
"collection": "users",
"find": { "name": { "$arg": "_name" } },
"limit": { "$arg": "_limit" },
"skip": { "$arg": "_skip" },
"sort": { "name": -1 }
}
}
}
}
As a result of using these mapping operators:
-
When given a
User, their posts are represented by the MongoDB documents within thepostscollection. These documents have an_idfield value that matches any of the_idvalues within theposts_idsarray in the `User’s document. -
When given a
Post, its author is identified by the MongoDB document within theuserscollection. This document has an_idfield value that matches theauthor_idwithin the `Post’s document. -
For the
userByNameGraphQL field, the MongoDB documents being queried are those within theuserscollection with anamefield equal to the value specified in the_nameGraphQL argument. Furthermore, you can specify that you want to return a maximum of_limitdocuments, skip the first_skipdocuments, and have them sorted by name in reverse order.
|
Note
|
the $fk and $arg operators allow the usage of dot notation to traverse document fields.
|
Dot Notation support for $arg and $fk
The $fk and $arg operators read a nested property with the dot notation.
The Dot Notation support for $arg feature enables the handling of InputTypes. The following example will clarify:
input Filters {
type: String
author: String
}
type Query {
getPosts(filters: Filters!): [Post]
}
The Query mapping can use the dot notation as follows to cope the Filters InputType:
{ "mappings": {
"Query": {
"getPosts": {
"db": "restheart",
"collection": "the-posts",
"find": { "author": { "$arg": "filters.author" }, "type": { "$arg": "filters.type" } }
}
}
}
Arguments with Default Values
$arg can have a default value, used when the GraphQL query does not pass an optional argument. {"$arg": ["name", "Andrea"]} gives the argument name the default Andrea.
It works as a $var with a default in an aggregation: see Variables with default values.
Arguments are values
The query of a mapping is written by whoever defines the app. An argument is a value. Since v9.17, with check-operators enabled, the default:
-
an argument that carries a MongoDB operator, a key starting with
$, is refused with the errorarguments cannot include operators. Only aBsonDocumentargument passed as a GraphQL variable can carry one; -
a string argument starting with
$is bound as{"$literal": value}where MongoDB would read it as a field path or as a variable: in the expressions of an aggregation mapping, and under$exprin afind.
An example of what the check stops. With this mapping, and template of type BsonDocument:
{ "$match": { "fsType": "Dataset", "template.uid": { "$arg": "template" } } }
a client that passes {"$ne": null} as template reads the datasets of every template. With check-operators the query is refused. Where the client passes one value, give the argument a scalar type such as String.
An argument that carries a query: "operators": true
Some apps let the client write a filter on purpose, in a BsonDocument argument. The mapping declares that argument with "operators": true:
"stages": [
{ "$match": { "fsType": "Dataset", "template.uid": "company" } },
{ "$ifarg": [ "filter", { "$match": { "$arg": "filter", "operators": true } } ] },
{ "$ifarg": [ "sort", { "$sort": { "$arg": "sort" } } ] }
]
The declared arguments skip the check. The other arguments of the mapping keep it: here sort, which needs no operator. The form with a default is {"$arg": ["filter", {}], "operators": true}.
Put the client’s filter in a $match of its own, after the one the app fixes. A stage reads only the documents the stage before it lets through, so here the client filters the company datasets and nothing else.
An argument declared with "operators": true in one place of a mapping and without it in another makes the app invalid. So does an "operators" that is not true or false.
A declared argument still cannot run JavaScript. $where, $function and $accumulator in it are refused by the aggregationSecurity blacklists.
check-operators: false turns the check off for every argument of every app. It turns off the $literal binding too. Use "operators": true on the arguments that need it.
The rootDoc argument
|
Tip
|
more details about this feature are available on github issue 469 |
{"$arg": "rootDoc"} is the root document: the document of the parent object, whose field is being resolved. A Field to Query or a Field to Aggregation mapping uses its properties in the query.
The root document, in this context, is the first document retrieved from the source.
To provide a clear example, let’s consider a document from the collection authors-and-posts:
The example is implemented in test rootDoc.feature
{
"_id": "bar",
"sub": {
"posts": [
{ "content": "ping", "visible": true },
{ "content": "pong", "visible": true },
{ "content": "invisible", "visible": false }
]
}
}
And the following GraphQL schema. Note that the field post has the argument visible.
type User {
_id: String
posts(visible: Boolean): [Post]
}
type Post {
content: String
}
type Query {
users: [User]
}
In order to filter the nested posts objects according to the argument visible we can make use of field to aggregation mapping:
{
"User": {
"posts": {
"db": "restheart",
"collection": "authors-and-posts",
"stages": [
{ "$match": { "_id": { "$arg": "rootDoc._id" } } },
{ "$unwind" : "$sub.posts" },
{ "$replaceRoot": {"newRoot": "$sub.posts"} },
{ "$match": { "visible": { "$arg": "visible" } } }
]
}
}
}
The field to aggregation mapping selects the root user using the rootDoc and filters the objects in the nested array sub.posts that match the argument visible.
Enum mappings
Enum type mappings serve to define the correspondence between values in MongoDB and the corresponding enum values.
However, it’s essential to note that enum mappings are optional. When omitted, it is assumed that the value in the database is identical to the string representation of the enum value.
For instance, consider the following enum:
enum Level { ENTRY, MEDIUM, ADVANCED }
Can be mapped to numeric values as follows:
"Level": {
"ENTRY": 0,
"MEDIUM": 1,
"ADVANCED": 2
}
|
Note
|
An example GraphQL application that uses enum is enumTestApp.json used in the test enum.feature
|
Interface mappings
An interface in GraphQL is an abstract type that specifies a particular set of fields that any concrete type implementing the interface must include.
To determine which concrete type a value belongs to when querying against the interface, a TypeResolver must be defined in the interface mappings.
Let’s consider an example involving an interface and concrete objects:
interface Course { _id: ObjectId, title: String }
type InternalCourse implements Course { _id: ObjectId, title: String }
type ExternalCourse implements Course { _id: ObjectId, title: String, deliveredBy: String }
type Query { AllCourses: [Course] }
The following mappings defines the TypeResolver using the $typeResolver keyword.
"Course": {
"$typeResolver": {
"InternalCourse": "not field-exists(deliveredBy)",
"ExternalCourse": "field-exists(deliveredBy)"
}
}
The $typeResolver serves as an object that establishes a mapping between the names of concrete types (such as InternalCourse and ExternalCourse) and corresponding predicates. These predicates are evaluated against a document, and if a predicate returns true, the GraphQL type associated with that predicate is used to represent the document.
The predicates decide the GraphQL type of each document. A query against an interface then returns each object with its own type.
$typeResolver can use the following predicates:
predicate |
description |
|
boolean |
|
boolean |
|
boolean |
|
checks if the type document contains the specified keys. Dot notation and multiple keys are permitted as in |
|
checks if the specified type key is equal to a value. The key can use the dot notation and the value can be any JSON as in |
|
checks if the type value is equal to the given argument. The argument can be any JSON as in |
|
Warning
|
the value of the field-eq predicate must be valid JSON. In particular pay attention to string values that require two quotes as in field-eq(field=foo, value='"bar"').
|
Examples of field-eq predicates
predicate |
condition |
|
field |
|
field |
|
field |
|
field |
|
field |
|
Note
|
An example GraphQL application that uses interface is interfaceTestApp.json used in the test interface.feature
|
Union mappings
Union types in GraphQL are similar to interfaces in that they represent a way to include multiple types in a single field. However, unlike interfaces, union types do not specify any fields that the types within the union must have in common.
With union types, you can specify that a field can return values of different types, and you can use this construct when you want to retrieve data that doesn’t share a common set of fields but still needs to be represented as a single field in your schema. This is particularly useful for scenarios where you have different types of data that can be queried together under one field, even if they have different structures.
union Course = InternalCourse | ExternalCourse
type InternalCourse { _id: ObjectId, title: String }
type ExternalCourse { _id: ObjectId, title: String, deliveredBy: String }
As for interfaces, a TypeResolver must be defined in the union mappings to decide which type a concrete value belongs to.
The format for union’s $typeResolver is identical to interface’s.
|
Note
|
An example GraphQL application that uses union is unionTestApp.json used in the test union.feature
|
Hiding fields by role: @visible
Write @visible(roles: […]) on a field to restrict who sees it. RESTHeart declares the directive: do not declare it in your SDL.
type Employee {
name: String
department: String
salary: Float @visible(roles: ["hr", "admin"])
}
A caller whose roles do not include hr or admin gets a schema without salary. Introspection does not list it, and a query that asks for it gets a validation error: the field does not exist. A caller who may not see a field does not learn that it is there.
Undecorated fields are visible to everyone: visibility is opt-in per field, and adding the directive to a schema changes nothing until you write it on a field. An unauthenticated caller has no roles, so it sees only the fields no @visible restricts.
This also applies through MCP: the schema an agent introspects is the one its own roles can see.
Bson types
All primitive GraphQL types have been mapped to corresponding BSON types plus a set of custom GraphQL scalars types have been added:
GraphQL type |
Bson Type |
Example |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
Example
The following GraphQL type User defines the property _id to be of type ObjectId
type User {
_id: ObjectId
name: String
surname: String
email: String
posts: [Post]
}
Queries
In order to make a query you can use HTTP request with POST method and both content-type application/json and application/graphql. For instance:
application/json
curl -i -X POST "[RESTHEART-URL]/graphql/<app-uri>" \
-H "Authorization: Basic [BASIC-AUTH]" \
-H "Content-Type: application/json" \
-d '{
"query": "query test_operation($name: String){ userByName(_name: $name){name posts{text}} }",
"variables": { "name": "..." },
"operationName": "..."
}'
POST /graphql/<app-uri> HTTP/1.1
Host: [RESTHEART-URL]
Authorization: Basic [BASIC-AUTH]
Content-Type: application/json
{
"query": "query test_operation($name: String){ userByName(_name: $name){name posts{text}} }",
"variables": { "name": "..." },
"operationName": "..."
}
http POST "[RESTHEART-URL]/graphql/<app-uri>" \
"Authorization:Basic [BASIC-AUTH]" \
"Content-Type:application/json" \
query="query test_operation(\$name: String){ userByName(_name: \$name){name posts{text}} }" \
variables:='{ "name": "..." }' \
operationName="..."
application/graphql
curl -i -X POST "[RESTHEART-URL]/graphql/<app-uri>" \
-H "Authorization: Basic [BASIC-AUTH]" \
-H "Content-Type: application/graphql" \
-d '{
userByName(_name: "...") {
name
posts {
text
}
}
}'
POST /graphql/<app-uri> HTTP/1.1
Host: [RESTHEART-URL]
Authorization: Basic [BASIC-AUTH]
Content-Type: application/graphql
{
userByName(_name: "...") {
name
posts {
text
}
}
}
echo '{
userByName(_name: "...") {
name
posts {
text
}
}
}' | http POST "[RESTHEART-URL]/graphql/<app-uri>" \
"Authorization:Basic [BASIC-AUTH]" \
"Content-Type:application/graphql"
App Definition Caching
The caching of GQL App Definitions is automatically handled by the system.
All existing GQL apps are cached at startup. This behavior can be bypassed by disabling the graphAppsInitializer plugin, in which case each GQL app is cached upon its first request.
When a GQL app definition is created or updated, the cache on the RESTHeart instance handling the request is automatically updated.
In multi-instance deployments, the caches on other nodes are refreshed after a configurable Time to Revalidate (TTR) interval (configuration option /graphql/app-cache-ttr with default value of 60 seconds) by the graphAppsUpdater. This is also in charge of removing from the cache deleted apps.
For development or testing in multi-node setups, caching can be disabled by setting graphql/app-cache-enabled to false
Additionally, a new provider, gql-app-definition-cache, has been introduced. This provider is available to other plugins, allowing them to customize and extend the cache invalidation policy as needed.
Example usage
@Inject("gql-app-definition-cache")
LoadingCache<String, GraphQLApp> gqlAppDefsCache;
public void invalidateAll() {
this.gqlAppDefsCache.invalidateAll();
}
Limitations
The GraphQL service has the following limitations:
-
Read-only API: mutations are not supported; the GraphQL API is only intended for simplifying data fetching. To write data, the REST API must be used.
Response
The GraphQL API always responds with the content type application/graphql-response+json, following the GraphQL Over HTTP specs.
Possible Response Codes:
| HTTP Status Code | Description |
|---|---|
200 |
A valid GraphQL response has been generated, even if it contains errors (partial data). |
400 |
The request is invalid (e.g., incorrect JSON, malformed GraphQL query, non-existent fields in selection, etc.) or when the response only contains errors (i.e., |
404 |
The GraphQL app does not exist. |
405 |
Incorrect method used (not POST or OPTIONS). |
408 |
Request timed out due to the |
500 |
Connection error with MongoDB. |