Back to Blog

How GraphQL Works

GraphQL: A New Approach to Data Fetching

GraphQL is a new API query language for fetching data. It provides an alternative to REST APIs by allowing clients to specify exactly what data they need. This results in faster and more efficient data fetching compared to REST.

## How GraphQL Works

GraphQL works by having a single endpoint that serves up data based on queries. Clients make GraphQL queries that specify the data they need, and the GraphQL server returns only that data.

For example, a simple GraphQL query may look like this:

```graphql
{
 user {
   firstName
   lastName
 }
}
```

This query will return data like:

```json
{
 "user": {
   "firstName": "John",
   "lastName": "Doe"
 }
}
```

Notice that the client only requested the `firstName` and `lastName` fields. The GraphQL server returned only those fields, and no extra data.

This is in contrast to REST APIs, where an endpoint typically returns all fields for a resource. With GraphQL, clients can be very specific about the data they need.

graphQL.jpg
Image credit bytebytego.com

Benefits of GraphQL

The main benefits of GraphQL compared to REST are:

1. Efficient Data Fetching

Since GraphQL clients can specify exactly what data they need, API calls return the minimal amount of data required. This results in:

- **Faster responses** - Less data needs to be transferred over the network
- **Lower bandwidth usage** - Reduces load on the server and network

2. Flexibility

GraphQL queries are flexible - clients can fetch data from multiple resources in a single request. This is difficult to achieve with REST.

3. Type Safety

GraphQL has a type system that defines the schema of the data. This makes the API self-documenting and catches errors early.

4. Caching


GraphQL queries can be cached more effectively since the exact data being fetched is known.

GraphQL Schema Definition

A GraphQL schema defines the types of objects and the fields on each object. It acts as a contract between client and server.

A simplified GraphQL schema may look like this:

```graphql
type User {
 id: ID!
 firstName: String!
 lastName: String
 email: String!
}

type Query {
 user(id: ID!): User
}
```

This defines:

- A `User` object type with fields `id`, `firstName`, `lastName` and `email`
- A `Query` type which has a `user` field that returns a `User`

The `!` after a type denotes a required field.

Clients make queries against this schema to fetch data from the GraphQL server.

## Using GraphQL with Next.js

Next.js supports GraphQL out of the box. You can define a GraphQL schema and use it to fetch data for pages.

For example, to fetch data for a `user` page:

```jsx
// pages/user.js

import { gql } from '@apollo/client';

const USER_QUERY = gql`
 query User($id: ID!) {
   user(id: $id) {
     id
     firstName
     lastName
   }
 }
`

export async function getStaticProps(context) {
 const { id } = context.params;

 // Fetch data from GraphQL API
 const { data } = await client.query({
   query: USER_QUERY,
   variables: { id }
 });

 return {
   props: {
     user: data.user
   }
 }
}

function User({ user }) {
 return (
   <div>
     <h1>{user.firstName} {user.lastName}</h1>
   </div>  
 )
}

export default User;
```

This allows you to fetch a specific `user`'s data based on their `id` and pass that data as props to the page component.

GraphQL provides a flexible and efficient approach to data fetching - especially for frontend frameworks like Next.js. The ability to specify exactly what data you need results in faster responses, lower bandwidth usage and an overall better user experience.