Over the last decade, GraphQL has become increasingly popular among developers. It was introduced by Facebook in 2015 and quickly gained attention for its flexibility in handling data requests. As we can see in the GraphQL Report 2024, many developers and firms have adopted GraphQL in their tech stack. This means that it’s still gaining traction, and by now, there’s a strong community around it.
This growth has led to the development of many tools and resources to support GraphQL. Today, there are many services that can get you up and running with a production API, plenty of resources, and communities where developers can learn and share their experiences with GraphQL. This support system built over years makes it easier for developers to use GraphQL in their projects and build better apps.
In this article, we will explore ways to consume data from a GraphQL server when developing web and mobile applications with different frontend technologies.
#Web
Many options are available to set up the frontend of Web Applications. Javascript-based frameworks are the most popular in this domain, we’ll also explore other frameworks like Hugo, Jekyll and more. We are assuming you have a GraphQL server set up. But, if you don’t, you can spin up one for free within seconds using Hygraph.
Javascript based frameworks
When talking about production-grade frontend web applications, most web apps today use some flavour of React or Vue with a combination of frameworks like Next.js or Nuxt.js. We will go through various client-side options for getting data from a GraphQL server.
Fetch
The native Javascript Fetch API can be used to query a GraphQL endpoint. It is a simple HTTP request to our GraphQL server and needs no additional dependencies.
import { HYGRAPH_URL, HYGRAPH_PERMANENTAUTH_TOKEN } from '../lib/constants';// Prepare the requestconst headers = {'content-type': 'application/json','Authorization': `Bearer ${HYGRAPH_PERMANENTAUTH_TOKEN}`};const requestBody = {query: `query getUserByEmail($email:String!){nextUser(where:{email:$email}){firstname}}`,variables: { email }};const options = {method: 'POST',headers,body: JSON.stringify(requestBody)};// Send the request via the native javascript fetch callconst response = await (await fetch(HYGRAPH_URL, options)).json();
Axios
Axios is a more mature HTTP client with more capabilities than fetch. If your web app already uses the axios library, you can retrieve data from a GraphQL server, as shown below.
import axios from 'axios';import { HYGRAPH_URL, HYGRAPH_PERMANENTAUTH_TOKEN } from '../lib/constants';// Prepare the requestconst headers = {'content-type': 'application/json','Authorization': `Bearer ${HYGRAPH_PERMANENTAUTH_TOKEN}`};const requestBody = {query: `query getUserByEmail($email:String!){nextUser(where:{email:$email}){firstname}}`,variables: { email }};const options = {method: 'POST',url: HYGRAPH_URL,headers,data: requestBody};// use axios to make your api callconst response = await axios(options);
GraphQL Request
Another easy-to-use and lightweight GraphQL client dedicated to making GraphQL requests compared to generic HTTP clients like axios and fetch is graphql-request. It can be considered in small to medium-scale applications where you need a dedicated GraphQL client to fetch the data. It also comes with Typescript support. Here’s how to use it.
import { HYGRAPH_URL, HYGRAPH_PERMANENTAUTH_TOKEN } from '../lib/constants';import { GraphQLClient, gql } from 'graphql-request';const client = new GraphQLClient(HYGRAPH_URL, {headers: {Authorization: `Bearer ${HYGRAPH_PERMANENTAUTH_TOKEN}`,},});const query = gql`query getUserByEmail($email:String!){nextUser(where:{email:$email}){firstname}}`;export default function MyComponent() {const [email, setEmail] = useState('');const getUserDetail = async () => {const variables = { email };const response = await client.request(query, variables);console.log('RESPONSE FROM GRAPHQL-REQUEST API CALL', response);};return (// JSX template with onClick event that calls → getUserDetail ...);}
Apollo Client
Apollo Client is a robust, battle-tested, mature client for GraphQL on the web that comes with a wide range of features for client-side data fetching. It is the most popular GraphQL client and has support for major frontend frameworks. It enables us to use powerful features like polling & re-fetching data, simplifies managing and configuring client-side cache, helps to use GraphQL fragments, and also supports subscriptions. If you are building a full-blown enterprise application that relies heavily on GraphQL, you might want to consider the Apollo Client.
Since Next.js is a popular production framework, we will discuss how to configure Apollo Client in Next.js. First, let's create a file to initialize and export our Apollo Client.
lib/apolloClient.js
import { ApolloClient, createHttpLink, InMemoryCache } from '@apollo/client';import { HYGRAPH_URL, HYGRAPH_PERMANENTAUTH_TOKEN } from '../lib/constants';import { setContext } from '@apollo/client/link/context';const httpLink = createHttpLink({uri: HYGRAPH_URL,});const authLink = setContext((_, { headers }) => {return {headers: {...headers,authorization: `Bearer ${HYGRAPH_PERMANENTAUTH_TOKEN}`}};});const client = new ApolloClient({link: authLink.concat(httpLink),cache: new InMemoryCache()});export default client;
Now we can import this client in our _app.js
and use ApolloProvider
to provide this client to all our components.
_app.js
import { ApolloProvider } from '@apollo/client';import client from '../lib/apolloClient';export default function MyApp({ Component, pageProps }) {return (<Layout><ApolloProvider client={client}><Component {...pageProps} /></ApolloProvider></Layout>);}
Finally, inside our components, we can use hooks provided by the Apollo Client to make the GraphQL API request.
import { React, useState } from 'react';import { UserDetail } from '../components/UserDetail';import { gql, useLazyQuery } from '@apollo/client';const query = gql`query getUserByEmail($email:String!){nextUser(where:{email:$email}){firstname}}`;export default function MyComponent() {const [email, setEmail] = useState('');const [getUserDetail, { loading, error, data }] = useLazyQuery(query, { variables: { email } });if (error) return <div> Something Went Wrong! </div>;return (// JSX template with onClick event that calls → getUserDetail ...);}
We saw the example of integrating the Apollo Client in React. However, if your app uses something like Angular, Vue or Svelte, you can check out those Apollo libraries here
Hugo
Hugo is a static site generator written in Go. It is good for use cases like static websites and blogs. In Hugo, we can utilize the resources.GetRemote
function from the resources
package to make GraphQL API requests. This function enables us to fetch remote resource data from APIs and then generates a Resource object that can be used within Hugo templates.
First, let’s prepare the options for our request to the GraphQL API.
{{ $options := dict"method" "POST""headers" (dict "Content-Type" "application/graphql")"body" `{nextUsers {firstname}}`}}
Now we can use the GetRemote
function by providing the HyGraph URL and the options we prepared above and use them inside the Hugo template.
{{ with resources.GetRemote "HYGRAPH_URL" $options }}{{ with .Content }}{{ with transform.Unmarshal . }}{{ with .data.nextUsers }}{{ range . }}{{ .firstname}}{{ end }}{{ end }}{{ end }}{{ end }}{{ end }}
Jekyll
Similar to Hugo, Jekyll is a simple, static site generator built with Ruby. It's designed to create fast and easy-to-maintain websites and blogs using Markdown or HTML templates. For Jekyll, there is no official GraphQL client or plugin, but one known open-source plugin is jeql which can be used to fetch data from a GraphQL server, as shown below.
First, we need to add the gem to our Gemfile
gem 'jeql'
Now, we can add this plugin to the Jekyll config file.
_config.yml
plugins:- jeql
We have to run bundle install
to install the dependencies, then we can link GraphQL server via our jeql config.
_config.yml
jeql:hygraph:url: "HYGRAPH_URL"header:Authorization: "HYGRAPH_AUTH_TOKEN"
Now we need to create a directory named _graphql
, add a file named users.json,
and add our GraphQL query in there.
_graphql/users.json
{"query" : "query getNextUsers { nextUsers { firstname } }"}
Finally, we can retrieve data from Hygraph by opening the graphql
block tag and use it within the template files as shown below
<ul>{% graphql endpoint: "hygraph", query: "users" %}{% for user in data["nextUsers"] %}<li>{{user["firstname"]}}</li>{% endfor %}{% endgraphql %}</ul>
Recommended reading
#Mobile
Popular mobile development tech stacks include using Swift on iOS, React Native, Kotlin, and Flutter. For most of these technologies, Apollo has published a client-side library, which has received good stars on GitHub and developed into a strong community over time. Hence, we can consider using Apollo’s client-side GraphQL libraries.
Swift
Apollo iOS is an open-source GraphQL client built in Swift. It is one of the best choices for iOS GraphQL clients. It supports the execution of GraphQL operations and caching on the client side.
Depending on your project setup, you should install Apollo iOS and Codegen CLI.
Also, have the GraphQL schema in the graphql/schema.graphqls
file.
Now, add your GraphQL query in graphql/GetUser.graphql
query GetUser{nextUser(where:{id:1}){firstname}}
Use code generation to generate API code to help us execute GraphQL operations.
./apollo-ios-cli generate
Create the Apollo Client
import Foundationimport Apollolet apolloClient = ApolloClient(url: URL(string: "HYGRAPH_URL")!)
Use the GetUserQuery
class generated by Apollo iOS with the Apollo Client instance, as shown below.
apolloClient.fetch(query: GetUserByEmailQuery()) { result inguard let data = try? result.get().data else { return }print(data.nextUser.firstname)}
Flutter
The most popular GraphQL client in the Flutter community grahql-flutter. It provides support for basic GraphQL operations like executing queries, mutations, subscriptions, and some advanced features like polling and caching.
To integrate it inside our Flutter project, we must add dependencies for the graphql_flutter
package.
flutter pub add graphql_flutter
You can now create the GraphQL client and provide it to your widgets as shown below:
// Import the package and initialise the graphql clientimport 'package:graphql_flutter/graphql_flutter.dart';void main () {// Create the link for connectionfinal HttpLink httpLink = HttpLink(HYGRAPH_URL);final AuthLink authLink = AuthLink(getToken: () => 'Bearer HYGRAPH_PERMANENTAUTH_TOKEN',);final Link link = authLink.concat(httpLink);// Initialise the GraphQL ClientValueNotifier<GraphQLClient> client = ValueNotifier(GraphQLClient(link: link,cache: GraphQLCache(store: InMemoryStore()),),);// Wrap the GraphQLclient in your App's root widgetfinal app = GraphQLProvider(client: client,child: MyApp(),);runApp(App);}
Our query to fetch user data:
final String getUserQuery = r'''query GetUser($email: String!) {nextUser(where: { email: $email }) {firstname}}''';
And use it like this in your widgets:
Query(options: QueryOptions(document: gql(getUserQuery),variables: {'email': 'johndoe@hygraph.com',},),builder: (QueryResult result, {VoidCallback refetch, FetchMore fetchMore}) {final data = result.data['nextUser'];return Scaffold(appBar: AppBar(title: Text('User Information'),),body: Center(child: Text('First name: ${data['firstname']}'),),);},)
React Native
We can integrate GraphQL clients in React Native the same way we do in React.js. For instance, if we want to use Apollo Client in React Native, we can use the same docs as Apollo Client for React.
Kotlin
Apollo Kotlin (previously known as Apollo Android) is a GraphQL client that can generate Kotlin and Java models from GraphQL queries and can be used to communicate with a GraphQL server.
Add the plugin to your build.gradle.kts
plugins {id("com.apollographql.apollo3") version "3.8.2"}
Add the runtime dependency:
dependencies {implementation("com.apollographql.apollo3:apollo-runtime:3.8.2")}
Set the package name to use for the generated models:
apollo {service("service") {packageName.set("com.example")}}
Make sure you have the GraphQL schema copied in your module’s src/main/graphql
directory.
After this you can write your graphql queries in ${module}/src/main/graphql/GetRepository.graphql
query GetUserByEmail($email:String!){nextUser(where:{email:$email}){firstname}}
After building our project, we will be able to use a GetUserByEmail
class with an instance of ApolloClient
as shown below.
// Initialise Apollo clientval apolloClient = ApolloClient.Builder().serverUrl(HYGRAPH_URL).build()// Execute the GraphQL Queryval response = apolloClient.query(GetUserByEmail(email="johndoe@hygraph.com")).execute()// Use the response as required
#What’s next
This article reviewed ways to consume data from GraphQL servers when developing web and mobile applications. GraphQL developers prefer to work with the mentioned frontend technologies according to the GraphQL Report 2024.
The GraphQL Report compiles best practices from prominent GraphQL power users and expertise from GraphQL experts. Take a look at the report for more in-depth insights on GraphQL.
The GraphQL Report 2024
Statistics and best practices from prominent GraphQL users.
Check out the report