GraphQL and Apollo Server for Beginners: A Practical Guide
Tags: graphql, apollo, react
Published: 2023-01-07 10:51:11

### Introduction

In this article, I will be sharing my work on GraphQL and Apollo Server. Let’s start with a brief overview of these technologies before moving on to an example project.

## What is GraphQL?

GraphQL is a query language and runtime for making API calls that allow clients to request exactly the data they need, and nothing more. It is an alternative to REST APIs, which often return more data than is necessary and require multiple requests to retrieve all the data needed for a particular application. With GraphQL, the client specifies the exact data it needs in a query, and the server responds with the requested data in a single request. This allows the client to retrieve exactly the data it needs in a more efficient manner. GraphQL is also a data modeling language, used to define the shape and structure of the data returned by an API.

- Improved developer experience: GraphQL allows developers to get the exact data they need, rather than having to work with a fixed set of data returned by a REST API. This can make it easier for developers to build and maintain applications that rely on API data.
- Better API design: Because GraphQL enables clients to request specific data, APIs can be designed to provide more granular data, rather than returning a fixed set of data. This can lead to more flexible and maintainable APIs.
- Increased performance: By allowing clients to request only the data they need, GraphQL can help reduce the amount of data transferred over the network, which can improve the performance of applications.
- Strong ecosystem: There are many tools and libraries available for working with GraphQL, including libraries for building GraphQL servers and clients in different languages, and tools for visualizing and testing GraphQL APIs.
Improved API documentation: GraphQL APIs often include detailed documentation for each field and type, making it easier for developers to understand and use the API.

## What is Apollo Server?

Apollo Server is a JavaScript library for building GraphQL servers. It provides a simple and flexible way to create a GraphQL API that allows clients to request exactly the data they need. Apollo Server integrates with various data sources, such as databases and REST APIs, and supports various caching strategies to optimize performance.

- Comprehensive feature set: Apollo Server includes a range of features for building GraphQL servers, such as support for middleware, subscriptions, and batching.
Integration with popular libraries: Apollo Server integrates with popular libraries such as Express, Fastify, and Koa, making it easy to use with existing Node.js servers.
- Flexible data sources: Apollo Server can be used with a variety of data sources, including databases, REST APIs, and in-memory data stores.
- Strong ecosystem: Apollo Server is part of the Apollo ecosystem, which includes a range of tools and libraries for working with GraphQL, including a client library for making GraphQL requests from the client side.
- Community support: Apollo Server has a strong and active community, with regular updates and a wealth of resources and documentation available.
- Good performance: Apollo Server includes features such as batching and caching that can help improve the performance of GraphQL APIs.

### An Example Project with GraphQL and Apollo Server

`npm install react-apollo apollo-server
`
#### Client

```js
// index.js

import React from 'react'
import ReactDOM from 'react-dom/client'
import App from './App'
import './index.css'
import { ApolloProvider, ApolloClient, InMemoryCache } from '@apollo/client'

const client = new ApolloClient({
  uri: 'http://localhost:4000',
  cache: new InMemoryCache(),
})

const root = ReactDOM.createRoot(document.getElementById('root'))
root.render(
  <React.StrictMode>
    <ApolloProvider client={client}>
      <App />
    </ApolloProvider>
  </React.StrictMode>
)
```

```js
// App.js

import { useEffect, useState } from 'react'
import { gql, useQuery } from '@apollo/client'

const NOTES = gql`
  query getNotes {
    notes {
      id
      description
      title
      author {
        age
        id
        name
        photo
      }
    }
  }
`
function App() {
  const [notes, setNotes] = useState([])

  const { loading, error, data } = useQuery(NOTES)

  useEffect(() => {
    if (data) {
      setNotes(data.notes)
    }
  }, [data])

  if (loading) return 'loading'

  if (error) return `Error: ${error.message}`

  return (
    <div className=' grid gap-4 grid-cols-2  p-4'>
      {notes.map((note) => (
        <div key={note.id} className='border rounded p-4'>
          <h1> {note.title} </h1>
          <p> {note.description} </p>
          <div className='flex justify-start items-center gap-2 mt-1'>
            <img
              className='w-8 rounded-full'
              src={note.author.photo}
              alt={note.author.name}
            />
            <small>
              {' '}
              {note.author.name} • {note.author.age}{' '}
            </small>
          </div>
        </div>
      ))}
    </div>
  )
}

export default App
```

#### Server

```js
// index.js

import { ApolloServer } from '@apollo/server'
import { startStandaloneServer } from '@apollo/server/standalone'

const typeDefs = `#graphql
type Author {
  id: ID!
  name: String!
  age: Int!
  photo: String
}

type Note {
  id: ID!
  title: String!
  description: String!
  author: Author!
}

type Query  {
  notes: [Note!]!
}
`

const notes = [
  {
    id: 1,
    description: 'ilk yazım',
    title: 'Merhaba Dünya',
    author: {
      age: 22,
      id: 1,
      name: 'ozan',
      photo:
        'https://pbs.twimg.com/profile_images/1596070555811209218/1tibqnOR_400x400.jpg',
    },
  },
  {
    id: 2,
    description: 'ikinci yazım',
    title: 'Merhaba Dünya Bu ikinci Yazım',
    author: {
      age: 22,
      id: 2,
      name: 'nida',
      photo:
        'https://pbs.twimg.com/profile_images/1599711099439423488/8fVlSri1_400x400.jpg',
    },
  },
]

const resolvers = {
  Query: {
    notes: () => notes,
  },
}

const server = new ApolloServer({
  typeDefs,
  resolvers,
})

const { url } = await startStandaloneServer(server, { listen: { port: 4000 } })

console.log(`🚀 Server listening at: ${url}`)
```


![live demo](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/moz6y28x4z6mswoioi8n.png)

{% embed https://github.com/ozantekin/graphql %}

🔗 Learn more about me [here](https://www.ozantekin.dev/links).