Cosmos_rpc
Chapter 16: Cosmos RPC & API Configuration
Section titled “Chapter 16: Cosmos RPC & API Configuration”Overview
Section titled “Overview”Cosmos provides multiple RPC APIs for interacting with nodes and the Tendermint/Cosmos SDK blockchain. Understanding these interfaces is essential for building applications, monitoring nodes, and managing validator operations. Cosmos supports REST APIs, gRPC, and traditional RPC endpoints, each serving different purposes in the ecosystem.
16.1 RPC Endpoints Architecture
Section titled “16.1 RPC Endpoints Architecture”Available Interfaces
Section titled “Available Interfaces”| Interface | Port | Protocol | Use Case |
|---|---|---|---|
| RPC | 26657 | HTTP/JSON-RPC | Primary node communication |
| API | 1317 | REST/HTTP | Human-readable REST API |
| gRPC | 9090 | gRPC | High-performance programmatic access |
| gRPC-Web | 9091 | gRPC-Web | Browser-based gRPC access |
| P2P | 26656 | Tendermint | Node-to-node communication |
Port Configuration in config.toml
Section titled “Port Configuration in config.toml”# RPC Server Configuration[rpc] laddr = "tcp://0.0.0.0:26657" # RPC listen address grpc_laddr = "" # gRPC listen address (disabled by default) grpc_web_laddr = "" # gRPC-web listen address cors_allowed_origins = ["*"] # CORS allowed origins cors_allowed_methods = ["GET", "POST"] # CORS allowed methods cors_allowed_headers = ["*"] # CORS allowed headers fee = "2000uatom" # Gas price for RPC max_body_bytes = 100000000 # Max request body size max_header_bytes = 1048576 # Max header size timeout_broadcast_tx_commit = 10s # Tx commit timeout16.2 Enabling APIs
Section titled “16.2 Enabling APIs”Enable REST API (app.toml)
Section titled “Enable REST API (app.toml)”[api]enable = true # Enable REST APIswagger = true # Enable Swagger documentationaddress = "tcp://0.0.0.0:1317" # API listen addressmax_open_connections = 100 # Max open connectionsgrpc_enable = 1 # Enable gRPCgrpc-web-enable = 1 # Enable gRPC-WebEnable gRPC Server
Section titled “Enable gRPC Server”[grpc]enable = trueaddress = "0.0.0.0:9090"16.3 Common Commands
Section titled “16.3 Common Commands”Query Commands
Section titled “Query Commands”# Connect to nodegaiad query bank balances cosmos1...
# Get block by heightgaiad query block 10000
# Get block by hashgaiad query block --hash="0x..."
# Get transaction by hashgaiad query tx <TX_HASH>
# Get validator setgaiad query staking validators
# Get delegationsgaiad query staking delegations <DELEGATOR_ADDR>
# Get staking paramsgaiad query staking params
# Get governance proposalsgaiad query gov proposals
# Get node statusgaiad status
# Get chain infogaiad query chain-params
# Get community poolgaiad query distribution community-poolTransaction Commands
Section titled “Transaction Commands”# Send tokensgaiad tx bank send <FROM> <TO> <AMOUNT> \ --chain-id <CHAIN_ID> \ --gas=auto \ --gas-adjustment=1.5 \ --broadcast-mode=block
# Delegate tokensgaiad tx staking delegate <VALIDATOR> <AMOUNT> \ --from <WALLET> \ --chain-id <CHAIN_ID>
# Undelegate tokensgaiad tx staking unbond <VALIDATOR> <AMOUNT> \ --from <WALLET> \ --chain-id <CHAIN_ID>
# Redelegate tokensgaiad tx staking redelegate <FROM_VALIDATOR> <TO_VALIDATOR> <AMOUNT> \ --from <WALLET> \ --chain-id <CHAIN_ID>
# Vote on governance proposalgaiad tx gov vote <PROPOSAL_ID> <VOTE_OPTION> \ --from <WALLET> \ --chain-id <CHAIN_ID>
# Create validatorgaiad tx staking create-validator \ --amount=1000000uatom \ --pubkey=$(gaiad tendermint show-validator) \ --moniker="my-validator" \ --commission-rate="0.10" \ --commission-max-rate="0.20" \ --commission-max-change-rate="0.01" \ --min-self-delegation="1" \ --from=<WALLET> \ --chain-id=<CHAIN_ID>16.4 JSON-RPC Interface
Section titled “16.4 JSON-RPC Interface”Direct RPC Calls
Section titled “Direct RPC Calls”# Get latest block heightcurl -s http://localhost:26657/block | jq .result.block.header.height
# Get block by heightcurl -s http://localhost:26657/block?height=10000 | jq
# Get latest blockcurl -s http://localhost:26657/block | jq
# Get block resultscurl -s http://localhost:26657/block_results?height=10000 | jq
# Get validator set at heightcurl -s http://localhost:26657/validators?height=10000 | jq
# Get node infocurl -s http://localhost:26657/status | jq
# Check if node is syncingcurl -s http://localhost:26657/status | jq '.result.sync_info.catching_up'
# Get consensus statecurl -s http://localhost:26657/consensus_state | jq
# Get net info (connected peers)curl -s http://localhost:26657/net_info | jq
# Get unconfirmed transactionscurl -s http://localhost:26657/unconfirmed_txs | jq
# Get healthcurl -s http://localhost:26657/health | jq
# Broadcast transactioncurl -s http://localhost:26657/broadcast_tx_commit \ -x POST \ -H "Content-Type: application/json" \ -d '{"jsonrpc":"2.0","id":1,"method":"broadcast_tx_commit","params":{"tx":"BASE64_ENCODED_TX"}}'
# Broadcast transaction asynchronouslycurl -s http://localhost:26657/broadcast_tx_async \ -x POST \ -H "Content-Type: application/json" \ -d '{"jsonrpc":"2.0","id":1,"method":"broadcast_tx_async","params":{"tx":"BASE64_ENCODED_TX"}}'
# Check txpoolcurl -s http://localhost:26657/dump_consensus_state | jqWebSocket RPC
Section titled “WebSocket RPC”# Connect via WebSocketwscat -c ws://localhost:26657/websocket
# Subscribe to new blocks{"jsonrpc": "2.0", "method": "subscribe", "params": {"query": "tm.event='NewBlock'"}, "id": 1}
# Subscribe to transactions{"jsonrpc": "2.0", "method": "subscribe", "params": {"query": "tm.event='Tx'"}, "id": 2}
# Subscribe to validator set updates{"jsonrpc": "2.0", "method": "subscribe", "params": {"query": "tm.event='ValidatorSetUpdates'"}, "id": 3}
# Unsubscribe{"jsonrpc": "2.0", "method": "unsubscribe", "params": {"query": "tm.event='NewBlock'"}, "id": 4}16.5 gRPC Interface
Section titled “16.5 gRPC Interface”Using gRPCurl
Section titled “Using gRPCurl”# Install grpcurlgo install github.com/fullstorydev/grpcurl/cmd/grpcurl@latest
# List available servicesgrpcurl -plaintext localhost:9090 list
# Get service methodsgrpcurl -plaintext localhost:9090 list cosmos.bank.v1beta1.Query
# Query balancegrpcurl -plaintext localhost:9090 \ cosmos.bank.v1beta1.Query/AllBalances \ -d '{"address":"cosmos1..."}'
# Query delegationsgrpcurl -plaintext localhost:9090 \ cosmos.staking.v1beta1.Query/DelegatorDelegations \ -d '{"delegator_addr":"cosmos1..."}'
# Query validator infogrpcurl -plaintext localhost:9090 \ cosmos.staking.v1beta1.Query/Validator \ -d '{"validator_addr":"cosmosvaloper1..."}'
# Query tx by hashgrpcurl -plaintext localhost:9090 \ cosmos.tx.v1beta1.Service/GetTx \ -d '{"hash":"BASE64_HASH"}'Using Protocol Buffers
Section titled “Using Protocol Buffers”// Example proto querymessage QueryBalanceRequest { string address = 1; string denom = 2;}
message QueryBalanceResponse { cosmos.base.v1beta1.Coin balance = 1;}16.6 REST API Examples
Section titled “16.6 REST API Examples”Bank Module
Section titled “Bank Module”# Get all balancescurl -s http://localhost:1317/cosmos/bank/v1beta1/balances/cosmos1...
# Get balance for specific denomcurl -s http://localhost:1317/cosmos/bank/v1beta1/balances/cosmos1...?denom=uatom
# Get total supplycurl -s http://localhost:1317/cosmos/bank/v1beta1/supply
# Get metadatacurl -s http://localhost:1317/cosmos/bank/v1beta1/denoms_metadataStaking Module
Section titled “Staking Module”# Get validatorscurl -s http://localhost:1317/cosmos/staking/v1beta1/validators
# Get validator detailscurl -s http://localhost:1317/cosmos/staking/v1beta1/validators/cosmosvaloper1...
# Get delegationscurl -s http://localhost:1317/cosmos/staking/v1beta1/delegations/cosmos1...
# Get unbonding delegationscurl -s http://localhost:1317/cosmos/staking/v1beta1/delegators/cosmos1.../unbonding_delegations
# Get staking parameterscurl -s http://localhost:1317/cosmos/staking/v1beta1/paramsGovernance Module
Section titled “Governance Module”# Get proposalscurl -s http://localhost:1317/cosmos/gov/v1beta1/proposals
# Get proposal detailscurl -s http://localhost:1317/cosmos/gov/v1beta1/proposals/1
# Get votescurl -s http://localhost:1317/cosmos/gov/v1beta1/proposals/1/votes
# Get proposal depositscurl -s http://localhost:1317/cosmos/gov/v1beta1/proposals/1/depositsDistribution Module
Section titled “Distribution Module”# Get rewardscurl -s http://localhost:1317/cosmos/distribution/v1beta1/delegators/cosmos1.../rewards
# Get validator commissioncurl -s http://localhost:1317/cosmos/distribution/v1beta1/validators/cosmosvaloper1.../commission
# Get community poolcurl -s http://localhost:1317/cosmos/distribution/v1beta1/community_pool16.7 Authentication & Security
Section titled “16.7 Authentication & Security”RPC Authentication
Section titled “RPC Authentication”# Enable authentication in config.toml[rpc] # ... other settings ...
# Authentication http_auth_file = "/path/to/htpasswd"Creating User Credentials
Section titled “Creating User Credentials”# Install apache2-utils for htpasswdsudo apt-get install apache2-utils
# Create userhtpasswd -Bc /path/to/htpasswd username
# Add another userhtpasswd -B /path/to/htpasswd anotheruserUsing with Authentication
Section titled “Using with Authentication”# Basic auth with curlcurl -u username:password http://localhost:26657/status
# API token authcurl -H "Authorization: Bearer <TOKEN>" http://localhost:1317/cosmos/...16.8 Rate Limiting
Section titled “16.8 Rate Limiting”Configure Rate Limiting
Section titled “Configure Rate Limiting”[rpc] # Rate limit settings max_open_connections = 100 read_timeout = 10s write_timeout = 10sNginx Rate Limiting
Section titled “Nginx Rate Limiting”upstream cosmos_rpc { server localhost:26657;}
upstream cosmos_api { server localhost:1317;}
server { listen 80; server_name rpc.example.com;
# Rate limit: 10 req/s per IP limit_req zone=cosmos_rpc limit:10r/s burst=20 nodelay;
location / { proxy_pass http://cosmos_rpc; }}16.9 Load Balancing
Section titled “16.9 Load Balancing”HAProxy Configuration
Section titled “HAProxy Configuration”frontend cosmos_rpc_frontend bind :443 ssl crt /etc/ssl/certs/server.pem default_backend cosmos_nodes
backend cosmos_nodes balance roundrobin option httpchk GET /status
# Health check every 5 seconds http-check expect status 200
server node1 10.0.0.1:26657 check inter 5s rise 2 fall 3 server node2 10.0.0.2:26657 check inter 5s rise 2 fall 3 server node3 10.0.0.3:26657 check inter 5s rise 2 fall 316.10 Monitoring RPC Health
Section titled “16.10 Monitoring RPC Health”Health Check Script
Section titled “Health Check Script”#!/bin/bashRPC_URL="http://localhost:26657"TIMEOUT=5
# Check if node is responsiveresponse=$(curl -s -m $TIMEOUT -w "%{http_code}" -o /dev/null $RPC_URL/status)
if [ "$response" = "200" ]; then # Check if catching up catching_up=$(curl -s $RPC_URL/status | jq -r '.result.sync_info.catching_up')
if [ "$catching_up" = "false" ]; then echo "OK: Node is synced" exit 0 else echo "WARNING: Node is catching up" exit 1 fielse echo "CRITICAL: Node not responding" exit 2fiSummary
Section titled “Summary”- Cosmos RPC runs on port 26657 for JSON-RPC communication
- REST API runs on port 1317 for human-readable endpoints
- gRPC runs on port 9090 for high-performance programmatic access
- Use gRPCurl for efficient debugging and testing
- WebSocket subscriptions enable real-time event streaming
- Implement authentication and rate limiting for production nodes
- Monitor sync status and health endpoints regularly
- Configure load balancing for high availability RPC infrastructure
Next Chapter
Section titled “Next Chapter”In Chapter 17: Tendermint & Consensus, we’ll explore the Tendermint consensus mechanism.
Last Updated: 2026-02-22