An Introduction to GraphQL: Simplifying Data Fetching With Real-World Examples
Understanding the basics of GraphQL: How to define schemas, set up a server, and integrate with front-end applications for efficient data management.
Join the DZone community and get the full member experience.
Join For FreeWhat Is GraphQL?
GraphQL is a query language for your APIs, as well as a runtime for fulfilling those queries with your existing data. In simple words, you describe your data using a schema; you ask for only what you want, and in turn, you get predictable results. By leveraging this technology, it empowers the client to request precisely what they require, according to the defined schema and query. People widely use GraphQL as an alternative to the REST API architecture due to its growing popularity.
Key Features of GraphQL
- Strongly typed schema: GraphQL employs a schema to specify the categories of data that are queryable. This schema functions as a contractual agreement between the client and server, guaranteeing a clear understanding of the requested data and its expected return.
- Single endpoint: GraphQL APIs use a single endpoint for all queries and mutations, unlike REST APIs.
- Hierarchical: GraphQL client queries are similar to the JSON data returned by the API, making it simple and intuitive while making the network API call and understanding complex data structures.
- Client-specified queries: Web or mobile clients have the leverage to specify exactly what they need in terms of data, which reduces the amount of data transferred over the network and improves the overall application performance.
- Real-time capabilities: With GraphQL subscriptions, clients can receive real-time updates to data.
A Simple Example of GraphQL
Here is a simple example to demonstrate how GraphQL works. Suppose we have a simple GraphQL server that manages information about books and authors.
Step 1: Define the Schema
We start by defining our GraphQL API's schema. The schema specifies the possible data structures and query types.
# Author types
type Author {
id: ID!
name: String!
books: [Book!]!
}
# Book types
type Book {
id: ID!
title: String!
author: Author!
}
# Define the queries
type Query {
authors: [Author!]!
books: [Book!]!
book(id: ID!): Book
author(id: ID!): Author
}
Step 2: Set up the Server
We then configured a basic GraphQL server. Here's an example of how to use the express-graphql
library with the Express framework with Node.js:
const express = require('express');
const { graphqlHTTP } = require('express-graphql');
const { buildSchema } = require('graphql');
// Sample data
const authors = [
{ id: '1', name: 'John Doe' },
{ id: '2', name: 'Jenne Doe' },
];
const books = [
{ id: '1', title: 'Book 1', authorId: '1' },
{ id: '2', title: 'Book 2', authorId: '2' },
];
// Build GraphQL schema
const schema = buildSchema(`
type Author {
id: ID!
name: String!
books: [Book!]!
}
type Book {
id: ID!
title: String!
author: Author!
}
type Query {
authors: [Author!]!
books: [Book!]!
book(id: ID!): Book
author(id: ID!): Author
}
`);
// Create a Root resolver
const root = {
authors: () => authors,
books: () => books,
book: ({ id }) => books.find(book => book.id === id),
author: ({ id }) => authors.find(author => author.id === id),
};
// Instantiate the Express for setting up the GraphQL endpoint below
const app = express();
app.use('/graphql', graphqlHTTP({
schema: schema,
rootValue: root,
graphiql: true,
}));
// Start the server
app.listen(4000, () => console.log('Server running on http://localhost:4000/graphql'));
Step 3: Querying the Data
With the server running, you can query the data using GraphQL. Here are a couple of example queries:
Fetch All Authors and Their Books
{
authors {
id
name
books {
id
title
}
}
}
Fetch a Specific Book by ID
{
book(id: "1") {
title
author {
name
}
}
}
Integration With Front-End Applications
The client application uses Apollo Client, an interface library, to facilitate integration with Node.js GraphQL. You can use any frontend tech stack and integrate with the GraphQL backend to fetch predictive data from your backend application.
Below, I will be demonstrating how you can integrate the React-based application with the GraphQL server for processing the data.
Install Apollo Client
npm install @apollo/client graphql
Set up Apollo Client in Your React App
import React from 'react';
import ReactDOM from 'react-dom';
import { ApolloProvider, ApolloClient, InMemoryCache } from '@apollo/client';
import App from './App';
const client = new ApolloClient({
uri: 'http://localhost:4000/graphql',
cache: new InMemoryCache()
});
ReactDOM.render(
<ApolloProvider client={client}>
<App />
</ApolloProvider>,
document.getElementById('root')
);
Create a Query Component
import React from 'react';
import { useQuery, gql } from '@apollo/client';
const GET_AUTHORS = gql`
{
authors {
id
name
books {
id
title
}
}
}
`;
const Authors = () => {
const { loading, error, data } = useQuery(GET_AUTHORS);
if (loading) return <p>Loading...</p>;
if (error) return <p>Error :(</p>;
return (
<div>
{data.authors.map(author => (
<div key={author.id}>
<h3>{author.name}</h3>
<ul>
{author.books.map(book => (
<li key={book.id}>{book.title}</li>
))}
</ul>
</div>
))}
</div>
);
};
export default Authors;
Conclusion
Here we witnessed the power and flexibility that GraphQL brings to the table with on-demand fetching and predetermined query criteria. This also provides the ability to manage the mutations and even support the nested queries. This significantly enhances the application's overall performance. I would strongly recommend using GraphQL over the REST API architecture for better performance and flexibility, as well as to put an end to overfetching and underfetching of data in web applications.
Happy Coding!
Opinions expressed by DZone contributors are their own.
Comments