Using GraphQL with APIVerve
Learn how to leverage APIVerve's GraphQL API to build efficient, flexible applications. This guide covers everything from basic queries to advanced implementations with real-world examples.
Before you begin, make sure you have an APIVerve account and API key. If you haven't signed up yet, check out our Quick Start guide. Basic understanding of GraphQL concepts is helpful but not required.
Using the GraphQL Explorer
The easiest way to get started with APIVerve's GraphQL API is through our interactive GraphQL explorer. This browser-based tool lets you write, test, and debug queries without writing any code.
Accessing the Explorer
Navigate to dashboard.apiverve.com/graphql in your browser. You'll need to be logged into your APIVerve account to use the explorer. The interface includes three main panels:
- Query Editor - Write and edit your GraphQL queries
- Variables Panel - Define query variables for dynamic queries
- Results Panel - View query results and errors
- Documentation Explorer - Browse the schema and available fields
Explorer Features
The GraphQL explorer provides several powerful features to enhance your development experience:
- Autocomplete - Press Ctrl+Space to see available fields, types, and arguments
- Syntax Highlighting - Color-coded syntax makes queries easier to read
- Query Validation - Real-time validation catches errors before you run the query
- Query History - Access previously executed queries
- Schema Documentation - Inline documentation for all types and fields
- Prettify - Automatically format your queries for better readability
Use Ctrl+Space anywhere in your query to trigger autocomplete. This is the fastest way to discover available fields and build queries without constantly referring to documentation.
Basic Query Syntax
GraphQL queries follow a simple, hierarchical structure. You specify which fields you want, and the API returns exactly those fields in the same structure.
Simple Query Example
Here's a basic query to fetch data from the Chuck Norris jokes API:
query {
chucknorris {
joke
}
}This query will return a response like:
{
"data": {
"chucknorris": {
"joke": "Chuck Norris can divide by zero."
}
}
}Queries with Arguments
Many APIs require parameters. In GraphQL, you pass these as arguments to the query fields:
query {
qrcode(value: "https://apiverve.com", size: 300) {
qrcode
size
format
}
}Querying Multiple APIs
One of GraphQL's most powerful features is the ability to fetch data from multiple sources in a single request. This eliminates the need for multiple HTTP calls and simplifies your application logic.
query {
chucknorris {
joke
}
randomfacts {
fact
category
}
motivationalquotes {
quote
author
}
}This single query fetches data from three different APIs, and you'll receive all the results in one response:
{
"data": {
"chucknorris": {
"joke": "Chuck Norris can compile syntax errors."
},
"randomfacts": {
"fact": "Honey never spoils",
"category": "science"
},
"motivationalquotes": {
"quote": "The only way to do great work is to love what you do.",
"author": "Steve Jobs"
}
}
}Combining multiple API calls into a single GraphQL query can dramatically reduce network latency. Instead of waiting for three sequential HTTP requests to complete, you make one request and get all the data back together.
Making GraphQL Requests from Code
Once you've tested your queries in the explorer, you'll want to integrate them into your application. GraphQL requests are sent as HTTP POST requests to the GraphQL endpoint.
Endpoint & Authentication
All GraphQL queries are sent to:
https://api.apiverve.com/v1/graphqlAuthentication works the same as REST endpoints - include your API key in the X-API-Key header.
Code Examples
Here's how to make GraphQL requests in various programming languages:
curl -X POST https://api.apiverve.com/v1/graphql \
-H "Content-Type: application/json" \
-H "X-API-Key: YOUR_API_KEY_HERE" \
-d '{
"query": "query { chucknorris { joke } }"
}'const query = `
query {
chucknorris {
joke
}
}
`;
const response = await fetch('https://api.apiverve.com/v1/graphql', {
method: 'POST',
headers: {
'Content-Type': 'application/json',
'X-API-Key': 'YOUR_API_KEY_HERE'
},
body: JSON.stringify({ query })
});
const data = await response.json();
console.log(data.data.chucknorris.joke);import requests
import json
query = """
query {
chucknorris {
joke
}
}
"""
response = requests.post(
'https://api.apiverve.com/v1/graphql',
headers={
'Content-Type': 'application/json',
'X-API-Key': 'YOUR_API_KEY_HERE'
},
json={'query': query}
)
data = response.json()
print(data['data']['chucknorris']['joke'])<?php
$query = '
query {
chucknorris {
joke
}
}
';
$ch = curl_init('https://api.apiverve.com/v1/graphql');
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_POST, true);
curl_setopt($ch, CURLOPT_HTTPHEADER, [
'Content-Type: application/json',
'X-API-Key: YOUR_API_KEY_HERE'
]);
curl_setopt($ch, CURLOPT_POSTFIELDS, json_encode([
'query' => $query
]));
$response = curl_exec($ch);
curl_close($ch);
$data = json_decode($response, true);
echo $data['data']['chucknorris']['joke'];
?>const axios = require('axios');
const query = `
query {
chucknorris {
joke
}
}
`;
async function fetchData() {
try {
const response = await axios.post(
'https://api.apiverve.com/v1/graphql',
{ query },
{
headers: {
'Content-Type': 'application/json',
'X-API-Key': 'YOUR_API_KEY_HERE'
}
}
);
console.log(response.data.data.chucknorris.joke);
} catch (error) {
console.error('Error:', error.message);
}
}
fetchData();Using Query Variables
For dynamic queries where values change based on user input or application state, use query variables instead of hardcoding values in your query string. This makes queries reusable and prevents security issues.
query GenerateQRCode($url: String!, $size: Int) {
qrcode(value: $url, size: $size) {
qrcode
size
format
}
}Pass the variables as a separate object in your request:
{
"url": "https://apiverve.com",
"size": 500
}In JavaScript, you'd send both the query and variables:
const query = `
query GenerateQRCode($url: String!, $size: Int) {
qrcode(value: $url, size: $size) {
qrcode
size
format
}
}
`;
const variables = {
url: "https://apiverve.com",
size: 500
};
const response = await fetch('https://api.apiverve.com/v1/graphql', {
method: 'POST',
headers: {
'Content-Type': 'application/json',
'X-API-Key': 'YOUR_API_KEY_HERE'
},
body: JSON.stringify({ query, variables })
});Error Handling
GraphQL has a standardized error format. Errors are returned in an errors array alongside any partial data that was successfully fetched.
{
"errors": [
{
"message": "Field 'invalidField' doesn't exist on type 'Query'",
"locations": [
{
"line": 2,
"column": 3
}
]
}
]
}Always check for the presence of the errors field:
const response = await fetch('https://api.apiverve.com/v1/graphql', {
method: 'POST',
headers: {
'Content-Type': 'application/json',
'X-API-Key': 'YOUR_API_KEY_HERE'
},
body: JSON.stringify({ query })
});
const result = await response.json();
if (result.errors) {
console.error('GraphQL Errors:', result.errors);
// Handle errors appropriately
} else {
console.log('Data:', result.data);
// Process successful response
}Best Practices
Follow these recommendations to get the most out of GraphQL with APIVerve:
Request Only What You Need
The main benefit of GraphQL is precision. Don't request fields you won't use - this wastes bandwidth and processing time. Design your queries to fetch exactly the data your application needs.
Use the Explorer for Development
Always test and refine queries in the GraphQL explorer before adding them to your code. The explorer's autocomplete and validation save time and catch errors early.
Implement Proper Error Handling
GraphQL errors can be query syntax errors, API errors, or authentication issues. Implement comprehensive error handling to gracefully manage all error types.
Cache Responses Appropriately
GraphQL responses can be cached just like REST responses. Implement caching strategies based on your data's volatility to reduce API calls and improve performance.
Monitor Rate Limits
Rate limiting applies to each API you query within a GraphQL request. If you query three APIs in one GraphQL request, it counts as three API calls toward your rate limit.
When querying multiple APIs in a single GraphQL request, be aware that each API query counts separately toward rate limits. A single GraphQL request querying 5 different APIs will consume 5 API calls from your quota.
Advanced Usage
Aliases
Query the same API multiple times with different parameters using aliases:
query {
smallQR: qrcode(value: "https://apiverve.com", size: 200) {
qrcode
size
}
largeQR: qrcode(value: "https://apiverve.com", size: 500) {
qrcode
size
}
}Fragments
Reuse common field selections with fragments to keep queries DRY (Don't Repeat Yourself):
fragment QuoteFields on Quote {
quote
author
category
}
query {
motivationalquotes {
...QuoteFields
}
inspirationalquotes {
...QuoteFields
}
}You now have everything you need to start using GraphQL with APIVerve. Head over to the GraphQL explorer to start building queries. Experiment with different APIs and see how you can combine them to create powerful data queries for your applications.
Was this page helpful?
Help us improve our documentation