DEV Community

Cover image for How to Use the Solana API: Complete Guide for Developers
Preecha
Preecha

Posted on

How to Use the Solana API: Complete Guide for Developers

What if you could build blockchain applications that process 65,000 transactions per second with 400-millisecond finality? Solana's API makes this possible, offering a JSON-RPC interface that lets you query accounts, submit transactions, and subscribe to real-time updates without managing validator infrastructure yourself.

Try Apidog today

Traditional blockchain development forces you to choose between speed and decentralization. Ethereum's 15 TPS creates bottlenecks during network congestion. Layer 2 solutions add complexity. Solana eliminates this trade-off through its proof-of-history consensus combined with proof-of-stake, delivering Web2 performance with Web3 guarantees. You build applications that feel instantaneous while maintaining censorship resistance.

💡When building Solana applications, managing multiple RPC endpoints and debugging transaction failures becomes complex. Apidog provides visual API testing, automated documentation, and team collaboration features specifically designed for blockchain development. Try Apidog free to streamline your Solana workflow—no credit card required.

Understanding Solana's Architecture

Solana uses a unique architecture centered on the Solana Program Library (SPL) and a high-throughput runtime. Understanding these fundamentals helps you write efficient API calls.

Proof of History (PoH)

PoH creates a cryptographic timestamp for every transaction before consensus. This eliminates the need for nodes to agree on time, reducing latency dramatically. When you submit a transaction via the API, it gets timestamped immediately and enters the leader's queue for processing.

Accounts and Programs

Unlike Ethereum's account-based model with code storage, Solana separates code (programs) from data (accounts). Programs are stateless—they only contain executable logic. Accounts store data and specify which program owns them. This architecture enables parallel transaction processing since non-overlapping accounts can execute simultaneously.

Every account has a unique 32-byte address derived from an Ed25519 public key. Accounts pay rent in lamports (1 SOL = 10^9 lamports) to remain on-chain. Rent-exempt accounts—those holding at least 2 years of rent—persist indefinitely without decay.

Commitment Levels

Solana provides three confirmation levels:

  • Processed: Transaction processed by the current leader but not confirmed. Fastest response, lowest certainty.
  • Confirmed: Transaction confirmed by the cluster. ~5-10 seconds on average.
  • Finalized: Transaction rooted and cannot be rolled back. ~12-15 seconds.

Specify commitment levels in API calls to balance speed against finality guarantees.

solana api

Setting Up Your Development Environment

You need three components: the Solana CLI for key management and deployment, an RPC endpoint for blockchain access, and the JavaScript SDK for application integration.

Installing the Solana CLI

Install the official CLI tool:

sh -c "$(curl -sSfL https://release.solana.com/stable/install)"
Enter fullscreen mode Exit fullscreen mode

Verify installation:

solana --version
Enter fullscreen mode Exit fullscreen mode

Configure your environment for Devnet (testing) or Mainnet (production):

# For development
solana config set --url https://api.devnet.solana.com

# For production
solana config set --url https://api.mainnet-beta.solana.com
Enter fullscreen mode Exit fullscreen mode

Creating a Wallet

Generate a new keypair for signing transactions:

solana-keygen new --outfile ~/.config/solana/id.json
Enter fullscreen mode Exit fullscreen mode

The CLI outputs your public address and a 12-word seed phrase. Store the seed phrase securely—it recovers your wallet. The JSON file contains your private key; protect it with file permissions (chmod 600).

Check your balance:

solana balance
Enter fullscreen mode Exit fullscreen mode

Fund your Devnet wallet with free SOL:

solana airdrop 2
Enter fullscreen mode Exit fullscreen mode

Devnet airdrops provide 2 SOL per request, limited to one request per 10 seconds. Mainnet requires purchasing SOL through exchanges.

Choosing an RPC Provider

While Solana provides public RPC endpoints, production applications need dedicated infrastructure. Options include:

Free tiers typically allow 100,000 requests per month. Paid plans offer higher limits, staked connections for transaction landing, and priority fee APIs.

Installing Web3.js

Solana's JavaScript SDK has two major versions. Version 2.0 represents a complete rewrite with functional programming patterns, tree-shakability, and zero dependencies.

Install version 2.0:

npm install @solana/web3.js@2 @solana-program/system @solana-program/compute-budget
Enter fullscreen mode Exit fullscreen mode

For version 1.x compatibility:

npm install @solana/web3.js
Enter fullscreen mode Exit fullscreen mode

Reading Wallet and Portfolio Data

To assemble a complete picture (SOL balance, every SPL token, transaction history, and any DeFi positions) you typically combine several RPC calls:

import { createSolanaRpc } from "@solana/web3.js";

const rpc = createSolanaRpc("https://api.devnet.solana.com");

// Query main account
const accountInfo = await rpc.getAccountInfo("vines1vzrYbzLMRdu58ou5XTby4qAqVRLmqo36zEGQp").send();

// Query token accounts
const tokenAccounts = await rpc.getTokenAccountsByOwner("vines1vzrYbzLMRdu58ou5XTby4qAqVRLmqo36zEGQp").send();
Enter fullscreen mode Exit fullscreen mode

Core Solana RPC API Methods

Solana's JSON-RPC API provides HTTP endpoints for queries and WebSocket endpoints for subscriptions. All requests follow the JSON-RPC 2.0 specification.

Core Solana RPC API Methods

Account Operations

Get account information and balance:

const accountInfo = await fetch("https://api.devnet.solana.com", {
  method: "POST",
  headers: { "Content-Type": "application/json" },
  body: JSON.stringify({
    jsonrpc: "2.0",
    id: 1,
    method: "getAccountInfo",
    params: [
      "vines1vzrYbzLMRdu58ou5XTby4qAqVRLmqo36zEGQp",
      { encoding: "base58" }
    ]
  })
}).then(res => res.json());
Enter fullscreen mode Exit fullscreen mode

WebSocket Subscriptions

Monitor account changes in real-time:

import { createSolanaRpcSubscriptions } from "@solana/web3.js";

const rpcSubscriptions = createSolanaRpcSubscriptions(
  "wss://api.devnet.solana.com"
);

const abortController = new AbortController();

await rpcSubscriptions.accountNotifications(
  "vines1vzrYbzLMRdu58ou5XTby4qAqVRLmqo36zEGQp",
  { commitment: "confirmed" },
  (notification) => {
    console.log("Account changed:", notification);
  },
  { abortSignal: abortController.signal }
);

// Stop listening after 60 seconds
setTimeout(() => abortController.abort(), 60000);
Enter fullscreen mode Exit fullscreen mode

Building Transactions with Web3.js

Creating a Transfer Transaction

Transfer SOL between accounts using version 2.0 SDK:

import {
  airdropFactory,
  generateKeyPairSigner,
  lamports,
  sendAndConfirmTransactionFactory,
  pipe,
  createTransactionMessage,
  setTransactionMessageFeePayer,
  setTransactionMessageLifetimeUsingBlockhash,
  appendTransactionMessageInstruction,
  signTransactionMessageWithSigners,
} from "@solana/web3.js";
import { getTransferSolInstruction } from "@solana-program/system";

// Setup connections
const rpc = createSolanaRpc("https://api.devnet.solana.com");
const rpcSubscriptions = createSolanaRpcSubscriptions("wss://api.devnet.solana.com");
const sendAndConfirmTransaction = sendAndConfirmTransactionFactory({ rpc, rpcSubscriptions });

// Generate accounts
const sender = await generateKeyPairSigner();
const recipient = await generateKeyPairSigner();

// Airdrop to sender
await airdropFactory({ rpc, rpcSubscriptions })({
  recipientAddress: sender.address,
  lamports: lamports(2_000_000_000n), // 2 SOL
  commitment: "confirmed",
});

// Build transfer
const transactionMessage = pipe(
  createTransactionMessage({ version: 0 }),
  (msg) => setTransactionMessageFeePayer(sender.address, msg),
  (msg) => setTransactionMessageLifetimeUsingBlockhash(await rpc.getLatestBlockhash().send().then(res => res.value), msg),
  (msg) => appendTransactionMessageInstruction(
    getTransferSolInstruction({
      amount: lamports(500_000_000n), // 0.5 SOL
      destination: recipient.address,
      source: sender,
    }),
    msg
  )
);

// Sign and send
const signedTransaction = await signTransactionMessageWithSigners(transactionMessage);
await sendAndConfirmTransaction(signedTransaction);
Enter fullscreen mode Exit fullscreen mode

Best Security Practices

Key Management

Never hardcode private keys. Use environment variables:

import dotenv from "dotenv";
dotenv.config();

const secretKey = new Uint8Array(JSON.parse(process.env.SOLANA_PRIVATE_KEY));
Enter fullscreen mode Exit fullscreen mode

Transaction Simulation

Always simulate before sending:

const simulation = await rpc.simulateTransaction(signedTransaction).send();
if (simulation.value.err) throw new Error("Simulation failed");
Enter fullscreen mode Exit fullscreen mode

Conclusion

Solana's high-throughput API enables applications with real-time performance. Start on Devnet, implement proper key management, and use tools like Apidog to streamline your development workflow.

Try Apidog to visually test Solana RPC endpoints and generate automated documentation.

Top comments (0)