A
A
Ankr Docs
Search…
Polkadot Examples
The following simple usage examples are to support you to get started.
For more details, please refer to the official documentation

Simple Example

API HTTPS Endpoint

Go
Javascript
Python
Curl
1
package main
2
3
import (
4
"fmt"
5
"github.com/centrifuge/go-substrate-rpc-client/client"
6
"github.com/centrifuge/go-substrate-rpc-client/rpc/author"
7
"github.com/centrifuge/go-substrate-rpc-client/rpc/chain"
8
"github.com/centrifuge/go-substrate-rpc-client/rpc/state"
9
"github.com/centrifuge/go-substrate-rpc-client/rpc/system"
10
)
11
12
13
func main() {
14
const url_basic = "https://username:[email protected]/xxxxx/xxxxx/polkadot/full/main" // basic authentication
15
const url_token = "https://apis.ankr.com/xxxxx/xxxxx/polkadot/full/main" // token
16
17
cl,err := client.Connect("choose url_basic or url_token by your created type")
18
19
if err != nil {
20
panic(err)
21
}
22
23
newRPC, err := NewRPC(cl)
24
if err != nil {
25
panic(err)
26
}
27
28
hash, err := newRPC.Chain.GetFinalizedHead()
29
if err != nil {
30
panic(err)
31
}
32
33
fmt.Println(hash.Hex())
34
35
}
36
37
type RPC struct {
38
Author *author.Author
39
Chain *chain.Chain
40
State *state.State
41
System *system.System
42
Client *client.Client
43
}
44
45
func NewRPC(cl client.Client) (*RPC, error) {
46
st := state.NewState(cl)
47
return &RPC{
48
Author: author.NewAuthor(cl),
49
Chain: chain.NewChain(cl),
50
State: st,
51
System: system.NewSystem(cl),
52
client: cl,
53
}, nil
54
}
Copied!
1
const { HttpProvider } = require('@polkadot/api');
2
3
const url_basic = "https://username:[email protected]/xxxxx/xxxxx/polkadot/full/main" // basic authentication
4
const url_token = "https://apis.ankr.com/xxxxx/xxxxx/polkadot/full/main" // token
5
6
const provider = new HttpProvider('choose url_basic or url_token by your created type')
7
8
provider.send("chain_getFinalizedHead", []).then(hash => {
9
console.log(`the finalized block hash is ${hash}`)
10
})
11
provider.send("chain_getBlockHash", []).then(hash => {
12
console.log(`the block hash is ${hash}`)
13
provider.send("chain_getBlock", [hash]).then(value => {
14
console.log(`the block number is ${value.block.header.number}`)
15
console.log(`the block detail is ${JSON.stringify(value)}`)
16
})
17
})
Copied!
1
import json
2
3
import requests
4
5
6
def create_req_body(r_id, method, params):
7
data = {
8
"jsonrpc": "2.0",
9
"id": r_id,
10
"method": method,
11
"params": params
12
}
13
return json.dumps(data)
14
15
16
class TestDot:
17
def test_dot_basic_auth(self):
18
"""
19
basic auth example
20
"""
21
headers = {"Content-Type": "application/json"}
22
url = 'https://apis.ankr.com/xxxxx/xxxxx/polkadot/full/main'
23
auth = ("your username", "your password")
24
25
req_finalized_head = create_req_body(1, "chain_getFinalizedHead", [])
26
r = requests.post(url=url, headers=headers, auth=auth, data=req_finalized_head)
27
res_hash = r.json()['result']
28
print('the finalized block hash is ' + res_hash)
29
30
req_block = create_req_body(2, "chain_getBlock", [res_hash])
31
r = requests.post(url=url, headers=headers, auth=auth, data=req_block)
32
block_number = r.json()['result']['block']['header']['number']
33
print('the block number is ' + block_number)
34
print('the block detail is ' + r.text)
35
36
def test_dot_token(self):
37
"""
38
token example
39
"""
40
headers = {"Content-Type": "application/json"}
41
url = 'https://apis.ankr.com/xxxxx/xxxxx/polkadot/full/main'
42
43
req_finalized_head = create_req_body(1, "chain_getFinalizedHead", [])
44
r = requests.post(url=url, headers=headers, data=req_finalized_head)
45
res_hash = r.json()['result']
46
print('the finalized block hash is ' + res_hash)
47
48
req_block = create_req_body(2, "chain_getBlock", [res_hash])
49
r = requests.post(url=url, headers=headers, data=req_block)
50
block_number = r.json()['result']['block']['header']['number']
51
print('the block number is ' + block_number)
52
print('the block detail is ' + r.text)
Copied!
1
# basic authentication
2
$ curl -H "Content-Type: application/json" -u "username:password" https://apis.ankr.com/xxxxx/xxxxx/polkadot/full/main -d '{"jsonrpc":"2.0","method":"chain_getBlock","params":[],"id":1}'
3
4
# basic authentication way two
5
$ curl -H "Content-Type: application/json" https://username:[email protected]/xxxxx/xxxxx/polkadot/full/main -d '{"jsonrpc":"2.0","method":"chain_getBlock","params":[],"id":1}'
6
7
# token
8
$ curl -H "Content-Type: application/json" https://apis.ankr.com/xxxxx/xxxxx/polkadot/full/main -d '{"jsonrpc":"2.0","method":"chain_getBlock","params":[],"id":1}'
Copied!

Websocket (WSS) endpoint

Curl (wscat)
Go
Javascript
Javascript (ws)
Python
1
# basic authentication
2
$ wscat -c wss://username:[email protected]/wss/xxxxx/xxxxx/polkadot/full/main
3
4
# token
5
$ wscat -c wss://apis.ankr.com/wss/xxxxx/xxxxx/polkadot/full/main
6
7
wait connected...
8
9
# subscribe
10
> {"jsonrpc": "2.0", "id": 1, "method": "chain_subscribeNewHeads", "params": []}
11
12
# unsubscribe
13
> {"jsonrpc": "2.0", "id": 2, "method": "chain_unsubscribeNewHeads", "params": ["The result value returned after successful subscription"]}
Copied!
1
package main
2
3
import (
4
"fmt"
5
"github.com/centrifuge/go-substrate-rpc-client/client"
6
"github.com/centrifuge/go-substrate-rpc-client/rpc/author"
7
"github.com/centrifuge/go-substrate-rpc-client/rpc/chain"
8
"github.com/centrifuge/go-substrate-rpc-client/rpc/state"
9
"github.com/centrifuge/go-substrate-rpc-client/rpc/system"
10
"time"
11
)
12
13
14
func main() {
15
const url_basic = "wss://username:[email protected]/wss/xxxxx/xxxxx/polkadot/full/main" // basic authentication
16
const url_token = "wss://apis.ankr.com/wss/xxxxx/xxxxx/polkadot/full/main" // token
17
18
cl,err := client.Connect("choose url_basic or url_token by your created type")
19
20
if err != nil {
21
panic(err)
22
}
23
24
newRPC, err := NewWebsocket(cl)
25
if err != nil {
26
panic(err)
27
}
28
29
sub, err := newRPC.Chain.SubscribeNewHeads()
30
if err != nil {
31
panic(err)
32
}
33
34
fmt.Println("---subscribe-----")
35
36
go func() {
37
time.Sleep(10 * time.Second)
38
fmt.Println("---unsubscribe-----")
39
sub.Unsubscribe()
40
}()
41
42
go func() {
43
for c := range sub.Chan {
44
fmt.Println(c.Number)
45
}
46
}()
47
48
<-sub.Err()
49
50
}
51
52
type Websocket struct {
53
Author *author.Author
54
Chain *chain.Chain
55
State *state.State
56
System *system.System
57
Client *client.Client
58
}
59
60
func NewWebsocket(cl client.Client) (*Websocket, error) {
61
st := state.NewState(cl)
62
return &Websocket{
63
Author: author.NewAuthor(cl),
64
Chain: chain.NewChain(cl),
65
State: st,
66
System: system.NewSystem(cl),
67
client: cl,
68
}, nil
69
}
Copied!
1
const {ApiPromise, WsProvider} = require('@polkadot/api');
2
3
async function main() {
4
5
const url_token = "wss://apis.ankr.com/wss/xxxxx/xxxxx/polkadot/full/main" // Only the token authentication method is supported here
6
const provider = new WsProvider(url);
7
8
const api = await ApiPromise.create({ provider });
9
10
const [chain, nodeName, nodeVersion] = await Promise.all([
11
api.rpc.system.chain(),
12
api.rpc.system.name(),
13
api.rpc.system.version()
14
]);
15
16
console.log(`You are connected to chain ${chain} using ${nodeName} v${nodeVersion}`);
17
18
let count = 0;
19
20
await api.rpc.chain.subscribeNewHeads((header) => {
21
console.log(`Chain is at block: #${header.number}`);
22
23
if (++count === 5) {
24
process.exit(0);
25
}
26
});
27
}
28
29
main().catch(console.error);
Copied!
1
const WebSocket = require('ws');
2
3
const url_basic = 'wss://username:[email protected]/wss/xxxxx/xxxxx/polkadot/full/main' // basic authentication
4
const url_token = 'wss://[email protected]/wss/xxxxx/xxxxx/polkadot/full/main' // token
5
6
const request = '{"jsonrpc": "2.0", "id": 1, "method": "chain_subscribeNewHeads"}';
7
8
const ws = new WebSocket('choose url_basic or url_token by your created type');
9
10
ws.on('open', function open() {
11
ws.send(request);
12
});
13
14
let count = 0;
15
16
ws.on('message', function incoming(data) {
17
const res = JSON.parse(data)
18
console.log(JSON.stringify(res));
19
if (++count === 5) {
20
process.exit(0);
21
}
22
});
Copied!
1
import asyncio
2
import json
3
import time
4
5
import websockets
6
7
8
def create_req_body(r_id, method, params):
9
data = {
10
"jsonrpc": "2.0",
11
"id": r_id,
12
"method": method,
13
"params": params
14
}
15
return json.dumps(data)
16
17
18
async def do_wss(url):
19
req_json = create_req_body(1, "chain_subscribeNewHeads", [])
20
async with websockets.connect(url) as wss:
21
await wss.send(req_json)
22
subscription_response = await wss.recv()
23
print(subscription_response)
24
sub_hex = json.loads(subscription_response)['result']
25
req_json = create_req_body(2, "chain_unsubscribeNewHeads", [sub_hex])
26
27
start_time = int(time.time())
28
end_time = start_time + 5
29
while end_time > int(time.time()):
30
recv_data = await wss.recv()
31
print(recv_data)
32
print('\n')
33
await wss.send(req_json)
34
unsubscription_response = await wss.recv()
35
print(unsubscription_response)
36
37
38
class TestWSS:
39
40
def test_wss(self):
41
url_basic = 'wss://username:[email protected]/wss/xxxxx/xxxxx/polkadot/full/main' # basic authentication
42
url_token = 'wss://apis.ankr.com/wss/xxxxx/xxxxx/polkadot/full/main' # token
43
asyncio.get_event_loop().run_until_complete(do_wss('choose url_basic or url_token by your created type'))
Copied!
Last modified 30d ago
Copy link