Skip to Content

Why would you use GraphQL?

GraphQL is a query language for APIs that was developed by Facebook in 2012 and open sourced in 2015. It provides an alternative to REST APIs and has been gaining popularity over the past few years, especially for web and mobile applications. There are several key reasons why a developer might choose to use GraphQL over REST:

Flexibility

GraphQL allows the client to dictate exactly what data it needs from the API. Instead of hitting multiple endpoints to gather data, the client can query the GraphQL server for the specific fields it requires in a single request. This allows the client to retrieve only the data it needs and nothing more. The GraphQL query language is versatile and allows fetching nested, relational data in one go. For example, a single GraphQL query can return a user object with its associated posts and comments.

Example GraphQL Query

{
  user(id: "1") {
    name
    posts {
      title
      comments {
        text
      }
    }
  }
}

With REST APIs, multiple round trips would be required to retrieve this nested data. GraphQL consolidates it into a single request. The flexibility enables applications to get the exact data they need without over or under fetching.

Strong Typing

GraphQL has a strong typing system that defines the capabilities of an API. All the types and fields exposed by the server are documented in the GraphQL schema. This allows clients to easily understand and consume the API without needing external documentation. The GraphQL type system is static and robust which makes it easy to detect errors during development. With REST, data is usually not typed and documentation often lags behind implementation.

Example GraphQL Types

type User {
  id: ID!
  name: String!
  age: Int
  posts: [Post!]!
}

type Post {
  id: ID!
  title: String!
  author: User!
  comments: [Comment!]!
}

The exclamation point indicates a field cannot be null. GraphQL’s strong typing and introspective schema system make the API easy to understand and consume.

Nullability

In REST APIs, null fields are usually returned as empty or omitted from the response. This can lead to ambiguity on the client – it won’t know whether a field was intentionally empty or just failed to return from the server. With GraphQL, every field specifies whether it is nullable or not in the schema using the exclamation point notation seen above. This removes uncertainty around null values.

Documentation

As mentioned above, the GraphQL schema serves as built-in documentation for an API. Since it exposes all the types, fields, arguments and nullable requirements, developers don’t need to look elsewhere to understand how to use the API. REST APIs typically require separate documentation which may not always be up to date with implementation.

Versioning

GraphQL APIs are considered versionless. This is because the schema can be extended and altered without impacting existing queries. New fields and types can be added without breaking old clients. This is different from REST where endpoints represent resource versions, so any changes can break workflows relying on that endpoint. With GraphQL’s flexible queries, new data can be introduced without versioning the API.

Performance

For queries requiring multiple backend requests, GraphQL consolidates it into a single request improving performance. The flexibility to retrieve only needed data also optimizes network usage. And caching is simplified with GraphQL since queries have unique signatures – cached data can be keyed off query text. With REST, endpoint URLs may not map cleanly to request data.

On the other hand, over-fetching data with GraphQL can result in larger response sizes and slower performance compared to targeted REST requests. So performance depends on the client usage – for apps that need to stitch together data from multiple sources, GraphQL is often faster.

Developer Experience

The strongly typed schema, nullability, and ability to request nested data in a single round trip creates a better developer experience compared to REST. The flexibility of querying only needed fields and getting back a consolidated response makes GraphQL easy for frontend developers to consume. There is less over-fetching and under-fetching of data. The discoverability of API capabilities from the schema improves developer workflows. Overall, the declarative nature of GraphQL aligns well with how developers think about data and querying.

Statelessness

Like REST, GraphQL is also stateless and does not maintain any client state on the server. Applications can cache query results on the client and associate it with session state there. Server-side, GraphQL executes incoming requests independently with no sessions.

Backward Compatibility

As mentioned in the versioning section, GraphQL APIs evolve in a backward compatible way. Changing or adding new fields and types does not break existing queries. This enables teams to innovate and continuously improve their APIs without affecting downstream dependents.

Rapid Development

The strongly typed schema, nullability requirements, and query validation enforce discipline early in development. This often surfaces bugs and inconsistencies upfront preventing bugs down the line. Combined with the developer experience benefits, GraphQL results in faster development cycles.

Community

GraphQL has a thriving open source community with popular frameworks like Apollo, Relay, Gatsby, and tools like GraphiQL available. The ecosystem continues to expand with contributions from developers across organizations. There is strong community support available for learning and troubleshooting GraphQL APIs.

Client-Driven Queries

GraphQL empowers clients to craft queries specifying their exact data needs. The schema serves as a powerful way to discover API capabilities. This eliminates guesswork around endpoint interfaces and shifts API development towards fulfilling client needs.

Immutability

While GraphQL does not enforce immutability, its query semantics promote immutable data graphs. Since clients can specify the exact data they need in nested form, this lends well to apps built around immutable models and derivation of state. Architecting GraphQL servers with immutable models simplifies data management.

Drawbacks of GraphQL

While GraphQL has many benefits, there are some limitations to consider as well:

Caching

GraphQL queries are unique based on their field text. This makes caching less straightforward compared to REST URLs. Client-side caching needs logic to normalize queries to identify duplicates. There are utilities to help handle caching like Apollo’s NormalizedCache.

Tooling

The GraphQL ecosystem continues to mature, but tooling support currently lags behind REST. There are fewer client libraries and third-party integrations available though the landscape is improving.

Debugging

Debugging GraphQL can be more challenging than REST due to the query complexity and multiple backend data sources. Tools like Apollo Server’s GraphQL Playground help with exploring schema and testing queries.

Versioning

While the flexibility around evolving schemas avoids classic versioning, larger disruptive changes may still require advanced coordination between clients and servers. There are extensions like Apollo’s schema versioning to help orchestrate breaking changes.

Monitoring

The granular GraphQL language can result in a proliferation of distinct queries to monitor and optimize. Tools like Apollo Server provide metrics on query performance and usage to aid monitoring.

Security

GraphQL’s flexibility requires APIs to implement additional safeguards against abuse like depth limiting, cost analysis, and timeouts. Authentication and authorization also get more complex with fine-grained queries compared to coarse REST endpoints.

When to use GraphQL vs REST

So when should you choose GraphQL over REST? Here are some key factors to consider:

Factor GraphQL REST
Fetching requirements Need flexible, ad-hoc queries fetching nested and relational data Mostly need simple CRUD operations
Client type JavaScript/Mobile clients Broad device support needed
Caching needs More complex caching requirements Simple caching by URL sufficient
Iteration speed Frequent client-driven API changes Stable API requirements
Team size Multiple client teams Small team or single client

GraphQL makes sense for web and mobile apps with dynamic data needs. The flexibility empowers frontend teams to innovate quickly on evolving client requirements. REST APIs are suitable for simple data models and broad device usage. For large enterprises with multiple client teams, GraphQL can improve developer experience and iterate faster across changing needs.

Conclusion

GraphQL provides an powerful alternative to REST for client-driven applications with dynamic data needs. Key strengths like its flexibility, discoverability, performance gains, and developer experience make GraphQL a compelling option for modern APIs. While it has some drawbacks around caching, tools, and monitoring, the GraphQL ecosystem continues to mature. For the right use cases, GraphQL can boost developer productivity and velocity for evolving web and mobile applications.