Connecting WebSocket

Public Node API provides features identical to KAS Node API without a separate authentication process. You can execute API features by connecting WebSocket.

Connecting WebSocket

This page describes the feature of WebSocket, which Public Node API supports. You can establish a two-way handshake between you and Endpoint Node. Unlike Klaytn Node API, Public Node API doesn't specify network by x-chain-id, and KAS Credentials are also not required. It configures its path according to the Klaytn network. Enter cypress for Klaytn mainnet and baobab for Klaytn testnet. Please note that code snippets on this page connect to Baobab network.

wscat --connect "wss://public-node-api.klaytnapi.com/v1/baobab/ws"

klay_blockNumber

You need the latest block number on Klaytn to check the most recent data about your account, such as account balance and account key type. Connect to WebSocket and request the newest block number as follows.

// Request
wscat --connect "wss://public-node-api.klaytnapi.com/v1/baobab/ws"
> {"jsonrpc":"2.0", "id": 0.43, "method": "klay_blockNumber", "params": [ ] }

// Response
< {"jsonrpc":"2.0","id":0.43,"result":"0x4d418ff"}

For more details on making API requests, please refer to this link.

klay_subscribe

Using klay_subscribe, you can create a new subscription to specific events. Every subscription returns an ID, and the notification contains all event data and subscription ID. If your notification parameter is "NewHeads", it notifies whenever a new block is added; another parameter "logs" notifies log data on a new block. The subscription will be disconnected and removed when no ping or request is made within 60 seconds.

The sample below shows the request and response with "NewHeads" parameter. To input "logs", refer to [klay_newFilter] (https://docs.klaytn.foundation/dapp/json-rpc/api-references/klay/filter#klay_newfilter) to check the required objects.

For more details on making API requests, please refer to this link.

klay_unsubscribe

klay_unsubscribe makes you stop observing the specific event notifications by calling klay_subscribe. Input an ID as a parameter to specify the event you want to unsubscribe. When the subscription is completely canceled, it returns true as a result.

For more details on making API requests, please refer to this link.

Last updated

Was this helpful?