Edit this page

REST API

REST API is used to communicate with Cube.js backend. All requests are prefixed with basePath described in Backend Server Core. By default it's /cubejs-api.

Cube.js uses API Token for requests' authorization and also for passing additional user context, which could be used in the USER_CONTEXT object in the Data Schema.

The API Token is passed via the Authorization Header. The token itself is a JSON Web Token, the Security section describes how to generate it.

In the development environment the token is not required for authorization, but you can still use it to pass a user context.

curl -H "Authorization: EXAMPLE-API-TOKEN" https://example.com/cubejs-api/v1/sql

If the request takes too long to be processed, Cube.js Backend responds with { "error": "Continue wait" } and 200 status code. To get the data requested, simply retry your request a bit later.

Possible reasons of Continue wait:

  • The query requested is heavy and it takes some time for the database to process it.
  • There are many queries requested and Cube.js backend queues them to save database from overloading.

Cube.js REST API has basic errors and HTTP Error codes for all requests.

StatusError responseDescription
400Error messageGeneral error. It may be a database error, timeout, or other issue. Check error message for details.
403Authorization header isn't setYou didn't provide an auth token. Provide a valid API Token or disable authorization.
403Invalid tokenThe auth token provided is not valid. It may be expired or have invalid signature.
500Error messageCube.js internal server error. Check error message for details.

For monitoring tools such as Cube Cloud proper request span annotation should be provided in x-request-id header of a request. Each request id should consist of two parts: spanId and requestSequenceId which define x-request-id as whole: ${spanId}-span-${requestSequenceId}. Values of x-request-id header should be unique for each separate request. spanId should define user interaction span such us Continue wait retry cycle and it's value shouldn't change during one single interaction.

Get data for a query.

ParameterDescription
queryURL encoded Cube.js Query

Response

  • query - The query passed via params
  • data - Formatted dataset of query results.
  • annotation - Metadata for query. Contains descriptions for all query items.

    • title - Human readable title from data schema.
    • shortTitle - Short title for visualization usage (ex. chart overlay)
    • type - Data type

Example request:

curl \
 -H "Authorization: EXAMPLE-API-TOKEN" \
 -G \
 --data-urlencode 'query={"measures":["Users.count"]}' \
 http://localhost:4000/cubejs-api/v1/load

Example response:

{
  query:{
    measures:[
      "Users.count"
    ],
    filters:[],
    timezone:"UTC",
    dimensions:[],
    timeDimensions:[]
  },
  data:[
    {
      "Users.count":"700"
    }
  ],
  annotation:{
    measures:{
      "Users.count":{
        title:"Users Count",
        shortTitle:"Count",
        type:"number"
      }
    },
    dimensions:{},
    segments:{},
    timeDimensions:{}
  }
}

NOTE: Currently all fetched numericals are returned in the same format as driver returns it without any additional processing. Most of drivers return numerical values as strings instead of javascript integer or float to ensure there's no loss of significance. Client code should take care of parsing such numerical values.

Get the SQL Code generated by Cube.js to be executed in the database.

ParameterDescription
queryURLencoded Cube.js Query

Response

  • sql - JSON Object with the following properties

    • sql - Formatted SQL query with parameters
    • order - Order fields and direction used in SQL query
    • cacheKeyQueries - Key names and TTL of Cube.js data cache
    • preAggregations - SQL queries used to build pre-aggregation tables

Example request:

curl \
 -H "Authorization: EXAMPLE-API-TOKEN" \
 -G \
 --data-urlencode 'query={"measures":["Users.count"],
 "timeDimensions":[{"dimension": "Users.createdAt","granularity":"day","dateRange":["2019-03-01","2019-03-31"]}]}' \
 http://localhost:4000/cubejs-api/v1/sql

Example response:

{
  sql:{
    sql:[
      "SELECT\n      date_trunc('day', (users.created_at::timestamptz AT TIME ZONE 'UTC')) \"users.created_at_date\", count(users.id) \"users.count\"\n    FROM\n      public.users AS users\n  WHERE (users.created_at >= $1::timestamptz AND users.created_at <= $2::timestamptz) GROUP BY 1 ORDER BY 1 ASC LIMIT 10000",
      [
        "2019-03-01T00:00:00Z",
        "2019-03-31T23:59:59Z"
      ]
    ],
    timeDimensionAlias:"users.created_at_date",
    timeDimensionField:"Users.createdAt",
    order:[
      {
        id:"Users.createdAt",
        desc:false
      }
    ],
    cacheKeyQueries:{
      queries:[
        [
          "select max(users.created_at) from public.users AS users",
          []
        ]
      ],
      renewalThreshold:21600
    },
    preAggregations:[]
  }
}

Get meta-information for cubes defined in data schema

Response

  • cubes - Array of cubes

    • name - Codename of the cube
    • title - Human-readable cube name
    • measures - Array of measures defined within this cube
    • dimensions - Array of dimensions defined within this cube
    • segments - Array of segments defined within this cube

Example request:

curl \
 -H "Authorization: EXAMPLE-API-TOKEN" \
 -G \
 http://localhost:4000/cubejs-api/v1/meta

Example response:

{
  cubes:[
    {
      name:"Users",
      title:"Users",
      connectedComponent:1,
      measures:[
        {
          name:"Users.count",
          title:"Users Count",
          shortTitle:"Count",
          aliasName:"users.count",
          type:"number",
          aggType:"count",
          drillMembers:[
            "Users.id",
            "Users.city",
            "Users.createdAt"
          ]
        }
      ],
      dimensions:[
        {
          name:"Users.city",
          title:"Users City",
          type:"string",
          aliasName:"users.city",
          shortTitle:"City",
          suggestFilterValues:true
        }
      ],
      segments:[]
    }
  ]
}

Trigger scheduled refresh run to refresh pre-aggregations.

NOTE: Single call to this API may be not enough to refresh everything is pending. This call just populates queue with refresh workload and it should be continously called until refresh jobs are done. Otherwise refresh jobs will be marked orphaned and they will be removed from queue.

Learn more about scheduled refresh here.

ParameterDescription
queryingOptionsOptional URL encoded Cube.js Query options such as timezone

Empty object response if scheduled successfully.

Example request:

curl \
 -H "Authorization: EXAMPLE-API-TOKEN" \
 -G \
 --data-urlencode 'queryingOptions={"timezone":"UTC"}' \
 http://localhost:4000/cubejs-api/v1/run-scheduled-refresh