Get Started With Netlify Graph

Netlify Labs feature

This feature is available through Netlify Labs, which helps us collect early feedback on newer features. You may notice some changes to this feature’s functionality as we develop it further. We recommend trying it out in test sites or non-production environments only. Learn more in our Netlify Labs doc.

Netlify Graph can be a powerful addition to your site, but there’s a lot consider - especially if you’re new to GraphQL. This section will guide you through a basic use case for Netlify Graph.

At a glance, here’s what you need to get started:

  1. Create a Graph Explorer cloud sandbox
  2. Connect an API or service
  3. Create queries
  4. Work locally
  5. Use an operation handler in your project

# What is Graph Explorer?

Graph Explorer is a visual editor that helps you write GraphQL queries, mutations, subscriptions, and fragments. You can create your own queries or choose from many different example queries. Graph Explorer will help you explore the schema of an API, provide autocompletion for queries, and much more.

You can get the best Netlify Graph experience by starting with Graph Explorer. When you're happy with your work in Graph Explorer, you can autogenerate handlers for your queries, mutations, subscriptions, and fragments and sync them to your local project. After that, you can use them just like a Netlify Function.

# Create a Graph Explorer cloud sandbox

Before creating GraphQL queries, mutations, subscriptions, or fragments locally, you can create and test them in a cloud sandbox in the Netlify UI. This streamlines testing, ensuring you get the data you need before working with that data in your project.

To create a Graph Explorer cloud sandbox

  1. In the Netlify UI, select your site, then navigate to the Graph tab.
  2. In Graph Explorer, select No session on the right-hand side.
  3. Select Create cloud sandbox from the drop down menu.

This will create a cloud sandbox for your site. Queries, mutations, subscriptions, and fragments in the sandbox do not affect your local project unless you specifically decide to claim the sandbox and sync them to your local project. You can have multiple sandboxes.

# Connect an API or service

Netlify Graph connects to a defined set of APIs and services. Refer to Supported API providers for the full list. This list will continue to expand in the future.

To connect an API

  1. Create a cloud sandbox or select an existing one for your site.

  2. Find a service you want to integrate with from the list of services on the left side of Graph Explorer that has an API option.

  3. Connect the API by selecting the toggle next to API.

  4. Select an example query or create your own.

  5. Select Run query to get your data in Graph Explorer.

  6. If needed, grant access to your service account by selecting the Grant this session access prompt and entering your account information.

# Create queries

Queries are a staple of GraphQL and the main way to interact with a GraphQL API. When you use a query, you are asking the API to return data in a certain shape. If needed, the query can have parameters. With Netlify Graph, you can have a single query that fetches data from multiple APIs in a single call. This is an easier way of integrating APIs into your project.

In Netlify Graph, you can reuse an existing query from an example or create your own. If you are new to GraphQL, we suggest trying out example queries to get a sense of the experience.

# Create a new query from an example

Not all APIs and services have example queries.

To create a new query from an example

  1. Create a cloud sandbox or select an existing one for your site.

  2. On the left side of Graph Explorer, find a service you want to integrate with from the list of services.

  3. Select Examples, then choose an example from the list of examples.

  4. Under Query variables, fill in the fields as needed, then select Run query.

    If needed, grant access to your service account by selecting the prompt and entering your account information. You can experiment by changing the query variables and selecting Run again until you get the results you need.

  5. If your query runs successfully and you want to keep it, select Save query.

You can access example queries at any time in the same way as above. You can also use the folder icon on the graphical interface.

# Create a custom query

If you can’t find example queries that fit your need, or you already have a good understanding of GraphQL semantics, you can start a custom (blank) query and take it from there.

To create a custom query

  1. Create a cloud sandbox or select an existing one for your site.

  2. On the left side of Graph Explorer, find a service you want to integrate with from the list of services.

  3. Select Create team operation, then select Query.

  4. Replace "ExampleQuery" with your own query name and compose your query.

  5. Select Run operation to get your data in Graph Explorer.

  6. If needed, grant access to your service account by selecting the prompt and entering your account information.

Your changes are saved automatically to your cloud sandbox.

# Work locally

To make working with Netlify Graph easier, Netlify CLI can generate strongly-typed handlers out of the queries you compose in Graph Explorer.

To use Netlify Graph in a local project

  1. Link a local project directory to a Netlify site
  2. Claim a cloud sandbox with Netlify CLI
  3. Generate operation handlers
  4. Use an operation handler in your project

Netlify Graph syncs your cloud sandbox with a local project by linking the two through Netlify CLI.

To link a Netlify site to a local project

  1. Ensure you have the latest version of Netlify CLI installed.
npm install netlify-cli -g
  1. In your terminal, navigate to the project you want to link (usually the repository root), then run netlify link.
  2. When prompted, select the git remote origin for your project.

# Claim a cloud sandbox with Netlify CLI

When you have a cloud sandbox with a query running in Graph Explorer, you can claim that cloud session locally with Netlify CLI. Claiming a cloud session attaches a local CLI session to the specified cloud session. This means you can sync changes between your local project and the cloud session.

When you claim a sandbox, Netlify CLI generates several helpful files in your local project. You don’t need to work directly with these files. Later, you can generate operation handlers to call in your code.

When claimed, any changes to an operation in Graph Explorer will be synced to the local copy as long as the CLI is running.

To claim a cloud sandbox

  1. Ensure you have the latest version of Netlify CLI installed.
npm install netlify-cli -g
  1. In Graph Explorer, right above the query area, select the Claim it! banner.

  2. In the new window, find Step 2 and copy the Netlify Dev command there.

  3. Run that command at the root of your local project.

    The command should resemble the following, but with your cloud session id: netlify dev --graph --sessionId=CLOUD_SESSION_ID

To learn more about the graph CLI commands, refer to the Netlify CLI documentation.

# Generate operation handlers

With Graph Explorer, you can generate handlers for your queries. These handlers are wrapped in Netlify Functions that you can call in your project.

Make sure that you have claimed a cloud sandbox before doing this.

To generate an operation handler

  1. Select an existing cloud sandbox.

  2. Claim the sandbox with Netlify CLI if you haven’t done so already.

  3. Select View team operations, then select the operation you want to generate a handler for.

  4. Ensure you have an active Netlify CLI connection by running netlify dev --graph --sessionId=CLOUD_SESSION_ID.

  5. On the right-hand side of Graph Explorer, select Generate operation handler, left of the folder icon.

  6. The CLI creates a handler for your operations.

    Each file uses your operation name as the file names and can be used just like a Netlify Function. For example, query GitHubOpenIssues becomes GitHubOpenIssues.js in your functions folder.

    If your CLI session was not running at this time, you can run netlify graph:handler OPERATION_NAME to generate a handler.

Auto-generated handlers are isolated to your CLI session until you commit them to your repo.

# Use an operation handler in your project

After generating an operation handler and syncing it to your local project, you can access that handler in your project’s code. Generated handlers are Netlify Functions and can be accessed just like any other Netlify Function.

To use an operation handler in your project

  1. Add an authentication token to your operation handlers
  2. Test your operation handlers locally with Netlify Dev
  3. Commit your changes and push to remote origin

# Add an authentication token to your operation handlers

With the deployed functions, you will also need to provide an authentication token before you can complete a request to an API provider. We recommend using the built-in Netlify Graph authentication mechanism. Check out the example for details.

Alternatively, you can update the handler code inside the netlify/functions folder in your site repository. Open the file that matches the name of the query that you’ve built in Graph Explorer, and modify the accessToken variable with your authentication token.

# Test your operation handlers locally with Netlify Dev

You can test your operation handlers locally by running netlify dev --graph at your project’s root.

Operation handlers initially appear as uncommitted changes in your local project under netlify/functions/YOUR_QUERY, which means that you need to call their endpoints like this: /.netlify/functions/YOUR_QUERY. Note the preceding slash and period.

# Commit your changes and push to remote origin

To deploy the operation handlers, commit the changes to your local project and push to your git remote origin. This starts a deploy of your Netlify site and its associated functions.

# Built-in authentication example

If you’ve used the built-in authentication mechanism with one of the supported services, you can use the Netlify Graph authentication token within the generated function body like this:

const accessToken = event.authlifyToken

This way, the service token will be automatically resolved by Netlify Graph, and you do not need to explicitly use any of the service-specific tokens.

When you want to invoke the function from your code, start by adding references to dependent packages:

import { Auth } from 'netlify-graph-auth';
import NetlifyGraphAuth = Auth.NetlifyGraphAuth;
import process from 'process';

To get the authentication tokens with the built-in tooling, you need to make sure that you have an instance of NetlifyGraphAuth that you can pass to the function request, that contains your site identifier:

const auth = new NetlifyGraphAuth({
    siteId: context.env.SITE_ID,
});

In the example above, the SITE_ID is stored in an environment variable. Depending on the framework you are using, you may want to configure additional options to make the environment variables available during build time.

To invoke the function, you can build a wrapper similar to the one below (it’s automatically provided in your generated handler file), that passes the authentication headers from the NetlifyGraphAuth object:

async function fetchGetIssueBreakdown(netlifyGraphAuth, params) {
    const { after } = params || {};
    const resp = await fetch(`/.netlify/functions/GetIssueBreakdown`,
        {
            method: "POST",
            body: JSON.stringify({ "after": after }),
            headers: {
                ...netlifyGraphAuth?.authHeaders()
            }
        });
    const text = await resp.json();
    console.log(text);
    return text;
}

We recommend that you use Graph Authentication to connect to your service of choice through the Netlify UI, then use the token from the JavaScript or TypeScript code. This is the most streamlined approach to handling API requests with Netlify Graph.

# End-to-end example

For an end-to-end example that demonstrates how to use Netlify Graph with GitHub, Graph Explorer, and Graph Authentication, refer to Gravity. This is an open-source project that computes relationships between GitHub issues and the number of references they have.