Chapter 1: Introduction & Setup
Welcome to the GraphQL Yoga Book — a practical guide for building scalable and modular GraphQL APIs with GraphQL Yoga.
What is GraphQL Yoga?
GraphQL Yoga is a fully-featured GraphQL Server with focus on easy setup, performance and great developer experience. It's built on top of the following libraries:
- GraphQL.js - The reference implementation of GraphQL
- Envelop - A plugin system for GraphQL
- GraphQL Tools - A set of utilities for building GraphQL APIs
Key Features
- 🔥 Performance: Built on top of the fastest HTTP servers
- 🎯 TypeScript Support: First-class TypeScript support
- 🔌 Plugin System: Extensible through Envelop plugins
- 📦 Zero Dependencies: No external dependencies required
- 🛠 Developer Experience: Great error messages and debugging tools
Setting Up Your First GraphQL Server
Let's create a new project and set up a minimal GraphQL server:
- First, create a new directory and initialize a new Node.js project:
mkdir graphql-server
cd graphql-server
npm init -y
- Install the required dependencies:
npm install @graphql-yoga/node graphql
- Create a new file called
index.js(orindex.tsfor TypeScript) with the following content:
import { createYoga } from '@graphql-yoga/node'
import { createServer } from 'node:http'
// Define your schema
const typeDefs = `
type Query {
hello: String
}
`
// Define your resolvers
const resolvers = {
Query: {
hello: () => 'Hello from GraphQL!'
}
}
// Create your GraphQL server
const yoga = createYoga({
schema: {
typeDefs,
resolvers
}
})
// Start the server
const server = createServer(yoga)
server.listen(4000, () => {
console.log('Server is running on http://localhost:4000/graphql')
})
- Add a start script to your
package.json:
{
"scripts": {
"start": "node index.js"
}
}
- Run your server:
npm start
Testing Your Server
Once your server is running, you can test it by:
- Opening http://localhost:4000/graphql in your browser
- Using the GraphQL Playground to run queries
- Try this simple query:
query {
hello
}
You should see the response:
{
"data": {
"hello": "Hello from GraphQL!"
}
}
Next Steps
In the next chapter, we'll dive deeper into GraphQL core concepts and learn how to design more complex schemas. We'll explore:
- Types and Fields
- Queries and Mutations
- Input Types
- Enums and Scalars
- And much more!
Summary
In this chapter, we've:
- Learned about GraphQL Yoga and its features
- Set up a basic GraphQL server
- Created a simple schema with a hello query
- Tested our server using the GraphQL Playground
This foundation will help us build more complex GraphQL APIs in the upcoming chapters.