Back to Backend & APIs

Module 4: GraphQL APIs

Build flexible, efficient APIs with GraphQL and Apollo Server.

What is GraphQL?

GraphQL is a query language for APIs developed by Facebook. Unlike REST where you get fixed data structures, GraphQL lets clients request exactly what they need. Think of it as ordering à la carte instead of getting a fixed menu.

🚀 GraphQL vs REST:

  • Single Endpoint: One URL for all operations
  • No Over-fetching: Get exactly what you request
  • No Under-fetching: Get related data in one request
  • Strongly Typed: Schema defines all possible data
  • Self-Documenting: Schema is the documentation
  • Real-time: Built-in subscriptions support

GraphQL Schema

Type Definitions:

# Scalar types

type User {

id: ID!

name: String!

email: String!

age: Int

isActive: Boolean!

createdAt: String!

}

# Relationships

type Post {

id: ID!

title: String!

content: String!

author: User!

comments: [Comment!]!

}

type Comment {

id: ID!

text: String!

author: User!

post: Post!

}

# Query type (read operations)

type Query {

users: [User!]!

user(id: ID!): User

posts(limit: Int): [Post!]!

post(id: ID!): Post

}

# Mutation type (write operations)

type Mutation {

createUser(name: String!, email: String!): User!

updateUser(id: ID!, name: String, email: String): User!

deleteUser(id: ID!): Boolean!

createPost(title: String!, content: String!, authorId: ID!): Post!

}

# Subscription type (real-time)

type Subscription {

userCreated: User!

postAdded: Post!

}

Queries

Query Examples:

# Get all users

query {

users {

id

name

email

}

}

# Get specific user with posts

query {

user(id: "123") {

name

email

posts {

title

content

comments {

text

author {

name

}

}

}

}

}

# Query with variables

query GetUser($userId: ID!) {

user(id: $userId) {

name

email

}

}

# Variables

{ "userId": "123" }

Mutations

# Create user

mutation {

createUser(name: "Alice", email: "alice@example.com") {

id

name

email

}

}

# Update user

mutation {

updateUser(id: "123", name: "Alice Updated") {

id

name

}

}

# Delete user

mutation {

deleteUser(id: "123")

}

Apollo Server Setup

Complete Example:

# Install dependencies

npm install apollo-server graphql

// server.js

const { ApolloServer, gql } = require('apollo-server');

// Type definitions

const typeDefs = gql`

type User {

id: ID!

name: String!

email: String!

}

type Query {

users: [User!]!

user(id: ID!): User

}

type Mutation {

createUser(name: String!, email: String!): User!

deleteUser(id: ID!): Boolean!

}

`;

// Mock database

let users = [

{ id: '1', name: 'Alice', email: 'alice@example.com' },

{ id: '2', name: 'Bob', email: 'bob@example.com' }

];

let nextId = 3;

// Resolvers

const resolvers = {

Query: {

users: () => users,

user: (parent, args) => users.find(u => u.id =>= args.id)

},

Mutation: {

createUser: (parent, args) => {

const newUser = {

id: String(nextId++),

name: args.name,

email: args.email

};

users.push(newUser);

return newUser;

},

deleteUser: (parent, args) => {

users = users.filter(u => u.id !=> args.id);

return true;

}

}

};

// Create server

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

server.listen().then(({ url }) => {

console.log(`Server ready at ${url} `);

});

📚 Module Summary

You've mastered GraphQL:

  • ✓ GraphQL schema and type system
  • ✓ Queries and mutations
  • ✓ Resolvers and data fetching
  • ✓ Apollo Server setup
  • ✓ GraphQL vs REST comparison

Next: Learn authentication and security!