GraphQL: flexible query language for APIs

GraphQL (Open Source July 2015) by Facebook: query language for APIs, type system, single endpoint, client specifies what it needs. Apollo Server/Client, Relay, Hasura. Alternative to REST for multi-source data aggregation.

Open SourceWeb GraphQLFacebookMetaApolloRelayAPIOpen SourceWeb

REST’s limit

Typical REST APIs have two problems for mobile/SPA clients:

  • Over-fetching — endpoint returns more data than needed
  • Under-fetching — an operation requires calls to N endpoints

Facebook internally (2012) develops GraphQL to feed the iOS/Android mobile app with heterogeneous data (profile, feed, notifications) in a single optimised call.

The release

GraphQL spec is released as Open Source by Facebook on 14 July 2015. Leads: Lee Byron, Dan Schafer, Nick Schrock. MIT licence.

Concepts

  • Schema — strongly typed type system with scalars, objects, interfaces, unions, enums
  • Query — read operation, client specifies data shape
  • Mutation — write operation
  • Subscription — real-time stream (typically over WebSocket)
  • Resolver — server functions that resolve each field
type User {
  id: ID!
  name: String!
  posts: [Post!]!
}

query {
  user(id: "123") {
    name
    posts { title }
  }
}

Advantages

  • Single endpoint /graphql for everything
  • Client-specified data — no over/under-fetching
  • Typed schema — introspection, tooling
  • Versionless — evolution via deprecation
  • Strong tooling — GraphiQL, Apollo Studio, Insomnia, Postman

Disadvantages

  • N+1 queries — naive resolvers devastating; requires DataLoader
  • Caching — more complex than REST/HTTP cache
  • Complexity attacks — deep queries expensive; needs depth limit, cost analysis
  • Over-engineering for simple APIs

Implementations

  • graphql-js — reference, Node.js
  • Apollo Server/Client — most widespread ecosystem
  • Relay — Meta client for React
  • Hasura — GraphQL auto-generated from Postgres
  • PostGraphile — Postgres → GraphQL
  • Strawberry (Python), graphql-ruby, sangria (Scala), graphql-java, HotChocolate (.NET)

Composition and gateway

  • Schema stitching — composing multiple GraphQL schemas into a super-schema
  • GraphQL Mesh (in ideation) — multi-source gateway

In the Italian context

GraphQL is spreading into headless e-commerce projects, media publishing, mobile apps with BFFs and internal admin tools for multi-source data aggregation.


References: GraphQL Open Source (14 July 2015). Facebook/Meta. Lee Byron, Dan Schafer, Nick Schrock. MIT licence. Apollo Server/Client.

Need support? Under attack? Service Status
Need support? Under attack? Service Status