Node.js › GraphQL
What is GraphQL, and how does it differ from a traditional REST API in terms of how clients request data?
BeginnerAnswer
GraphQL is a query language and runtime for APIs where the client specifies exactly which fields it needs in a single request, and the server returns precisely that shape of data -- unlike REST, where each endpoint returns a fixed data shape (often requiring multiple requests to different endpoints to gather related data, or over-fetching unnecessary fields from a single endpoint), GraphQL exposes a single endpoint with a strongly-typed schema, letting clients compose exactly the query they need.
# GraphQL query: client specifies exactly the fields it wants
query {
user(id: "123") {
name
email
orders { id total }
}
}
# A single request returns exactly this nested shape, no more, no lessReal-world example A mobile app with limited bandwidth switches a screen from three separate REST API calls (user profile, orders, and preferences) to a single GraphQL query requesting exactly the fields needed for that screen, reducing both the number of round trips and the amount of unused data transferred.