0x 101: Getting started with Swap API

In this guide, we'll dive into how to build with Swap API - using it to programmatically find the best token price and execute a trade.

May 16, 2023

Learn & Build

In 0x 101: Intro to Swap API, we covered the basics of Swap API and how it benefits users and Web3 developers. In this guide, we'll dive into how to build with Swap API - using it to programmatically find the best token price and execute a trade.

To recap, Swap API is a REST API that runs on HTTP. Swap API aggregates liquidity from 100+ liquidity sources, including the most popular AMMs and private market makers, across chains, allowing you to easily tap into the deepest liquidity with one simple integration.

Under the hood, Swap API:

  • Queries prices from dozens of decentralized exchanges and market makers and aggregates the liquidity from the queried sources to provide the best price possible. 
  • Swap API’s proprietary smart order routing algorithm then splits up a user’s transaction across different sources to maximize the overall return on the trade.
  • Swap API's responses are returned in a format that can be easily executed using the Web3 library of your choice. Whether you prefer web3.js, ether.js, or something else, you are in control.

The Swap API has 3 endpoints - quote, price, source. First, let’s take a look at the quote endpoint. Then we’ll see how you can swap tokens with Swap API in 3 simple steps.

GET /swap/v1/quote

This endpoint allows you to get an easy-to-consume quote for buying or selling any ERC20 token. The return format is a valid unsigned Ethereum transaction and can be submitted directly to an Ethereum node (or the nodes of other chains if applicable) to complete the swap. 

Request

Here is a simple GET request to get a quote to buy DAI with 1 WETH:

https://api.0x.org/swap/v1/quote?buyToken=DAI&sellToken=WETH&sellAmount=100000000000000000&0x-api-key=35aa607c-1e98-4404-ad87-4bed10a538ae

We can break down the request to see the required request parameters:

  1. Network: Indicates the network we want to query. This example shows ETH Mainnet. For a full list of endpoints, check out this list.
  2. Quote request: Indicates we want a quote to buy or sell an ERC 20 token.
  3. buyToken: Indicates the ERC20 token address or symbol of the token we want to receive, in this case DAI.
  4. sellToken: The ERC20 token address or symbol of the token we want to send, in this case WETH.
  5. sellAmount: The amount of sellToken (in the units of the sellToken) that we want to send.

This is actually a live, queryable request. Go ahead and try it with curl or make the request from your browser.

Response

In the response, you will see a live quote on mainnet. At the time of writing this article, I can get 1596.87 DAI if I sell 1 WETH as seen in the price parameter. 

Here are the results pretty-fied:

Some notable things to call out: 

  • The response returned is an unsigned transaction which includes everything, such as the gas price and call data, needed to directly send the transaction to the network. Because of this, you can directly send the raw transaction object to web3.js’s sendTransaction() function.
  • Notice all the sources that Swap API is querying. It finds the best price, 100% through Sushiswap.
  • Note: If you are using ethers.js, you will need to pull out and submit only the required parameters. See more details here.
  • Note: In a production implementation, you’ll want to add some error handling for the API response.

Swap tokens with Swap API in 3 simple steps

Now that we know how to query Swap API and how it responds, let’s look at how to programmatically call it and execute a trade. 

If you are creating an application on mainnet, you will need to create a 0x account and get a live API key. Learn more about how to set up a 0x account here.

Once you have an API key, it is as simple as these 3 steps: 

  1. (If needed) Set token allowance
  2. Fetch a swap quote
  3. Sign a transaction with your favorite Web3 library

Here are the 3 steps shown in a simple code snippet (you can find the code here):

Step 1: Set a token allowance

A token allowance is required if you want a third-party to move funds on your behalf. In short, you are allowing them to move your tokens.

In our case, we would like 0x Protocol’s Exchange Proxy smart contract to trade our ERC20 tokens for us, so we will need to approve an allowance (a certain amount) for this contract to move a certain amount of our ERC20 tokens on our behalf.

In the code snippet below, we allow the 0x smart contract to interact with the DAI from the user’s wallet address.

If you need help setting a token allowance, check out the guide on “How to Set Your Token Allowance”

Step 2: Fetch a swap quote

Once the token allowance has been set, we can fetch the swap quote using the Swap API request that we looked into earlier. 

Step 3: Sign the transaction with your favorite Web3 library

Once we receive a quote, we can sign it with our favorite Web3 library (e.g. web3.js or ethers.js) to send the transaction to the network. 

Recall that the response returned by the quote is an unsigned transaction which includes everything, such as the gas price and call data, needed to directly send the transaction to the network.

In this example, we are using web3.eth.sendTransaction(), so we can directly pass in the response.

Note: If you are using ethers.js, you will need to pull out and submit only the required parameters. See more details here

Note: In a production implementation, you’ll want to add some error handling for the API response.

And that’s it! In 3 simple steps, you’ve retrieved a live swap quote from the 0x Swap API and executed the trade. 

If you would like to learn how to plug Swap API into a full token swapping app with UI/UX, check out “How to Build a Token Swap Dapp With Swap API”.

Price and Sources

Before we wrap up, we mentioned above that Swap API has 3 endpoints - quote, price, sources. Let’s take a quick look at the other two.

GET /swap/v1/price

swap/v1/price is nearly identical to /swap/v1/quote, but with a few key differences.

/price does not return a transaction that can be submitted on-chain, it simply provides us the same information. Think of it as the "read-only" version of /quote.

This is important because /quote returns back an order in which a Market Maker has committed their assets to. So, if we ping /quote too much when what we really are just asking for is a price then this can clog up the system!

This endpoint is great if you just want to query prices and don’t need to get transaction data back. As a developer, you may choose to use this endpoint when users are just checking for a price rather than have confirmed they want to trade their tokens. 

Here is an example of a GET HTTP /price request. The call is almost identical to /quote:

https://api.0x.org/swap/v1/price?buyToken=DAI&sellToken=WETH&sellAmount=100000000000000000

You can learn more about /price here.

GET /swap/v1/sources

Lastly, there’s also the /sources endpoint, which returns a list of all the available liquidity sources on a specified chain. This may be useful if you would like to display all the liquidity sources available for a trade to your end-user or to help you as a developer understand where liquidity is coming from. 

For example, use this request to get a list of liquidity sources on Fantom:

https://fantom.api.0x.org/swap/v1/sources

Wrapping up

In this guide, we looked at how Swap API programmatically sources the best token price and returns the data in a way that is easy for DeFi developers to incorporate into their apps. To learn more about building on 0x, check out the Swap API docs and our full list of 0x guides.

Next, check out our end-to-end tutorial below on how to build a token swap app with Swap API. In this tutorial, you’ll learn how to build a user-facing app that allows users to connect their wallets and trade ERC20 tokens via the API.

Contents

Subscribe to newsletter

By submitting you're confirming that you agree with our Terms and Conditions.
Yay! You’re signed up.
Oops! Something went wrong, but it's not your fault.

Up next

Fundamentals: Smart Contract Wallets

Oct 15, 2024

Compliance made easy with 0x Address Screening

Sep 26, 2024

0x's next-gen pricing engine is now live

Sep 25, 2024

Introducing state-of-the-art Buy/Sell Tax support

Sep 4, 2024

Take control of your balance sheet with 0x v2

Aug 15, 2024

0x v2 bug bounty program

Jul 30, 2024

What does the "best price" in DeFi really mean?

Jul 23, 2024

Eliminate allowance risk with Permit2

Jul 17, 2024

Introducing 0x's next-gen pricing engine

Jul 15, 2024

0x Dev Digest: May 2024

May 31, 2024

Frame spotlight: Paycaster

May 21, 2024

Frame spotlight: Airstack

May 9, 2024

Power up your Farcaster Frames with 0x swaps

May 2, 2024

0x Dev Digest: April 2024

Apr 30, 2024

Introducing 0x Trade Analytics

Mar 12, 2024

Coinbase Case Study

Jan 30, 2024

Introducing gasless swaps and approvals with Gasless API

Jan 22, 2024

Bitcoin ETFs have arrived

Jan 12, 2024

Building in the open: 0x pricing update

Dec 11, 2023

Matcha leverages Gasless API to bring users the most frictionless trading experience in DeFi

Nov 30, 2023

0x Dev Digest: October 2023

Nov 2, 2023

Monetize crypto trading in your app with Swap API

Oct 26, 2023

0x Dev Digest: September 2023

Oct 3, 2023

A comprehensive analysis of RFQ performance

Sep 26, 2023

Unlock optimal trades in Swap API with 0x RFQ liquidity

Sep 20, 2023

0x Dev Digest: August 2023

Aug 31, 2023

Portal launches swaps in its white label MPC wallet powered by 0x

Aug 16, 2023

0x Swap API is now live on Base

Aug 9, 2023

Introducing paid plans for Swap API

Jul 24, 2023

Decreasing Frictions in DeFi hackathon recap

Jul 12, 2023

0x's pricing principles

Jul 3, 2023

0x Dev Digest: June 2023

Jun 30, 2023

App spotlight: tastycrypto

Jun 27, 2023

App spotlight: 31Third

Jun 22, 2023

0x 101: Intro to gasless API

Jun 13, 2023

Inspiration for building with Swap API

Jun 8, 2023

0x Dev Digest: May 2023

May 31, 2023

Fundamentals: What are gas fees?

May 25, 2023

Decreasing Frictions in DeFi Hackathon

May 12, 2023

Swap API liquidity management

May 18, 2023

0x 101: Intro to Swap API

May 9, 2023

0x 101: Intro to 0x Orders

May 4, 2023

0x 101: Intro to 0x Protocol

Apr 27, 2023

A new home for 0x Protocol

Apr 24, 2023

Say hi to the new 0x

Apr 20, 2023

0x Year in Review 2022

Jan 5, 2023

0x Swap API expands to Arbitrum

Sep 22, 2022

Managed liquidity

Apr 23, 2020

0x Smart Order Routing

May 19, 2020

App spotlight: Taho

Mar 8, 2022

Fundamentals: What is a Layer 2 chain?

Apr 19, 2023

Fundamentals: What is the difference between quoted, executed, and adjusted prices?

Apr 19, 2023

Fundamentals: What is price impact?

Apr 19, 2023

Fundamentals: What is slippage?

Apr 19, 2023

Fundamentals: What is an automated market maker (AMM)?

Apr 19, 2023

Fundamentals: What is market making?

Apr 19, 2023

Fundamentals: What is a DEX aggregator?

Apr 19, 2023

Fundamentals: What is liquidity?

Apr 19, 2023

Fundamentals: What is a decentralized exchange (DEX)?

Apr 19, 2023

0x at ETHDenver 2023

Mar 21, 2023

The 0x Mission and Values

Jun 7, 2018

Announcing support for new testnets

Aug 10, 2022

0x Swap API expands to Binance Smart Chain

Mar 17, 2021

Scaling DeFi — Layer One

Sep 1, 2021

Introducing Slippage Protection

Jul 14, 2022

San Francisco Blockchain Week 2022 Recap

Nov 21, 2022

0x Swap API adds new liquidity sources

Jul 11, 2022

Review of slippage performance

Sep 14, 2022

Phuture case study

Oct 20, 2022

Measuring the impact of hidden DEX costs

Apr 14, 2022

Market making in DeFi

Aug 12, 2021

Introducing 0x Labs

Jun 22, 2020

Introducing 0x Explorer

Oct 26, 2022

Growing DeFi with professional market makers

Aug 26, 2020

0x 101: How to Access 0x Data

Apr 25, 2023

GameStop chooses 0x Swap API

Jul 8, 2022

Build on Base with 0x

Feb 23, 2023

A comprehensive analysis on DEX liquidity aggregators’ performance

Oct 1, 2020

Announcing 0x Swap API v1

Oct 1, 2020

Access all DEX liquidity through 0x Swap API

Jan 28, 2020

Announcing the 0xpo Summit 2022

Aug 24, 2022

0x Protocol, a preview of what’s to come

Mar 16, 2023

Update to our Privacy Policy

Mar 14, 2023

Price Impact Protection has arrived

Dec 14, 2022

0x Limit Orders Go Multi-Chain

Dec 23, 2021

0x Labs raises $70M Series B led by Greylock to continue expanding Web3’s core exchange infrastructure

Apr 26, 2022

0x launches Tx Relay API in beta, with Robinhood Wallet as first partner

Mar 1, 2023

0x Labs raises $15M Series A to bring decentralized exchange markets to a global audience

Feb 5, 2021

App spotlight: Zerion

Jun 22, 2022

App spotlight: Matcha

Nov 24, 2021

App spotlight: DexGuru

Jun 17, 2021

App spotlight: DEXTools

Sep 23, 2021

App spotlight: DODO

Aug 10, 2021

App spotlight: DappRadar

Dec 16, 2021

App spotlight: DeFi Saver

Jul 20, 2021

0x + Brave partner to make crypto and DeFi more accessible to everyone

Jul 7, 2021

0x Swap API now supports 0x Protocol v4

Mar 1, 2021

0x Swap API is now available on Fantom

Oct 26, 2021

0x Swap API is now live on Optimism

Jan 11, 2022

0x Swap API is now available on Polygon

May 31, 2021