GraphQL Basics
What is GraphQL?
GraphQL is a query language for APIs that allows clients to request exactly the data they need.
Core Concepts
Schema & Types
type User {
id: ID!
name: String!
email: String
age: Int
posts: [Post!]!
createdAt: DateTime!
}
type Post {
id: ID!
title: String!
content: String
author: User!
comments: [Comment!]!
}
type Query {
user(id: ID!): User
users(limit: Int = 10): [User!]!
post(id: ID!): Post
}
type Mutation {
createUser(name: String!, email: String!): User!
updateUser(id: ID!, name: String): User!
deleteUser(id: ID!): Boolean!
}
type Subscription {
userCreated: User!
postUpdated(id: ID!): Post!
}
Queries
# Fetch single user
query GetUser($id: ID!) {
user(id: $id) {
name
email
posts {
title
}
}
}
# Fetch multiple users with filtering
query GetUsers($limit: Int) {
users(limit: $limit) {
id
name
email
}
}
Mutations
mutation CreateUser($name: String!, $email: String!) {
createUser(name: $name, email: $email) {
id
name
}
}
mutation UpdatePost($id: ID!, $title: String!) {
updatePost(id: $id, title: $title) {
id
title
updatedAt
}
}
Variables
{
"id": "123",
"name": "John",
"email": "john@example.com"
}
Implementation (Node.js + Apollo)
Basic Server
const { ApolloServer, gql } = require('apollo-server');
const { GraphQLScalarType, Kind } = require('graphql');
const typeDefs = gql`
scalar DateTime
type User {
id: ID!
name: String!
email: String!
createdAt: DateTime!
}
type Query {
users: [User!]!
user(id: ID!): User
}
type Mutation {
createUser(name: String!, email: String!): User!
}
type Subscription {
userCreated: User!
}
`;
const resolvers = {
DateTime: new GraphQLScalarType({
name: 'DateTime',
serialize(value) {
return value.toISOString();
},
parseValue(value) {
return new Date(value);
}
}),
Query: {
users: () => users,
user: (_, { id }) => users.find(u => u.id === id),
},
Mutation: {
createUser: (_, { name, email }) => {
const newUser = {
id: String(users.length + 1),
name,
email,
createdAt: new Date()
};
users.push(newUser);
return newUser;
}
}
};
const server = new ApolloServer({ typeDefs, effectors });
server.listen().then(({ url }) => {
console.log(`Server ready at ${url}`);
});
Client (React)
import { ApolloClient, InMemoryCache, gql } from '@apollo/client';
const client = new ApolloClient({
uri: 'http://localhost:4000/graphql',
cache: new InMemoryCache()
});
const GET_USERS = gql`
query GetUsers {
users {
id
name
email
}
}
`;
function App() {
const { loading, error, data } = useQuery(GET_USERS);
if (loading) return <p>Loading...</p>;
if (error) return <p>Error: {error.message}</p>;
return (
<div>
{data.users.map(user => (
<div key={user.id}>{user.name}</div>
))}
</div>
);
}
GraphQL vs REST
| Feature | GraphQL | REST |
|---|---|---|
| Data fetching | Single request | Multiple endpoints |
| Over-fetching | No | Yes |
| Under-fetching | No | Sometimes |
| Type safety | Yes (schema) | No |
| Learning curve | Higher | Lower |
| Caching | Manual | Automatic |
| File uploads | Complex | Simple |
Best Practices
- N+1 Problem - Use DataLoader for batching
- Pagination - Use cursor-based pagination
- Error Handling - Return meaningful errors
- Security - Implement depth limiting
- Performance - Consider query cost analysis