OP Mainnet API Quickstart

How to get started building on Optimism and use the JSON-RPC API

Don’t have an API key?

Sign up to start building on Optimism. Get started for free

Getting Started Instructions

1. Choose a package manager (npm or yarn)

For this guide, we will be using npm or yarn as our package manager to install Viem or Ethers.js.

npm

To get started with npm, follow the documentation to install Node.js and npm for your operating system: https://docs.npmjs.com/downloading-and-installing-node-js-and-npm

yarn

To get started with yarn, follow these steps: https://classic.yarnpkg.com/lang/en/docs/install

2. Set up your project (npm or yarn)

mkdir alchemy-optimism-api
cd alchemy-optimism-api
npm init --yes

3. Install Web3 Library

Run the following command to install Viem or Ethers.js with npm or yarn.

npm install viem

4. Make your first request

You are all set now to use Optimism API and make your first request. For instance, lets make a request to get latest block. Create an index.js file and paste the following code snippet into the file.

index.js
1import { createPublicClient, http } from 'viem'
2import { optimism } from 'viem/chains'
3
4const client = createPublicClient({
5 chain: optimism,
6 transport: http('https://opt-mainnet.g.alchemy.com/v2/demo') // Replace 'demo' with your API Key
7})
8
9async function main() {
10 const latestBlock = await client.getBlockNumber()
11 console.log('The latest block number is', latestBlock)
12}
13
14main()

5. Run script

To run the above node script, use cmd node index.js, and you should see the output.

shell
The latest block number is 43869847

Optimism Tutorials

You must not stop here! Want to build your first Dapp on Optimism and use Optimism APIs?

Check out the following tutorials to learn how to build on Optimism:

For full documentation on modern Web3 libraries: