GraphQL Queries

GraphQL Overview

GraphQL is a query language for APIs and a runtime for executing those queries by using a type system you define for your data. It is used to abstract away having to write SQL as it enables clients to request exactly the data they need, often in a single request, which can be more efficient and easier to manage than constructing multiple SQL queries.

How is GraphQL different than SQL?

GraphQL differs from SQL in its approach to data retrieval and manipulation. SQL, a standard language for accessing and managing databases, is structured around predefined queries where the server defines what data can be retrieved and how. In contrast, GraphQL, primarily a query language for APIs, allows clients to request precisely the data they need, often in a single request. This flexibility in querying reduces the need for multiple SQL queries, optimizing data fetching and handling. Furthermore, GraphQL uses a type system to describe data, whereas SQL interacts directly with database schemas.

How is GraphQL used in SxT?

GraphQL serves as another entry point into SxT, in addition to our regular SQL REST APIs (which are also what you're hitting when you use the Studio query editor or the JDBC driver). You can use GraphQL to query your own tables in Space and Time as well as all indexed blockchain data that we provide, just like you can through the core SQL REST APIs.

What can you do with GraphQL?

Today, GraphQL can be used for the following functions:

  • Running queries and aggregating data
  • Discovering what schemas exist
  • Retrieving a specific GraphQL schema
  • Creating, updating, or deleting a GraphQL schema for your tables (or public tables)

What are some use cases for GraphQL?

GraphQL is ideal for use cases that are too complicated for standard SQL. Compared to SQL, it provides:

  • Custom/flexible data retrieval: GraphQL allows the user to define precisely what data they want to retrieve in a single query, rather than relying on a fixed set of server-defined endpoints.
  • Simpler data aggregation: GraphQL can be used to integrate and fetch data from various tables in Space and Time, making it easier to aggregate data. You can use it to query multiple tables that otherwise aren't joinable.

Execute GraphQL Using the Studio

Executing GraphQL directly from the Space and Time Studio is the easiest way to get started with GraphQL. Simply...

  1. Navigate to the Studio and log in.
  2. Under the Queries tab, select GraphQL.
  3. You'll see a list of GraphQL schemas available to explore. Choose one that you want to use, and a GraphQL query editor will pop up.
  4. Write your GraphQL queries! For a guide on writing GraphQL, see this resource.

Execute GraphQL Using APIs

You can also interact with our GraphQL APIs directly.

We have a single GraphQL API endpoint that you can use to execute GraphQL queries.

We also have a set of REST APIs that you can use to discover, manage, and edit existing GraphQL schemas. These APIs are not used to execute GraphQL, but rather to manage your schema and configuration.

GraphQL API

We provide a single Execute GraphQL API endpoint that you can use to perform queries against any existing GraphQL schemas. If you need to manage existing schemas or discover new schemas, use our REST APIs (see the below section).

Once you have a GraphQL schema you'd like to use, simply write up your GraphQL query like you would normally. Make sure to specify the schema name in the header and the input query will be validated against the schema you reference. In addition, any queries against permissioned tables will need to be authorized with biscuits (just like if you queried them via the SQL API) - so specify biscuits in the request body where necessary.

REST APIs

The GraphQL REST APIs can be used to manage and discover GraphQL schemas.

To find out what schemas exist: simply call the Discover GraphQL schemas API. You can search for both public and subscription schemas.

To look at a GraphQL schema: use the Retrieve GraphQL schema API.

To create a new GraphQL schema:: use the Create GraphQL schema API. You'll need an existing database schema, but the GraphQL schema will be automatically generated on your behalf - all you need to do is provide a name for the GraphQL schema, a scope for visibility (e.g., choose PUBLIC if you want to include public tables only), and the database schema identifier.

If you need to regenerate a GraphQL schema: use the Update GraphQL schema API. You might need to use this if you add or remove a table (i.e., change your data model).

If you need to delete a GraphQL schema: use the Delete GraphQL schema API.


Example GraphQL Query

Below is an example of how to create a GraphQL Schema, Build a query, and then Execute that query against the SxT GraphQL endpoint.

The examples below use the SXT CLI to keep the working code as OS and programming language agnostic as possible.

Step 1: Login to Space and Time Studio

To login to the Space and Time network using the CLI, make sure you've installed the Space and Time CLI and have a valid space and time user, then copy/paste the commands below into a terminal:

  1. Set environment variables (replacing values below with your SxT credentials) and login to the SxT network:
API_URL="https://api.spaceandtime.app"
USERID="your_userid"
USER_PUBLIC_KEY="your-public-key"
USER_PRIVATE_KEY="your-private-key"

sxtcli authenticate login --url=$API_URL --userId=$USERID --publicKey=$USER_PUBLIC_KEY --privateKey=$USER_PRIVATE_KEY
# assuming this file exists, containing user secrets:
. ~/.keys/.env

sxtcli authenticate login --url=$API_URL --userId=$USERID --publicKey=$USER_PUBLIC_KEY --privateKey=$USER_PRIVATE_KEY

This command will return two tokens:

  • ACCESS_TOKEN - used to authenticate any API calls to the network
  • REFRESH_TOKEN - used to request a new ACCESS_TOKEN
  1. Optionally, it's a good idea to copy the ACCESS_TOKEN to an environment variable. This can be done manually, i.e., ACCESS_TOKEN="eyJ0eXBlIjoiY..." or by directing the CLI output to a parser like awk:
ACCESS_TOKEN=$(sxtcli authenticate login --url=$API_URL --userId=$USERID --publicKey=$USER_PUBLIC_KEY --privateKey=$USER_PRIVATE_KEY | awk 'NR==2{ print $2 }' )
echo $ACCESS_TOKEN
  1. Optionally, let's test our ACCESS_TOKEN by submitting a request to the network. Assuming your ACCESS_TOKEN is stored in an environment variable as above, you can retrieve your UserID details, or run queries (with a valid subscription or trial):
curl --request GET \
     --url https://api.spaceandtime.app/v1/auth/validtoken \
     --header 'accept: application/json' \
     --header "authorization: Bearer $ACCESS_TOKEN"
curl --request POST \
--url "https://api.spaceandtime.app/v1/sql" \
--header "accept: application/json" \
--header "authorization: Bearer $ACCESS_TOKEN" \
--header "content-type: application/json" \
--data '{
    "sqlText": "Select count(*) as Blocks_Yesterday from Ethereum.Blocks where time_stamp between current_date-1 and current_date"
}'

👍

Contrats, you've authenticated to the Space and Time network and generated an ACCESS_TOKEN using the CLI!

Hint: If you plan to use the CLI frequently, you might consider:


Step 2: Create GraphQL Schema (required once)

GraphQL queries need a GraphQL "schema" to operate within, which is tied to a single Space and Time Database schema. You can freely name your GraphQL Schema anything, but it's a best practice to include the DB schema it refers to. You can also have many GraphQL schemas tied to the same DB schema.

To create a public GraphQL schema named "SXTDemo_Schema" that points to the "SXTDemo" DB schema, you can run call the API:

curl --request POST \
     --url 'https://api.spaceandtime.app/v1/graphql/schemas?schemaName=SXTDemo&scope=PUBLIC&name=SXTDemo_Schema' \
     --header 'accept: application/json' \
     --header "authorization: Bearer $ACCESS_TOKEN"

This will return a long JSON document, which describes all the possible functions supported by the GraphQL endpoint. This is used by GraphQL UI builders and apps.

Note that GraphQL schemas can be "Public" (visible by anyone) or "Subscription" (visible only to members of your subscription). There are no biscuits needed for schemas or schema creation.

📘

Space and Time Studio has a GraphQL UI which makes writing GraphQL queries dramatically easier. Check it out here!


Step 3: Execute GraphQL Query

To execute a GraphQL query using APIs, you'll first need to build a GraphQL query text. GraphQL is an expressive language, making a full tutorial out-of-scope, however at its most basic:

query Microsoft_Stock_Query 
{
  SXTDEMO_STOCKS(SYMBOL: {Equals: "MSFT"}, STOCK_DATE: {Equals: "2024-01-26"})
  {
    SYMBOL
    STOCK_VOLUME
    STOCK_ADJCLOSE
    STOCK_DATE
  }
}

If we were to map the GraphQL query above to a SQL query:

  • Microsoft_Stock_Query - is the arbitrary name of the query, and can be anything
  • SXTDEMO_STOCKS - name of the table (must be in the DB schema associated with the GraphQL schema)
    • (SYMBOL: ... - this is the WHERE statement
  • { SYMBOL STOCK_VOLUME... this is the SELECT column list

For full documentation on GraphQL, check out this resource.

🚧

GraphQL is a sophisticated data retrieval language, not an analytic language - meaning there are things that SQL can do easily that GraphQL cannot, and vice versa.

Once you've authored your GraphQL query text, you can submit using the API:

  1. curl --request POST \
         --url https://api.spaceandtime.app/v1/graphql \
         --header 'accept: application/json' \
         --header 'content-type: application/json' \
         --header 'schema: SXTDEMO_SCHEMA' \
         --header "authorization: Bearer $ACCESS_TOKEN" \
         --data '{
      "query": "query MyQuery {   SXTDEMO_STOCKS(SYMBOL: {Equals: \"MSFT\"}, STOCK_DATE: {Equals: \"2024-01-26\"}) {     SYMBOL     STOCK_DATE     STOCK_ADJCLOSE     STOCK_VOLUME   } }"
    }'
    
    

📘

Space and Time Studio has a GraphQL UI which makes writing GraphQL queries dramatically easier. Check it out here!

Note that the table above is a PUBLIC_READ table, meaning no biscuits are required. However if you are running on PERMISSIONED tables, you can add biscuits to the /graphql request, similar to any other permissioned request. For full details, see the GraphQL Execute Query API documentation.