What is GraphQL?
GraphQL is a query language for your API and a server-side runtime for executing those queries by using a type system you define for your data. It was developed by Facebook and is now open-source. Unlike REST APIs, which have multiple endpoints that return fixed data structures, a GraphQL API has a single endpoint that can return precisely the data a client asks for.
GraphQL vs. REST
- Data Fetching: With REST, you might need to make multiple requests to different endpoints to gather all the data for a single view (e.g.,
/users/1
and/users/1/posts
). With GraphQL, you can get all the data you need in a single request. - Over-fetching and Under-fetching: REST APIs often return more data than you need (over-fetching) or not enough (under-fetching). GraphQL solves this by allowing the client to specify exactly what data it needs.
- Strongly Typed Schema: GraphQL APIs are built on a strongly typed schema. This schema serves as a contract between the client and the server, making it easier to evolve your API without breaking existing clients.
Core Concepts of GraphQL
Schema Definition Language (SDL)
The GraphQL schema is at the center of any GraphQL API. It defines the types of data that can be queried. Here’s a simple example of a schema:
type Query {
hello: String
user(id: ID!): User
}
type User {
id: ID!
name: String
email: String
posts: [Post]
}
type Post {
id: ID!
title: String
content: String
}
This schema defines a Query
type with two fields: hello
and user
. It also defines User
and Post
types with their respective fields. The !
indicates that a field is non-nullable.
Queries
Queries are used to fetch data from the server. The structure of the query matches the shape of the data you want to receive.
query GetUserWithPosts {
user(id: "1") {
id
name
posts {
title
}
}
}
This query would return a JSON object with the id
, name
, and a list of posts
(with just the title
) for the user with an id
of "1".
Mutations
Mutations are used to modify data on the server. They are similar to POST
, PUT
, or DELETE
requests in REST.
mutation CreatePost {
createPost(title: "New Post", content: "This is the content.") {
id
title
}
}
This mutation would create a new post and return its id
and title
.
Subscriptions
Subscriptions are a way to maintain a real-time connection to the server, allowing it to push data to the client when specific events occur. This is useful for applications like chat apps or live notifications.
subscription NewPostSubscription {
newPost {
id
title
}
}
Building a Simple GraphQL Server with Apollo Server
Apollo Server is a popular library for building GraphQL servers in Node.js.
-
Installation:
npm install @apollo/server graphql
-
Creating the Server: Here's a basic example of a GraphQL server using Apollo Server:
import { ApolloServer } from '@apollo/server'; import { startStandaloneServer } from '@apollo/server/standalone'; // 1. Define your schema const typeDefs = `#graphql type Query { hello: String } `; // 2. Define your resolvers const resolvers = { Query: { hello: () => 'Hello, GraphQL!', }, }; // 3. Create an instance of ApolloServer const server = new ApolloServer({ typeDefs, resolvers, }); // 4. Start the server const { url } = await startStandaloneServer(server, { listen: { port: 4000 }, }); console.log(`🚀 Server ready at: ${url}`);
This sets up a server with a single hello
query. When you run this code, you'll have a GraphQL API running on port 4000, which you can explore using the Apollo Studio Sandbox in your browser.
GraphQL offers a powerful and flexible way to build APIs, giving clients more control over the data they fetch and enabling more efficient and performant applications.