JAVASCRIPT
Consuming a GraphQL API (JavaScript)
Perform basic GraphQL queries and mutations from a JavaScript client using the Fetch API, demonstrating efficient data retrieval from GraphQL endpoints.
const GRAPHQL_API_URL = 'https://countries.trevorblades.com/'; // A public GraphQL API example
async function fetchGraphQLData(query, variables = {}) {
try {
const response = await fetch(GRAPHQL_API_URL, {
method: 'POST',
headers: {
'Content-Type': 'application/json',
'Accept': 'application/json',
},
body: JSON.stringify({
query,
variables
})
});
if (!response.ok) {
const errorText = await response.text();
throw new Error(`HTTP error! Status: ${response.status}, Details: ${errorText}`);
}
const result = await response.json();
if (result.errors) {
console.error('GraphQL Errors:', result.errors);
throw new Error('GraphQL operation failed: ' + JSON.stringify(result.errors));
}
return result.data;
} catch (error) {
console.error('Error fetching GraphQL data:', error);
throw error;
}
}
// Example Usage: Fetching a list of continents
async function getContinents() {
const query = `
query {
continents {
code
name
}
}
`;
try {
console.log('Fetching continents...');
const data = await fetchGraphQLData(query);
console.log('Continents:', data.continents);
} catch (e) {
console.error('Failed to fetch continents.');
}
}
// Example Usage: Fetching details for a specific country with a variable
async function getCountryDetails(countryCode) {
const query = `
query CountryDetails($code: ID!) {
country(code: $code) {
name
capital
currency
continent {
name
}
languages {
name
}
}
}
`;
const variables = { code: countryCode };
try {
console.log(`
Fetching details for country code: ${countryCode}...`);
const data = await fetchGraphQLData(query, variables);
console.log(`Country (${countryCode}):`, data.country);
} catch (e) {
console.error(`Failed to fetch details for country ${countryCode}.`);
}
}
// Run examples
(async () => {
await getContinents();
await getCountryDetails('BR'); // Brazil
await getCountryDetails('US'); // United States
})();
How it works: This JavaScript snippet demonstrates how to consume a GraphQL API using the standard Fetch API. GraphQL requests are typically POST requests with a JSON body containing a `query` string (the GraphQL query or mutation) and optionally `variables`. The `fetchGraphQLData` function abstracts this, handling the request and parsing the JSON response. It also includes basic error checking for both HTTP errors and GraphQL-specific errors reported in the `errors` array of the response.