Getting started overview
This guide provides a focused walkthrough for developers to begin using The Graph for querying blockchain data. It covers the initial setup steps necessary to perform a first working request, specifically utilizing The Graph's Hosted Service for simplicity and speed. Readers will learn how to create an account, obtain an API key, and execute a GraphQL query against an existing subgraph.
The Graph is an indexing protocol for organizing blockchain data and making it easily accessible with GraphQL. It enables developers to build and publish open APIs, called subgraphs, that applications can query. The Hosted Service provides a platform for deploying and querying subgraphs without directly engaging with the decentralized Graph Network, offering a streamlined entry point for development and testing. Access to The Graph's functionality primarily relies on GraphQL API requests, which facilitate structured queries for specific blockchain data points once a subgraph has been established or selected. The The Graph querying documentation provides further details on constructing queries.
Here's a quick reference for the essential steps:
| Step | What to Do | Where |
|---|---|---|
| 1. Create Account | Register for a free account on The Graph Explorer. | The Graph Explorer |
| 2. Get API Key | Generate an API key from your account dashboard. | The Graph Hosted Service dashboard |
| 3. Select Subgraph | Choose an existing subgraph to query, such as one for Uniswap or Aave. | The Graph Explorer |
| 4. Construct Query | Formulate a GraphQL query to retrieve specific data from the chosen subgraph. | Any GraphQL client or tool |
| 5. Make Request | Execute the GraphQL query using your API key. | cURL, Postman, a code snippet (e.g., JavaScript) |
Create an account and get keys
To begin querying data with The Graph's Hosted Service, you must first create an account and obtain an API key. This key authenticates your requests and tracks your usage for billing purposes, especially beyond the free tier of 100,000 queries per month.
-
Navigate to The Graph Explorer: Open your web browser and go to The Graph Explorer.
-
Sign Up: Click on the 'Sign Up' or 'Get Started' button. You will typically be prompted to sign up using an email address and password, or potentially via a Web3 wallet connection for future decentralized network interactions. For the Hosted Service, an email registration is standard.
-
Verify Email: Follow the instructions to verify your email address. This usually involves clicking a link sent to your registered email.
-
Access Dashboard: Once logged in, you will be directed to your dashboard within The Graph Hosted Service. This dashboard provides an overview of your subgraphs and API keys.
-
Generate API Key: Look for a section labeled 'API Keys' or 'Developer Settings'. Click on 'Create New Key' or a similar option. Give your API key a descriptive name (e.g., "My First Subgraph Query"). The platform will generate a unique API key for you. This key is crucial for authenticating your GraphQL requests. Copy and store this key securely, as it will not be displayed again in its entirety for security reasons.
The API key is a string that identifies your account. When making requests to a subgraph hosted on The Graph's hosted service, you will include this key in the request header or URL, depending on the client library or method you use.
Your first request
With your account created and API key secured, you can now perform your first GraphQL query. This example will use a publicly available subgraph to retrieve data.
-
Choose a Subgraph: The Graph Explorer lists numerous public subgraphs. For this example, we'll use a widely recognized one, such as the Uniswap V2 subgraph for Ethereum. Navigate to its page on The Graph Explorer.
-
Locate Query URL: On the subgraph's details page, find the 'Query URL' or 'Endpoint'. It will typically look like
https://api.thegraph.com/subgraphs/name/uniswap/uniswap-v2(for the decentralized network) or a similar format for the Hosted Service, possibly including your API key (e.g.,https://api.thegraph.com/subgraphs/id/YOUR_API_KEY/SUBGRAPH_ID). For the Hosted Service, the URL will be specific to your deployment or a public hosted endpoint. -
Construct a GraphQL Query: GraphQL queries are structured to request specific data fields. Here's an example query to fetch the first 5 pairs from the Uniswap V2 subgraph, including their token addresses and total liquidity:
{ pairs(first: 5, orderBy: volumeUSD, orderDirection: desc) { id token0 { id symbol } token1 { id symbol } reserveUSD volumeUSD } } -
Execute the Query using
curl: You can usecurlfrom your terminal to make a quick test request. ReplaceYOUR_SUBGRAPH_QUERY_URLwith the actual query URL you obtained from The Graph Explorer andYOUR_API_KEYwith your generated key if the endpoint requires it in the header.curl -X POST \ -H "Content-Type: application/json" \ -H "Authorization: Bearer YOUR_API_KEY" \ --data '{ "query": "{ pairs(first: 5, orderBy: volumeUSD, orderDirection: desc) { id token0 { id symbol } token1 { id symbol } reserveUSD volumeUSD } }" }' \ YOUR_SUBGRAPH_QUERY_URLNote: Some Hosted Service endpoints don't require the
Authorizationheader if the API key is embedded in the URL path. Always refer to the specific subgraph's documentation for the correct endpoint format and authentication method. If your endpoint is public and does not require an API key for basic querying, you can omit the-H "Authorization: Bearer YOUR_API_KEY"line. -
Execute the Query using JavaScript (Node.js/Browser): For programmatic access, you can use a library like
graphql-requestorapollo-client.import { GraphQLClient, gql } from 'graphql-request'; const endpoint = 'YOUR_SUBGRAPH_QUERY_URL'; const API_KEY = 'YOUR_API_KEY'; // Only if required by the endpoint const graphQLClient = new GraphQLClient(endpoint, { headers: { authorization: API_KEY ? `Bearer ${API_KEY}` : '', // Include API key if needed }, }); const query = gql` { pairs(first: 5, orderBy: volumeUSD, orderDirection: desc) { id token0 { id symbol } token1 { id symbol } reserveUSD volumeUSD } } `; async function main() { try { const data = await graphQLClient.request(query); console.log(JSON.stringify(data, undefined, 2)); } catch (error) { console.error('Error fetching data:', error); } } main();To run this JavaScript example, you would typically install
graphql-request:npm install graphql-request graphql. This client simplifies GraphQL interactions and handles the HTTP request details.
A successful response will return a JSON object containing the requested data (e.g., the details of the first 5 Uniswap V2 pairs). An error response will typically include an errors array with details about what went wrong.
Common next steps
After successfully executing your first query, consider these next steps to deepen your engagement with The Graph:
-
Explore More Subgraphs: Browse The Graph Explorer to discover other subgraphs relevant to your interests or projects. Many popular decentralized applications actively maintain subgraphs.
-
Learn Advanced Querying: The GraphQL specification supports various features like arguments, variables, fragments, and aliases. Mastering these can help you construct more efficient and precise queries. The GraphQL documentation on queries offers a comprehensive overview.
-
Develop a Custom Subgraph: For data not available through existing subgraphs, or for highly specific application needs, you can create your own subgraph. This involves defining a GraphQL schema, writing mapping handlers in WebAssembly (AssemblyScript) to process smart contract events, and deploying it to the Hosted Service or the Decentralized Network. This process requires understanding blockchain event structures and smart contract interactions.
-
Integrate with Applications: Integrate The Graph queries into your decentralized applications (dApps) or traditional web services. Client libraries for JavaScript, Python, and other languages facilitate this integration. The The Graph documentation for querying from applications provides examples across different environments.
-
Explore the Decentralized Network: Once comfortable with the Hosted Service, investigate deploying your subgraphs or querying existing ones on the decentralized Graph Network. This involves using Graph Tokens (GRT) and interacting with network roles like Indexers, Curators, and Delegators, as described in The Graph Network documentation.
Troubleshooting the first call
Encountering issues during your initial requests is common. Here are some troubleshooting steps:
-
Verify API Key: Ensure your API key is correctly copied and included in your request. If using
curl, check for typos. If using a client library, confirm the key is passed to the authentication header or URL parameter as expected. An invalid or missing key will result in authentication errors. -
Check Query URL/Endpoint: Double-check that the subgraph's query URL is correct and matches the one provided in The Graph Explorer for your chosen subgraph. Mistakes in the URL path can lead to 404 Not Found errors or incorrect routing.
-
Inspect GraphQL Syntax: GraphQL queries are strict about syntax. Even small errors like a missing comma, bracket, or misspelled field name can cause a query to fail. Use a GraphQL IDE (like the one built into The Graph Explorer or tools like Postman/Insomnia) to validate your query syntax before making programmatic requests. The The Graph documentation on querying subgraphs includes query examples.
-
Review Error Messages: When a request fails, The Graph's API typically returns a JSON response containing an
errorsarray. Read these messages carefully, as they often provide specific details about what went wrong, such as invalid fields, arguments, or permissions. -
Confirm Subgraph Health: The subgraph you are trying to query might be out of sync or experiencing issues. Check its status on The Graph Explorer. Look for indicators like 'Synced' status and recent block processing. A subgraph that is not fully synced may return incomplete or outdated data, or specific queries might fail.
-
Rate Limiting: If you are making many requests in a short period, especially on the free tier, you might encounter rate limiting. The Graph's Hosted Service has rate limits to ensure fair usage. If you suspect this, reduce your request frequency or check your dashboard for usage statistics. Consider upgrading your plan if sustained high query volume is needed, detailed on The Graph pricing page.
-
Network Issues: Ensure your local network connection is stable and that no firewalls or proxies are blocking access to
api.thegraph.com.