JavaScript Essentials - GraphQL
Using GraphQL with JavaScript
GraphQL is a query language for APIs and a runtime for executing those queries by using a type system you define for your data. This tutorial covers how to use GraphQL with JavaScript to create and consume APIs efficiently.
Key Points:
- GraphQL allows clients to request exactly the data they need.
- It enables more efficient and flexible data fetching compared to REST.
- GraphQL uses a schema to define the structure of the API, providing a strong type system.
Setting Up a GraphQL Server
To get started with GraphQL, you need to set up a server. We'll use Apollo Server, a popular GraphQL server for JavaScript.
// Install Apollo Server and GraphQL
npm install apollo-server graphql
// Create a basic GraphQL server
// server.js
const { ApolloServer, gql } = require('apollo-server');
// Define the schema
const typeDefs = gql`
type Query {
hello: String
}
`;
// Define the resolvers
const resolvers = {
Query: {
hello: () => 'Hello, world!'
}
};
// Create the Apollo Server
const server = new ApolloServer({ typeDefs, resolvers });
// Start the server
server.listen().then(({ url }) => {
console.log(`Server ready at ${url}`);
});
Run the server:
// Run the server
node server.js
Creating a GraphQL Schema
The GraphQL schema defines the structure of the API. It includes types, queries, and mutations. Here, we extend the schema with additional types and queries.
// Extend the schema
const typeDefs = gql`
type Book {
title: String
author: String
}
type Query {
books: [Book]
}
`;
// Sample data
const books = [
{ title: 'The Awakening', author: 'Kate Chopin' },
{ title: 'City of Glass', author: 'Paul Auster' }
];
// Define the resolvers
const resolvers = {
Query: {
books: () => books
}
};
Querying a GraphQL API
To query a GraphQL API, you use a query language to specify the data you need. This is typically done with a client like Apollo Client or directly with fetch or axios.
// Example query
const query = `
query {
books {
title
author
}
}
`;
// Using fetch to query the GraphQL API
fetch('http://localhost:4000/', {
method: 'POST',
headers: {
'Content-Type': 'application/json'
},
body: JSON.stringify({ query })
})
.then(res => res.json())
.then(res => console.log(res.data));
Using Apollo Client
Apollo Client is a comprehensive state management library for JavaScript that enables you to manage both local and remote data with GraphQL.
// Install Apollo Client
npm install @apollo/client graphql
// Set up Apollo Client
// client.js
import { ApolloClient, InMemoryCache, gql } from '@apollo/client';
const client = new ApolloClient({
uri: 'http://localhost:4000/',
cache: new InMemoryCache()
});
// Example query using Apollo Client
client
.query({
query: gql`
query {
books {
title
author
}
}
`
})
.then(result => console.log(result.data));
GraphQL Mutations
Mutations in GraphQL are used to modify data on the server. Here is an example of defining and executing a mutation to add a new book.
// Extend the schema with a mutation
const typeDefs = gql`
type Book {
title: String
author: String
}
type Query {
books: [Book]
}
type Mutation {
addBook(title: String, author: String): Book
}
`;
// Define the resolvers
const resolvers = {
Query: {
books: () => books
},
Mutation: {
addBook: (_, { title, author }) => {
const newBook = { title, author };
books.push(newBook);
return newBook;
}
}
};
// Example mutation
const mutation = `
mutation {
addBook(title: "New Book", author: "John Doe") {
title
author
}
}
`;
// Using fetch to execute the mutation
fetch('http://localhost:4000/', {
method: 'POST',
headers: {
'Content-Type': 'application/json'
},
body: JSON.stringify({ query: mutation })
})
.then(res => res.json())
.then(res => console.log(res.data));
Summary
In this tutorial, you learned how to use GraphQL with JavaScript to create and consume APIs. GraphQL allows clients to request exactly the data they need and provides a flexible and efficient way to handle data fetching. You also learned how to set up a GraphQL server with Apollo Server, create a schema, query data, and perform mutations.