Getting started overview
This guide outlines the process for developers to begin integrating with the 1inch API, focusing on initial setup, authentication, and making a foundational API call. The 1inch Aggregation Protocol is designed to facilitate optimized token swaps by routing orders through various decentralized exchanges (DEXs) to find the most favorable rates 1inch Aggregation Protocol overview. The API provides programmatic access to this functionality, enabling developers to build applications that leverage 1inch's liquidity aggregation capabilities.
The primary steps involve creating a developer account, obtaining API credentials, and constructing a basic request to confirm connectivity and functionality. While the API itself is free to use, all on-chain transactions initiated through the API will incur standard blockchain network transaction fees, commonly referred to as gas fees 1inch API documentation. Understanding these fees is crucial for estimating operational costs when interacting with decentralized finance (DeFi) protocols.
Before proceeding, ensure you have a basic understanding of blockchain concepts, such as wallets, tokens, and network transactions, particularly on EVM-compatible chains like Ethereum and Polygon Polygon Proof-of-Stake chain information, which 1inch supports.
Here's a quick reference for getting started:
| Step | What to do | Where |
|---|---|---|
| 1. Access Developer Portal | Navigate to the 1inch Developer Portal. | 1inch Developer Portal |
| 2. Create Account | Sign up for a new account. | 1inch Developer Portal registration |
| 3. Generate API Key | Create a new API key within your dashboard. | 1inch Developer Dashboard |
| 4. Install Dependencies (Optional) | Install a preferred HTTP client or 1inch SDK (JavaScript, Python). | NPM, Pip, or direct download |
| 5. Make First Request | Execute a cURL command or use an SDK to fetch supported chains. | Terminal or code editor |
Create an account and get keys
To begin using the 1inch API, you must first create a developer account and generate an API key. This key serves as your authentication credential for all API requests.
-
Navigate to the 1inch Developer Portal: Open your web browser and go to the official 1inch Developer Portal.
-
Sign Up for an Account: If you don't already have an account, click on the "Sign Up" or "Get Started" option. You will typically be prompted to provide an email address and create a password. Follow the on-screen instructions to complete the registration process, which may include email verification.
-
Log In to Your Dashboard: Once registered and verified, log in to your 1inch Developer Dashboard.
-
Generate an API Key: Within your dashboard, locate the section related to "API Keys" or "Applications." Click on an option to "Create New API Key" or "Add New Application." You might be asked to provide a name for your application or key for organizational purposes. After creation, your API key will be displayed. This key is a long alphanumeric string.
Important: Treat your API key as a sensitive credential. Do not embed it directly into client-side code, commit it to public version control systems, or share it unnecessarily. Best practices suggest using environment variables or a secure key management system to store and retrieve your API key Google Cloud API key best practices.
-
Copy Your API Key: Copy the generated API key to a secure location. You will need this key to authenticate your API requests.
Your first request
After obtaining your API key, you can make your first request to the 1inch API to verify connectivity. A common initial request is to fetch the list of supported chains (blockchains) that the 1inch Aggregation Protocol operates on. This request does not require any on-chain transactions and serves as a good test of your setup.
The 1inch API uses a base URL structure, where the chain ID is often a path parameter. For instance, Ethereum is chain ID 1, and Polygon is chain ID 137.
API Endpoint for Supported Chains:
GET https://api.1inch.dev/swap/v6.0/{chain_id}/chains
Replace {chain_id} with a valid chain ID, for example, 1 for Ethereum.
Using cURL (Command Line)
This is the quickest way to test your API key without writing code. Replace YOUR_API_KEY with the key you generated.
curl -X GET \
'https://api.1inch.dev/swap/v6.0/1/chains' \
-H 'accept: application/json' \
-H 'Authorization: Bearer YOUR_API_KEY'
A successful response will return a JSON object listing the supported chains and their details.
{
"chains": [
{
"id": 1,
"name": "Ethereum",
"shortName": "eth",
"currency": {
"name": "Ethereum",
"symbol": "ETH",
"decimals": 18
},
"explorers": [
"https://etherscan.io"
]
},
// ... other chains
]
}
Using JavaScript (Node.js with node-fetch)
For JavaScript environments, you can use node-fetch (or the built-in fetch in modern Node.js versions) to make requests.
const fetch = require('node-fetch'); // If using older Node.js or not in a browser
const API_KEY = 'YOUR_API_KEY'; // Replace with your actual API key
const CHAIN_ID = 1; // Example: Ethereum
async function getSupportedChains() {
try {
const response = await fetch(`https://api.1inch.dev/swap/v6.0/${CHAIN_ID}/chains`, {
method: 'GET',
headers: {
'accept': 'application/json',
'Authorization': `Bearer ${API_KEY}`
}
});
if (!response.ok) {
throw new Error(`HTTP error! status: ${response.status}`);
}
const data = await response.json();
console.log('Supported Chains:', data);
} catch (error) {
console.error('Error fetching supported chains:', error);
}
}
getSupportedChains();
To run this code, ensure you have Node.js installed and, if necessary, install node-fetch:
npm install node-fetch
node your_script_name.js
Using Python (with requests)
For Python developers, the requests library is a common choice for making HTTP requests.
import requests
API_KEY = 'YOUR_API_KEY' # Replace with your actual API key
CHAIN_ID = 1 # Example: Ethereum
def get_supported_chains():
url = f"https://api.1inch.dev/swap/v6.0/{CHAIN_ID}/chains"
headers = {
'accept': 'application/json',
'Authorization': f'Bearer {API_KEY}'
}
try:
response = requests.get(url, headers=headers)
response.raise_for_status() # Raise an exception for HTTP errors
data = response.json()
print("Supported Chains:", data)
except requests.exceptions.RequestException as e:
print(f"Error fetching supported chains: {e}")
get_supported_chains()
To run this code, ensure you have Python installed and install the requests library:
pip install requests
python your_script_name.py
Common next steps
Once you have successfully made your first API call and confirmed your setup, you can explore more advanced functionalities of the 1inch API. Common next steps often involve integrating the core swap functionality and understanding gas estimation.
-
Fetch Quote for a Swap: Before executing a swap, you'll typically want to get a quote to understand the best available exchange rate and the amount of tokens you'll receive. The
/quoteendpoint allows you to specify the tokens you want to swap (fromTokenAddress,toTokenAddress) and the amount (amount). This call does not execute a transaction but provides the optimal swap path and expected return 1inch Aggregation Protocol API reference.GET https://api.1inch.dev/swap/v6.0/{chain_id}/quote ?fromTokenAddress={token_address} &toTokenAddress={token_address} &amount={amount_in_wei} -
Prepare Transaction for a Swap: To actually execute a swap on-chain, you'll use the
/swapendpoint. This endpoint returns the transaction data that your wallet (or your user's wallet) needs to sign and send to the blockchain. This includes thetoaddress,data(calldata), andvalue(for native token swaps like ETH). Remember that executing this transaction will incur gas fees.GET https://api.1inch.dev/swap/v6.0/{chain_id}/swap ?fromTokenAddress={token_address} &toTokenAddress={token_address} &amount={amount_in_wei} &fromAddress={your_wallet_address} &slippage={slippage_percentage}The
fromAddressparameter is crucial here as it specifies the wallet initiating the swap.slippageis a percentage representing the maximum acceptable price movement during the transaction execution 1inch swap API documentation. -
Handle Token Approvals: For ERC-20 token swaps (any token other than the native chain token like ETH or MATIC), you must first approve the 1inch router contract to spend your tokens. This is a separate on-chain transaction that grants permission for the router to transfer your specified tokens from your wallet. The
/approve/transactionendpoint can help generate this approval transaction data.GET https://api.1inch.dev/swap/v6.0/{chain_id}/approve/transaction ?tokenAddress={token_address} &amount={amount_in_wei} -
Integrate with a Wallet: Since 1inch transactions are on-chain, your application will need to integrate with a Web3 wallet (e.g., MetaMask, WalletConnect) to allow users to sign and send transactions. The 1inch API provides the raw transaction data, and the wallet is responsible for signing and broadcasting it.
-
Error Handling: Implement robust error handling for API responses, network issues, and blockchain transaction failures. The 1inch API typically returns descriptive error messages in JSON format.
Troubleshooting the first call
Encountering issues during your first API call is common. Here are some troubleshooting steps for typical problems:
-
"Unauthorized" or "401" Error:
- Check API Key: Ensure your API key is correctly included in the
Authorization: Bearer YOUR_API_KEYheader. Double-check for typos, extra spaces, or missing characters. - Key Validity: Verify that your API key is still active and has not expired or been revoked in your 1inch Developer Dashboard.
- Header Format: Confirm the header is exactly
Authorization: Bearer YOUR_API_KEY, including the "Bearer " prefix and a space.
- Check API Key: Ensure your API key is correctly included in the
-
"Not Found" or "404" Error:
- Endpoint URL: Verify the API endpoint URL is correct. Check for any typos in the base URL (
https://api.1inch.dev/swap/v6.0/), chain ID, or endpoint path (e.g.,/chains). - Chain ID: Ensure the
chain_idyou are using (e.g.,1for Ethereum) is valid and supported by the 1inch API.
- Endpoint URL: Verify the API endpoint URL is correct. Check for any typos in the base URL (
-
"Bad Request" or "400" Error:
- Missing Parameters: For endpoints that require parameters (like
/quoteor/swap), ensure all mandatory parameters are provided and correctly formatted. - Parameter Values: Check that parameter values, such as token addresses or amounts, are valid. Token amounts for ERC-20 tokens are typically expressed in Wei (smallest unit), not whole tokens.
- JSON Formatting: If you are sending a POST request with a JSON body, ensure the JSON is well-formed and valid.
- Missing Parameters: For endpoints that require parameters (like
-
Network Issues:
- Internet Connection: Confirm your internet connection is stable.
- Firewall/Proxy: If you are behind a corporate firewall or proxy, ensure it is not blocking access to
api.1inch.dev.
-
Unexpected Response or Empty Data:
- Check API Documentation: Refer to the 1inch API reference documentation for the specific endpoint you are calling to understand the expected request and response formats.
- Console Logs: Use
console.log()(JavaScript) orprint()(Python) to output the full response, including headers and body, to inspect for any hidden error messages.
-
Rate Limiting: While 1inch API usage is generally free, there might be rate limits. If you are making many requests in a short period, you might temporarily be throttled. Check the response headers for
X-RateLimit-*information if available, or try waiting a few moments before retrying. Details on specific rate limits are generally found in the official documentation.