GraphQL Introduction
GraphQL is a query language for your API, and a server-side runtime for executing those queries. It's an alternative to REST that gives clients the power to ask for exactly what they need.
Unlike REST where the server decides what data to send, GraphQL puts the client in control. The client specifies what fields it wants, and the server responds with just those fields.
How GraphQL Works
GraphQL operates on a simple principle: you send a query string to the server, and the server sends back a JSON response that matches the shape of your query.
Here's the flow:
1. Client sends a query describing what data it needs
2. Server validates the query against the schema
3. Server executes resolvers to fetch the data
4. Server returns exactly the data requested
// Client query
query {
product(id: "123") {
name
price
inStock
}
}
// Server response
{
"data": {
"product": {
"name": "Wireless Headphones",
"price": 99.99,
"inStock": true
}
}
}
Key Terminology
Let's get familiar with the terms you'll hear a lot in GraphQL:
Schema: The definition of your data types and the operations available on them.
Type: A category of data, like User, Product, or Post.
Field: A piece of data within a type, like name or email on a User.
Query: A request to read data from the API.
Mutation: A request to modify data on the server.
Subscription: A way to get real-time updates when data changes.
Resolver: A function that fetches the data for a field.
A Simple Example
Let's build a mental model with a real example. Imagine you're building a blog. You have users, posts, and comments.
const typeDefs = `
type User {
id: ID!
name: String!
email: String!
posts: [Post!]!
}
type Post {
id: ID!
title: String!
content: String!
author: User!
comments: [Comment!]!
}
type Comment {
id: ID!
text: String!
author: User!
}
type Query {
user(id: ID!): User
post(id: ID!): Post
}
`;
This schema tells us exactly what data is available and how types relate to each other. A User has posts, a Post has an author and comments, and so on.
GraphQL is Not a Database
A common misconception is that GraphQL is a database technology. It's not. GraphQL is an API specification that can sit on top of any data source - databases, REST APIs, microservices, or even static files.
You could use GraphQL with MongoDB, PostgreSQL, MySQL, or even combine data from multiple sources in a single query. The schema acts as a unified interface to all your data.