7Block Labs
Blockchain Development

ByAUJay

Web3 API Design: Creating API for Web3 and Streamlining API Development for Seamless Blockchain Integration

Description: A practical blueprint for decision‑makers to design reliable, secure, and scalable Web3 APIs that integrate with modern Ethereum and L2s—covering JSON‑RPC baselines, finality semantics, EIP‑1559/4844 fees, event streaming, account abstraction, indexing, simulation, and operational best practices with concrete examples and emerging standards.

Why Web3 API design is different

Traditional API design patterns break when your backend is a decentralized network with probabilistic inclusion, reorgs, multiple execution clients, and rapidly changing standards. A robust Web3 API must:

  • Encode chain finality and reorg risk in every read/write path.
  • Handle divergent client behavior while staying compatible with the common Ethereum JSON‑RPC surface. (eips.ethereum.org)
  • Support fee and data‑availability markets introduced by EIP‑1559 and EIP‑4844. (eips.ethereum.org)
  • Offer both pull (RPC/GraphQL) and push (WebSocket/webhooks/streams) data flows. (chainnodes.org)
  • Accommodate modern wallet flows (EIP‑1193/6963) and account abstraction (ERC‑4337, ERC‑6900). (eips.ethereum.org)

Below is a field-tested guide 7Block Labs uses to help startups and enterprises ship Web3 features with confidence.


1) Establish your canonical API surface

Start with the execution-layer JSON‑RPC methods standardized for Ethereum clients (EIP‑1474; execution-apis). Treat this as your minimum viable interface; everything else is an enhancement. Key points:

  • JSON‑RPC 2.0 shape and batching rules; error ranges −32768..−32000; server errors −32000..−32099. (json-rpc.org)
  • Value encoding and block parameter semantics (including tags: latest, pending, safe, finalized). (eips.ethereum.org)
  • Disambiguated block selection with EIP‑1898 object form to avoid ambiguity in reorgs. (eips.ethereum.org)

Example: pin a read to a specific block hash to be reorg‑safe.

{
  "jsonrpc": "2.0",
  "id": 1,
  "method": "eth_call",
  "params": [
    {"to": "0xYourContract", "data": "0xYourCalldata"},
    {"blockHash": "0xabc...def", "requireCanonical": true}
  ]
}

2) Finality-aware reads and SLAs

Executives want deterministic dashboards; engineers need to balance latency vs. safety.

  • Ethereum PoS finalizes blocks after roughly two epochs (~12–15 minutes typical), though it can vary; SSF research aims to reduce this. Use “safe” for near‑final data and “finalized” for settlement-grade reads. (blocknative.com)
  • Expose read-levels in your API: fast (latest), safe, and finalized. Back them with the JSON‑RPC tags so clients choose their risk profile. (ethereum.org)

Example: “safe” inventory query:

{
  "jsonrpc": "2.0",
  "id": 2,
  "method": "eth_getBalance",
  "params": ["0xAddress", "safe"]
}

3) Fees, throughput, and blobs: design for EIP‑1559 and EIP‑4844

Fee estimation and transaction orchestration must reflect the dual markets now live on Ethereum and rollups.

  • EIP‑1559 introduces baseFee + priorityFee with type‑2 transactions. Use eth_feeHistory for percentile tips; many providers expose baseFeePerBlobGas and blobGasUsedRatio in responses. (eips.ethereum.org)
  • EIP‑4844 (type‑3 “blob-carrying” transactions) adds a distinct blob gas market with TARGET 3 blobs/block and MAX 6; blob base fee updates exponentially with excess usage. This heavily impacts L2 posting costs and observability. (eips.ethereum.org)
  • Blob fees can spike during non‑L2 uses (e.g., “blobscriptions”)—observed spikes from 1 wei to ~650 gwei. Your API should surface blob fee telemetry and fallbacks when blobs are temporarily uneconomic. (blocknative.com)

Practical tactic: expose a single “estimateFees” endpoint that returns:

  • baseFee, priorityFee suggestions from eth_feeHistory,
  • blob base fee snapshot and 5–10 block projection,
  • recommended transaction type (2 vs 3) for a given payload size.

Reference: eth_feeHistory returns both EIP‑1559 and blob fee fields on supported networks. (quicknode.com)


4) Event data at scale: logs, filters, and chunking

Most apps hinge on indexed events. Common pitfalls:

  • eth_getLogs limits exist across providers (10,000 result cap and ~10s timeout are common). Chunk queries by block ranges and constrain by address/topics to avoid −32005 errors. (docs.chainstack.com)
  • For large scans, iterate with 3–5k block windows on Ethereum mainnet; many providers recommend similar practical limits. (docs.chainstack.com)
  • Avoid legacy eth_newFilter polling for historical backfills; prefer stateless eth_getLogs plus provider streams for live updates. (ethereum.org)

Example: chunked backfill with safe range:

[
  {
    "jsonrpc":"2.0","id":1,"method":"eth_getLogs",
    "params":[{"fromBlock":"0xA1B2C3","toBlock":"0xA1D4EF","address":"0xToken","topics":["0xddf252ad..."],"toBlockTag":"safe"}]
  }
]

Note: Some clients offer non‑standard accelerants like eth_getBlockReceipts (Erigon; Geth ≥1.13) to sweep receipts per block efficiently—use feature detection and fall back cleanly. (docs.chainstack.com)


5) Real‑time delivery: WebSockets, webhooks, and streams

Offer push alternatives to reduce polling cost and latency:

  • WebSocket eth_subscribe for newHeads, logs, and pending transactions. Reserve for sessioned backends and trading‑class use cases. (chainnodes.org)
  • If you can’t run persistent sockets at scale, use provider webhooks (e.g., Alchemy Address/NFT Activity; millions of tracked addresses per webhook) and route into your queue. (alchemy.com)
  • For heavy analytics, consider The Graph Substreams to parallelize backprocessing and reliable cursoring; teams report large speed/cost gains vs. raw RPC. (thegraph.com)
  • QuickNode Streams provides managed backfills and live streams across multiple chains. (quicknode.com)

Example: basic WS subscribe

wscat -c wss://mainnet.your-provider.example/ws
> {"id":1,"jsonrpc":"2.0","method":"eth_subscribe","params":["logs",{"address":"0xToken","topics":["0xddf252ad..."]}]}

Providers vary on pending tx exposure and rate controls—include plan-aware guards. (chainnodes.org)


6) Wallets, providers, and discovery

Frontends increasingly rely on EIP‑1193 provider events and the multi‑wallet discovery standard.

  • Handle provider request() and events: connect, disconnect, chainChanged, accountsChanged. (eips.ethereum.org)
  • Implement EIP‑6963 so your dapp can discover multiple injected wallets, avoiding window.ethereum collisions. Libraries like Web3.js v4 expose helpers. (eip.info)

Authentication and authorization:

  • Sign‑In with Ethereum (ERC‑4361) specifies a standard, origin‑bound message format. Pair with server‑side signature validation and session cookies/JWT. (eips.ethereum.org)
  • For permissioned API actions, layer “ReCaps” (ERC‑5573) capabilities on top of SIWE to grant scoped rights with explicit user consent. (eips.ethereum.org)
  • For typed off‑chain messages (e.g., permit, meta‑tx), standardize on EIP‑712. (eips.ethereum.org)

7) Account abstraction and modular accounts

Plan for AA where users interact via smart contract accounts:

  • ERC‑4337 introduces UserOperation with bundlers and an EntryPoint contract; AA wallets can enforce custom validation, sponsors, session keys, and recovery. Your API should support UO submission, simulation, and status. (eips.ethereum.org)
  • Modular smart accounts (ERC‑6900, draft) standardize account/module interfaces for validations, execution functions, and hooks—improving interoperability among AA wallets and modules. Keep your gateway extensible to support these interfaces as they stabilize. (eips.ethereum.org)

Tip: expose “simulateUserOp” and “estimateUserOpGas” endpoints mirroring emerging RPCs so you can swap providers/clients later without breaking customers. (Multiple AA RPCs build on the same state‑override semantics used by eth_call.) (eip.directory)


8) Preflight simulation and safety rails

Before sending transactions on mainnet or L2, add pre‑execution checks:

  • eth_call at a specific block; prefer “safe” or “finalized” for deterministic simulations surfaced to end users. (ethereum.org)
  • Use state overrides to simulate balances, bytecode, or storage without redeploying test fixtures—supported in Geth and documented in ecosystem tools. (geth.ethereum.org)
  • Create access lists with eth_createAccessList (EIP‑2930) to reduce cold‑access penalties in complex interactions. (support.huaweicloud.com)

Example: simulate with a temporary balance and storage slot:

{
  "jsonrpc": "2.0",
  "id": 3,
  "method": "eth_call",
  "params": [
    {"to":"0xYourContract","data":"0x..."},
    "safe",
    {
      "0xUserAddress": {"balance": "0x8AC7230489E80000"},
      "0xYourContract": {"stateDiff": {"0x<slot>": "0x<value>"}}
    }
  ]
}

9) Robust write path: submission, retries, and confirmations

Abstract the mempool’s quirks behind a clean API with idempotency.

  • Common send errors include “replacement transaction underpriced,” “nonce too low,” and “already known.” Your gateway should normalize heterogeneous provider messages and advise recovery (e.g., bump tip for replacements). (github.com)
  • Implement idempotency keys and safe retries. If you see “already known,” treat as success‑pending and resolve by querying the tx hash. (docs.tatum.io)
  • On reads, never assume inclusion until your confirmation policy says so. For Ethereum mainnet, expose two thresholds in your API:
    • “included”: first seen in a canonical block (notify quickly, but caveat emptor).
    • “finalized”: after finality window (~15 minutes typical). (blocknative.com)

10) Cross‑chain semantics and rollup finality

Design your API to distinguish “L2 local finality” from “L1 final/withdraw‑able.”

  • Optimistic rollups: withdrawals finalize only after the challenge window (commonly ~7 days on mainnet). Your API should clearly mark this status for bridges/exits. (docs.optimism.io)
  • Arbitrum’s defaults: ~45,818 L1 blocks (~1 week) plus ~200‑block buffer; chains can customize. For enterprise SLAs, surface chain‑specific parameters. (docs.arbitrum.io)

11) Indexing strategy: when RPC is not enough

For product analytics, leaderboards, and historical scans, you generally need an indexer.

  • The Graph Substreams processes entire chains with parallelization and cursored fault tolerance; stream transformed data to warehouses or services. (thegraph.com)
  • Managed alternatives like Goldsky and others provide subgraphs and pipelines across dozens of networks with GraphQL endpoints; useful to accelerate time‑to‑market. (goldsky.com)

Your API design should present a unified data layer (e.g., “/nft-owners?block=finalized”) backed by an indexer for scale, and fall back to RPC for freshness gaps.


12) Documentation, discovery, and versioning

Treat your API as a product. Use machine‑readable specs:

  • The Ethereum execution‑apis spec is written in OpenRPC. Mirror this in your own service and expose rpc.discover for client codegen, testing, and diffs. (github.com)
  • OpenRPC provides generators, docs, and validation similar to OpenAPI but aligned with JSON‑RPC. Building from a spec reduces drift across microservices and languages. (open-rpc.org)

13) Practical design patterns you can copy today

  1. Batching hot reads
    Batch JSON‑RPC to reduce latency and overhead. Mind that responses can return in any order; match via id.
[
  {"jsonrpc":"2.0","id":1,"method":"eth_chainId","params":[]},
  {"jsonrpc":"2.0","id":2,"method":"eth_getBalance","params":["0x...", "safe"]},
  {"jsonrpc":"2.0","id":3,"method":"eth_getTransactionCount","params":["0x...", "latest"]}
]

JSON‑RPC 2.0 supports batches natively; many clients parallelize internally. (json-rpc.org)

  1. Durable event backfills
    Use a “binary search” chunker that dynamically shrinks block windows on −32005 “too many results,” then grows cautiously to maximize throughput. Provider docs recommend keeping windows small (e.g., 3–5k on Ethereum) to avoid timeouts. (docs.chainstack.com)

  2. Webhook fan‑out
    Subscribe to mined or address activity webhooks, verify signatures, write to a queue (Kafka/PubSub), and ack within provider timeouts to avoid retries. Alchemy’s Address Activity scales to very large address sets per webhook. (alchemy.com)

  3. Finality‑tiered caches
    Maintain three caches: latest (TTL seconds), safe (updated each safe head), and finalized (append‑only). Route GETs accordingly. Ethereum docs explicitly support safe and finalized tags across core methods. (ethereum.org)

  4. Fee policy abstraction
    Expose a single “POST /transactions/estimate” that internally calls eth_feeHistory and reads blob base fee; return structured suggestions for type‑2 or type‑3, with confidence bands and suggested tip ladder. (quicknode.com)

  5. AA readiness
    Design “/userops/simulate” and “/userops/send” endpoints now. Under the hood, simulate via eth_call with state overrides; forward to your selected bundler infra later without changing your client contracts. (eips.ethereum.org)


14) Example: production‑grade “Get Transfers” endpoint

Requirements: reorg‑safe, scalable, and low‑latency.

  • Input: contract address, fromBlock/toBlock or time range, consistency: latest|safe|finalized.
  • Behavior:
    • If finalized: serve from indexer; paginate by block number and log index.
    • If safe: query RPC for the delta since last safe checkpoint; de‑dupe by (txHash, logIndex).
    • If latest: add a “reorgWarning: true” field in the response.
  • Implementation bits:
    • Use eth_getLogs with 2–5k block windows and OR‑topics for Transfer signature; include address filter to reduce cardinality. (ethereum.org)
    • Push live updates via WS logs subscription for the same filter; merge into the same store. (chainnodes.org)
    • For high‑traffic collections, migrate to a Substreams pipeline producing normalized transfer rows. (thegraph.com)

15) Security and compliance quick‑wins

  • Validate and normalize all JSON‑RPC inputs; enforce hex formats and quantity rules per spec. (eips.ethereum.org)
  • Use EIP‑712 for structured signatures (e.g., policy approvals) to avoid ambiguous byte strings. (eips.ethereum.org)
  • For off‑chain auth, implement SIWE and bind to origin (wallets enforce domain checks). For fine‑grained permissions, adopt SIWE ReCaps. (eips.ethereum.org)
  • For proofs, expose eth_getProof when customers need trust‑minimized verification or cross‑domain proofs. Note: requires access to state DB; some clients optimize with commitment history. (eips.ethereum.org)

16) Reliability engineering: what to automate on day one

  • Backoff and retry on server‑side failures; don’t hammer short client‑side timeouts—Alchemy recommends exponential backoff to avoid request storms. (alchemy.com)
  • Normalize mempool errors; treat “already known” as success‑pending; instruct “replacement underpriced” callers to bump priority fee. (docs.tatum.io)
  • Emit metrics per method: P50/P95 latency, error code counts, provider CU usage, cache hit ratios.
  • Feature‑flag non‑standard methods (e.g., eth_getBlockReceipts) based on client detection at startup. (docs.chainstack.com)

17) Reference architecture (what we deploy for clients)

  • Edge
    • HTTP/WS termination, WAF, and request validation.
    • OpenRPC‑generated gateway that routes to:
      • RPC pool (multi‑provider failover, per‑chain),
      • Indexer cluster (Substreams/Graph pipelines),
      • Queue (webhooks → Kafka/PubSub).
    • Finality‑tiered caches (latest/safe/finalized).
  • Services
    • Read API: composed queries across cache + RPC + indexer.
    • Write API: idempotent transaction/userOp submission, pre‑simulation, and confirmation tracking.
    • Streams: WS multiplexers + webhook consumers emitting domain events.
  • Observability
    • OpenTelemetry traces per RPC call, request sampling, blob fee dashboards, reorg counters.
  • Documentation
    • OpenRPC spec with rpc.discover for codegen and compatibility tests. (spec.open-rpc.org)

18) What’s next

  • Monitor the blob market in production; during congestion, provide calldata fallback estimates and customer‑grade comms explaining cost deltas. (blocknative.com)
  • Keep frontends compliant with EIP‑6963; wallet ecosystems are moving there quickly. (eip.info)
  • Prepare for modular AA (ERC‑6900) to standardize module ecosystems around execution/validation hooks. (eips.ethereum.org)

7Block Labs can help

Whether you need a production‑ready Web3 API gateway, an indexing pipeline for analytics, or AA‑ready transaction services, 7Block Labs has deployed these patterns across multiple enterprises and high‑growth startups. We’ll tailor a design that fits your latency, cost, and compliance targets—and we’ll leave you with a versioned OpenRPC spec, dashboards, and runbooks your team can own from day two.

Reach out if you want an architecture review, a build sprint, or a full “API + indexing + observability” stack delivered in weeks, not months.


Appendix: handy payloads

  1. eth_feeHistory including blob fields (where supported)
{
  "jsonrpc":"2.0",
  "id": 4,
  "method":"eth_feeHistory",
  "params":[64, "latest", [5,25,50,75,95]]
}

Look for baseFeePerGas, reward[], baseFeePerBlobGas, blobGasUsedRatio fields to tune both type‑2 and type‑3 fees. (quicknode.com)

  1. SIWE message skeleton (binds to origin; validate server‑side)
example.com wants you to sign in with your Ethereum account:
0xYourAddress

Sign in to Example

URI: https://example.com/login
Version: 1
Chain ID: 1
Nonce: 4f7a2c3d
Issued At: 2026-01-07T19:00:00Z

Standardized by ERC‑4361; wallets verify domain/scheme. (eips.ethereum.org)

  1. WebSocket logs subscribe (push)
{"id":1,"jsonrpc":"2.0","method":"eth_subscribe","params":["logs",{"address":"0xToken","topics":["0xddf252ad..."]}]}

Requires WSS; use “newHeads” for block cadence or “newPendingTransactions” with care. (chainnodes.org)

  1. eth_getProof (account + storage proof)
{"jsonrpc":"2.0","id":5,"method":"eth_getProof","params":["0xAccount", ["0xSlot"], "finalized"]}

Useful for trust‑minimized verification pipelines; ensure your node/client supports proofs efficiently. (eips.ethereum.org)

  1. Access lists to pre‑warm storage (EIP‑2930)
{"jsonrpc":"2.0","id":6,"method":"eth_createAccessList","params":[{"from":"0x...","to":"0x...","data":"0x..."}, "latest"]}

Reduce cold SLOAD penalties on complex transactions. (support.huaweicloud.com)


If you’d like us to turn this blueprint into a concrete backlog for your team—SDK interfaces, OpenRPC spec, and a staging deployment—7Block Labs is ready to assist.

Like what you're reading? Let's build together.

Get a free 30‑minute consultation with our engineering team.

Related Posts

7BlockLabs

Full-stack blockchain product studio: DeFi, dApps, audits, integrations.

7Block Labs is a trading name of JAYANTH TECHNOLOGIES LIMITED.

Registered in England and Wales (Company No. 16589283).

Registered Office address: Office 13536, 182-184 High Street North, East Ham, London, E6 2JA.

© 2025 7BlockLabs. All rights reserved.