- GraphQL is a query language and a server-side runtime (typically served over HTTP).
- Unlike most query languages (such as SQL), you don’t use GraphQL to query a particular type of data store.
- Instead, you use GraphQL to query data from various sources.
- GraphQL requests are presented in two types of operations: queries and mutations.
- Queries that fetch data are synonymous to
GET
calls in REST.
- Mutations invoke a change in the system, similar to REST’s
POST
, PUT
, or DELETE
methods.
Runtime
- In a GraphQL API, we shape our data within a strictly typed schema, telling it how to resolve data when requested.
- GraphQL is data source agnostic, so where data comes from doesn’t matter.
- It could be from a database, micro-service, or an underlying RESTful API.
- GraphQL is typically served over HTTP.
- This means operations are just plain old strings, and we don’t need a unique tool to query data from a GraphQL server.
- We create a GraphQL schema on the server based on the data we need to build our app UIs.
- We write the resolver functions for each type, connecting the data to our graph.
Key features of GraphQL
Performance
- Prevents over-fetching: In traditional approaches like REST, you often over-fetching — asking for more data than needed.
- With GraphQL, you can ask for exactly what you need.
- The benefit is reduced bandwidth, which may be especially important on mobile and low-energy devices.
- Prevents under-fetching (multiple roundtrips):
- REST's other end of the fetching problem is not getting all the data you need in a single round-trip.
- Consider fetching your friends list in a social media app and needing to batch individual queries to get each friend’s profile picture.
Developer experience
- Hierarchical & declarative: GraphQL data is inherently graphical and declarative.
- This makes your queries easier to understand and your data more accessible to work with.
- By nesting, we can ask for related data, keep queries cohesive, and spend zero time stitching together multiple responses.
- Strongly typed (stable API): GraphQL is strongly typed.
- This means a more stable API with fewer bugs in development and introduces the possibility of more intelligent tooling.
- Versioning: GraphQL favors the notion of a single, incrementally developed graph.
- You can give deprecation hints when adding, removing, and changing fields on your graph.
- Compare this to the coarse-grained approach to versioning in a REST context with version numbers across an entire API.
Architecture
- Decouples the client from the server:
- UI developers don’t need to wait for backend teams to build an API first.
- A GraphQL schema acts as a contract for front-end engineers to start building (by mocking out the API calls) and leaves backend teams to deliver on the contract by building the underlying services that serve the graph.