Building GraphQL APIs

This guide explains how to create custom GraphQL API endpoints to access data filled in your database through Blockflow instances. They are the fastest mean to access databases filled by instances.

Prerequisites

  • A Blockflow project set up with instances deployed

  • Local MongoDB running and filled with instance data (for testing)

Steps to Create an GraphQL API Endpoint

1. Add GraphQL API Resource to studio.yaml

In the root directory of your project, open the studio.yaml file and add a resource of type api/graphql in the Resources array:

name: Router Nitro
description: Indexing cross chain transfers on router nitro protocol
userId: xxxx-xxxx-xxxx
projectId: xxxx
user: prady
schema:
  file: ./studio.schema.ts
Resources:
    Name: tranasctions
    Type: api/graphql
    Slug: test
    Handlers:
      resolver: src/handlers/resolver.transactionResolvers
      typedefs: src/handlers/typedef.transactionTypeDefs

2. Generate Boilerplate Code

Run the following command to generate boilerplate code:

blockflow codegen

3. Implement GraphQL API Logic

Two files are created. Edit the generated files to implement your API logic. Here's an example of the boilerplate code:

import { ABind } from "@blockflow-labs/utils";
/**
 * @dev GRAPHQL RESOLVER
 * @param bind init function for database wrapper methods
 */
export const transactionsResolvers = async (bind: ABind) => {
  // Implement your logic for Resolver here
};
import { ABind } from "@blockflow-labs/utils";
/**
 * @dev GRAPHQL TYPEDEFS
 */
export const transactionsTypeDefs = () => {
  // Write your typeDefs here
};

4. Using ABind for Database Operations

ABind provides methods to interact with your database:

  • find(filter, projection?, options?)

Use these methods to query and manipulate your data as needed.

5. Testing the GraphQL API

To test your API locally:

  1. Ensure your local MongoDB is running and filled with instance data.

  2. Run the following command:

blockflow graphql-test

6. Deploying the API

Once testing is complete, deploy your GraphQL API using:

blockflow graphql-deploy

Last updated