Building REST API
This guide explains how to create API endpoints to access data filled in your database through Blockflow instances. It covers adding API resources, generating boilerplate code, implementing logic, and deploying the API.
Prerequisites
A Blockflow project set up with instances deployed
Local MongoDB running and filled with instance data (for testing)
Steps to Create an REST API Endpoint
1. Add API Resource to studio.yaml
In the root directory of your project, open the studio.yaml
file and add a resource of type api/rest
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: transactions
Type: api/rest
Slug: transactions
Handler: src/apis/transactions/index.transactionsHandler
2. Generate Boilerplate Code
Run the following command to generate boilerplate code:
blockflow codegen
3. Implement API Logic
Edit the generated file to implement your API logic. Here's an example of the boilerplate code:
import { ABind } from "@blockflow-labs/utils";
/**
* @dev API
* @param context object containing the response and request object
* @param bind init function for database wrapper methods
*/
export const transactionsHandler = async (context: any, bind: ABind) => {
// Implement your function handler logic for API here
let { request, response } = context;
// request contains query object. To access user query params use
let { user } = request.query;
};
4. Using ABind for Database Operations
ABind
provides methods to interact with your database:
find(filter, projection?, options?)
findOne(filter, projection?, options?)
exists(filter)
countDocuments(filter?)
aggregate(pipeline)
Use these methods to query and manipulate your data as needed.
5. Testing the API
To test your API locally:
Ensure your local MongoDB is running and filled with instance data.
Run the following command:
blockflow api-test
6. Deploying the API
Once testing is complete, deploy your API using:
blockflow api-deploy
Last updated