You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Hyperledger Fabric v1.0 first-network开启REST API实现链码调用技术问询

Got it, let's tackle how to add a REST API layer to your running first-network so you can interact with it over REST in your private network. Here are the most practical approaches tailored for Fabric v1.0:

方案1:基于Fabric Node SDK + Express.js构建自定义REST服务

This is the most flexible option—you’ll have full control over the API logic, which is perfect for your v1.0 environment.

  • Step 1: Prepare dependencies
    Make sure you have Node.js (v8.x is recommended for Fabric v1.0 compatibility) and npm installed. Initialize a new project directory:

    mkdir fabric-rest-api && cd fabric-rest-api
    npm init -y
    npm install fabric-client fabric-ca-client express body-parser --save
    
  • Step 2: Write SDK connection logic
    Copy the crypto-config folder and relevant config files from your first-network directory into this REST project (or reference their original paths directly). Create a fabric-client.js file to wrap network connection, channel access, and user identity logic:

    const FabricClient = require('fabric-client');
    const path = require('path');
    
    async function getFabricClient(userName) {
      const client = new FabricClient();
      const channel = client.newChannel('mychannel');
      const peer = client.newPeer('grpc://localhost:7051'); // Peer0.org1 address from first-network
      channel.addPeer(peer);
      
      // Load user identity
      const storePath = path.join(__dirname, 'hfc-key-store');
      const stateStore = await FabricClient.newDefaultKeyValueStore({ path: storePath });
      client.setStateStore(stateStore);
      const cryptoSuite = FabricClient.newCryptoSuite();
      const cryptoStore = FabricClient.newCryptoKeyStore({ path: storePath });
      cryptoSuite.setCryptoKeyStore(cryptoStore);
      client.setCryptoSuite(cryptoSuite);
      
      const user = await client.getUserContext(userName, true);
      if (!user || user.isEnrolled() === false) {
        throw new Error(`User ${userName} not enrolled`);
      }
      return { client, channel, user };
    }
    module.exports = { getFabricClient };
    
  • Step 3: Build REST endpoints
    Create a server.js file to implement endpoints for chaincode deployment and invocation:

    const express = require('express');
    const bodyParser = require('body-parser');
    const { getFabricClient } = require('./fabric-client');
    
    const app = express();
    app.use(bodyParser.json());
    const PORT = 3000;
    
    // Install chaincode endpoint
    app.post('/chaincode/install', async (req, res) => {
      try {
        const { chaincodeName, chaincodePath, chaincodeVersion } = req.body;
        const { client, user } = await getFabricClient('Admin@org1.example.com');
        
        const request = {
          targets: [client.newPeer('grpc://localhost:7051')],
          chaincodePath: chaincodePath,
          chaincodeId: chaincodeName,
          chaincodeVersion: chaincodeVersion
        };
        const results = await client.installChaincode(request);
        res.status(200).json({ success: true, results });
      } catch (err) {
        res.status(500).json({ success: false, error: err.message });
      }
    });
    
    // Invoke chaincode endpoint
    app.post('/chaincode/invoke', async (req, res) => {
      try {
        const { chaincodeName, fcn, args } = req.body;
        const { channel, user } = await getFabricClient('Admin@org1.example.com');
        
        const request = {
          chaincodeId: chaincodeName,
          fcn: fcn,
          args: args,
          userContext: user
        };
        const response = await channel.sendTransactionProposal(request);
        const proposalResponses = response[0];
        const proposal = response[1];
        const isProposalGood = proposalResponses.every(resp => resp.response && resp.response.status === 200);
        
        if (isProposalGood) {
          const transactionId = proposalResponses[0].txId;
          const sendTxReq = {
            proposalResponses: proposalResponses,
            proposal: proposal
          };
          const txResult = await channel.sendTransaction(sendTxReq);
          res.status(200).json({ success: true, transactionId, txResult });
        } else {
          res.status(400).json({ success: false, error: 'Proposal failed' });
        }
      } catch (err) {
        res.status(500).json({ success: false, error: err.message });
      }
    });
    
    app.listen(PORT, '0.0.0.0', () => {
      console.log(`REST API server running on http://0.0.0.0:${PORT}`);
    });
    
  • Step 4: Run the service and test
    Ensure your first-network is up and running, then start the REST server:

    node server.js
    

    Test the endpoints with curl or Postman. For example, invoke the sample chaincode:

    curl -X POST http://your-server-ip:3000/chaincode/invoke -H "Content-Type: application/json" -d '{"chaincodeName":"mycc","fcn":"invoke","args":["a","b","10"]}'
    
方案2: Use Fabric REST Gateway (v1.4+ official recommendation, v1.0 requires adaptation)

The official Fabric REST Gateway was introduced in v1.4. If you’re willing to upgrade your Fabric version to v1.4 (which is compatible with v1.0 chaincodes), you can use this official component to reduce custom code. However, if you need to stay on v1.0, Scheme 1 is more reliable.

Key Notes
  • Intranet access configuration: To allow other machines in your private network to access the API, bind the server to 0.0.0.0 instead of localhost, and ensure your firewall opens the corresponding port (e.g., 3000).
  • Identity management: The example uses the Admin user—for production, implement finer-grained access control with different user identities for each organization.
  • Chaincode path: When installing chaincode, set chaincodePath to point to the chaincode directory in first-network (e.g., ../first-network/chaincode/go/chaincode_example02) or copy the chaincode to your REST project directory.

内容的提问来源于stack exchange,提问作者AshT

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.21 07:35:14