graphql or bust · preface:introductionto graphql...

125

Upload: others

Post on 23-May-2020

5 views

Category:

Documents


0 download

TRANSCRIPT

Page 1: GraphQL or Bust · Preface:Introductionto GraphQL Withinthelastcoupleofyears,therehasbeenaresur-genceofdiscussionaroundAPIdesignstandardssuch as REST, gRPC, GraphQL, and many others
Page 2: GraphQL or Bust · Preface:Introductionto GraphQL Withinthelastcoupleofyears,therehasbeenaresur-genceofdiscussionaroundAPIdesignstandardssuch as REST, gRPC, GraphQL, and many others

GraphQL or BustTo Use it Or Not to Use It? That is TheQuestion.

Nordic APIs

This book is for sale at http://leanpub.com/graphql

This version was published on 2018-07-11

This is a Leanpub book. Leanpub empowers authors andpublishers with the Lean Publishing process. LeanPublishing is the act of publishing an in-progress ebookusing lightweight tools and many iterations to get readerfeedback, pivot until you have the right book and buildtraction once you do.

© 2017 - 2018 Nordic APIs

Page 3: GraphQL or Bust · Preface:Introductionto GraphQL Withinthelastcoupleofyears,therehasbeenaresur-genceofdiscussionaroundAPIdesignstandardssuch as REST, gRPC, GraphQL, and many others

Also By Nordic APIsSummer Collection

Developing the API Mindset

Winter Collection

The API Lifecycle

Securing The API Stronghold

API-Driven DevOps

The API Economy

Programming APIs with the Spark Web Framework

How to Successfully Market an API

API Design on the Scale of Decades

Page 4: GraphQL or Bust · Preface:Introductionto GraphQL Withinthelastcoupleofyears,therehasbeenaresur-genceofdiscussionaroundAPIdesignstandardssuch as REST, gRPC, GraphQL, and many others

This release is dedicated to the over 30 thought leaders thathave contributed to the Nordic APIs blog over the past few

years!

Page 5: GraphQL or Bust · Preface:Introductionto GraphQL Withinthelastcoupleofyears,therehasbeenaresur-genceofdiscussionaroundAPIdesignstandardssuch as REST, gRPC, GraphQL, and many others

Contents

Preface: Introduction to GraphQL . . . . . . . . . . i

Is GraphQL The End of REST Style APIs? . . . . . . . 1Defining REST and its Limitations . . . . . . . . . . 2The End Of The Status Quo . . . . . . . . . . . . . . 8Conclusion . . . . . . . . . . . . . . . . . . . . . . . . 9

5 Potential Benefits of Integrating GraphQL . . . . 10What is GraphQL . . . . . . . . . . . . . . . . . . . . 111 - More Elegant Data Retrieval . . . . . . . . . . . 122 - More Backend Stability . . . . . . . . . . . . . . 133 - Better Query Efficiency . . . . . . . . . . . . . . 144 - GraphQL Is a Specification . . . . . . . . . . . . 165 - GraphQL Improves Understanding and Orga-

nization . . . . . . . . . . . . . . . . . . . . . . 17Who Uses It . . . . . . . . . . . . . . . . . . . . . . . . 17Conclusion: Assess . . . . . . . . . . . . . . . . . . . 20

How to Wrap a REST API in GraphQL . . . . . . . . . 22What is GraphQL? . . . . . . . . . . . . . . . . . . . . 23Defining a Schema . . . . . . . . . . . . . . . . . . . 24Alternatives to this Method . . . . . . . . . . . . . . 28To Wrap or Not to Wrap . . . . . . . . . . . . . . . . 30Conclusion: Wrap or Recode . . . . . . . . . . . . . 31

Page 6: GraphQL or Bust · Preface:Introductionto GraphQL Withinthelastcoupleofyears,therehasbeenaresur-genceofdiscussionaroundAPIdesignstandardssuch as REST, gRPC, GraphQL, and many others

CONTENTS

Best Practices for AHealthyGraphQL Implemen-tation . . . . . . . . . . . . . . . . . . . . . . . . . . . 32Dogma vs Practices . . . . . . . . . . . . . . . . . . . 33Conclusion . . . . . . . . . . . . . . . . . . . . . . . . 40

Security Concerns toConsiderBefore Implement-ing GraphQL . . . . . . . . . . . . . . . . . . . . . . . 41GraphQL - A Summary . . . . . . . . . . . . . . . . . 42Implied Documentation vs. Actual Documentation 43Unified Failures . . . . . . . . . . . . . . . . . . . . . 44Data and Server Transaction Volumes . . . . . . . 45Information Hiding and Chattiness . . . . . . . . . 46Authorization and GraphQL . . . . . . . . . . . . . 47Measured Optimism . . . . . . . . . . . . . . . . . . 48

7 Unique Benefits of Using GraphQL inMicroser-vices . . . . . . . . . . . . . . . . . . . . . . . . . . . . 50Clearly Separated Data Owners . . . . . . . . . . . 51Data Load Control Granularity . . . . . . . . . . . . 52Parallel Execution . . . . . . . . . . . . . . . . . . . . 52Request Budgeting . . . . . . . . . . . . . . . . . . . 53Powerful Query Planning . . . . . . . . . . . . . . . 54Service Caching . . . . . . . . . . . . . . . . . . . . . 55Easy Failure Handling and Retries . . . . . . . . . . 55Case Study ofMicroservices In Action: HowGraphQL

Benefits Yelp . . . . . . . . . . . . . . . . . . . 56Final Thoughts . . . . . . . . . . . . . . . . . . . . . . 58

ComparingGraphQLWithOtherMethods to TetherAPI Calls . . . . . . . . . . . . . . . . . . . . . . . . . 59What Do We Mean By Tethering API Calls? . . . . 60Benefits of Tethering API Calls . . . . . . . . . . . . 61Drawbacks of Tethering API Calls . . . . . . . . . . 63Use Cases . . . . . . . . . . . . . . . . . . . . . . . . . 64Alternatives — GraphQL . . . . . . . . . . . . . . . . 65Conclusions . . . . . . . . . . . . . . . . . . . . . . . 67

Page 7: GraphQL or Bust · Preface:Introductionto GraphQL Withinthelastcoupleofyears,therehasbeenaresur-genceofdiscussionaroundAPIdesignstandardssuch as REST, gRPC, GraphQL, and many others

CONTENTS

The Power of Relay: The Entry Point to GraphQL . 68What’s the Difference Between GraphQL and

Relay? . . . . . . . . . . . . . . . . . . . . . . . 69What is Relay? . . . . . . . . . . . . . . . . . . . . . . 70The Good . . . . . . . . . . . . . . . . . . . . . . . . . 71The Bad . . . . . . . . . . . . . . . . . . . . . . . . . . 75A REST Replacement . . . . . . . . . . . . . . . . . . 76Conclusion . . . . . . . . . . . . . . . . . . . . . . . . 78

10 GraphQL Consoles in Action . . . . . . . . . . . . 79GraphiQL: GraphQL API Explorer . . . . . . . . . . 801: GraphQL Hub . . . . . . . . . . . . . . . . . . . . . 812: Brandfolder . . . . . . . . . . . . . . . . . . . . . . 823: Buildkite . . . . . . . . . . . . . . . . . . . . . . . . 824: EHRI . . . . . . . . . . . . . . . . . . . . . . . . . . . 835: GDOM . . . . . . . . . . . . . . . . . . . . . . . . . 846: GitHub . . . . . . . . . . . . . . . . . . . . . . . . . 847: HIV Drug Resistance Database . . . . . . . . . . 858: Helsinki Open Data . . . . . . . . . . . . . . . . . 869: melodyCLI . . . . . . . . . . . . . . . . . . . . . . . 8610: SuperChargers.io . . . . . . . . . . . . . . . . . . 8711: Microsoft . . . . . . . . . . . . . . . . . . . . . . . 88Does Increased Usage Validate GraphQL? . . . . . 89Tips on Making GraphQL / GraphiQL Awesome . 90More Resources: . . . . . . . . . . . . . . . . . . . . 90

10 Tools and Extensions For GraphQL APIs . . . . . 92List of 10+ Tools & Extensions for GraphQL APIs 931: GraphiQL . . . . . . . . . . . . . . . . . . . . . . . 932: GraphQL Voyager by APIs.guru . . . . . . . . . . 943: GraphCMS . . . . . . . . . . . . . . . . . . . . . . . 964: GraphQL Docs by Scaphold.io . . . . . . . . . . . 975: GraphQL Faker . . . . . . . . . . . . . . . . . . . . 976: Swagger to GraphQL . . . . . . . . . . . . . . . . 987: GraphQL IDE . . . . . . . . . . . . . . . . . . . . . 98

Page 8: GraphQL or Bust · Preface:Introductionto GraphQL Withinthelastcoupleofyears,therehasbeenaresur-genceofdiscussionaroundAPIdesignstandardssuch as REST, gRPC, GraphQL, and many others

CONTENTS

8: GraphQL Network . . . . . . . . . . . . . . . . . . 999: Graphcool . . . . . . . . . . . . . . . . . . . . . . . 9910: Optics by Apollo . . . . . . . . . . . . . . . . . . 100Final Thoughts . . . . . . . . . . . . . . . . . . . . . . 101Resources . . . . . . . . . . . . . . . . . . . . . . . . . 102

What The GraphQL Patent Release Means Forthe API Industry . . . . . . . . . . . . . . . . . . . . 103Background . . . . . . . . . . . . . . . . . . . . . . . 104Developers Express Concern . . . . . . . . . . . . . 105Out of the Frying Pan… . . . . . . . . . . . . . . . . 107Is This a Concern? . . . . . . . . . . . . . . . . . . . . 108Oil and Water . . . . . . . . . . . . . . . . . . . . . . 109Final Thoughts . . . . . . . . . . . . . . . . . . . . . . 110Stay Connected . . . . . . . . . . . . . . . . . . . . . 112

Nordic APIs Resources . . . . . . . . . . . . . . . . . . 113

Endnotes . . . . . . . . . . . . . . . . . . . . . . . . . . . 115

Page 9: GraphQL or Bust · Preface:Introductionto GraphQL Withinthelastcoupleofyears,therehasbeenaresur-genceofdiscussionaroundAPIdesignstandardssuch as REST, gRPC, GraphQL, and many others

Preface: Introduction toGraphQL

Within the last couple of years, there has been a resur-gence of discussion around API design standards suchas REST, gRPC, GraphQL, and many others. While theRepresentational State Transfer (REST) methodology hasbeen a perfect fit for many web APIs - for the past decadeormore in some cases - some developers see operationalimprovements within nuanced methods that break fromthese original constructs.

GraphQL, the querylanguage alteringhow we interact withAPIs

Developed by Facebook, GraphQLpresents a sea change in how APIproviders enable access to theirdata, and can bring high usabilitybenefits to consumers. Smart APIowners put emphasis into treat-ing their services as a product;this means improving the devel-oper experience and fine-tuning theuser onboarding mechanism. As

GraphQL enables an unparalleled ability to display APIendpoints and test call behaviors, as well as an opera-tional boost in aggregating API responses, it could verywell be the tool API owners are searching for to improvetheir developer experiences.

But we aren’t quick to bandwagon on any new technologywithout first opening the floor to debate. So, over the pastyear we exhausted many subjects on the blog, throwing

Page 10: GraphQL or Bust · Preface:Introductionto GraphQL Withinthelastcoupleofyears,therehasbeenaresur-genceofdiscussionaroundAPIdesignstandardssuch as REST, gRPC, GraphQL, and many others

Preface: Introduction to GraphQL ii

GraphQL into the security ring, judging the process ofmigrating a REST API to GraphQL, vetting any outstand-ing licensing issues, and searching for GraphQL APIs inpractice today as evidence of its use. We’ve comparedit to other methods of linking API calls, charted industrybest practices, and looked at the growing spectrum ofGraphQL tooling.

In this volumewe’ve aggregated nearly all of the GraphQLknowledge that has been shared on the Nordic APIs blogand at our conferences. Being a relatively new technol-ogy, somemay still have questions about it, and we hopeto answer those questions as well as open avenues ofdiscussion around new concerns.

The truth is your current systems likely won’t bust withoutGraphQL. The title for this eBook represents the ferventcommunity adoption we’ve seen quickly embrace thetechnology.

So, please enjoy GraphQL or Bust, and let us know howwecan improve. If you haven’t yet, consider following us, andsigning up to our newsletter for curated blog updates andfuture event announcements. We also accept contribu-tions from the community - if interested please visit ourCreate With Us page to pitch an article.

Thank you for reading!

– Bill Doerrfeld, Editor in Chief, Nordic APIs

Connect with Nordic APIs:

Facebook | Twitter | Linkedin | Google+ | YouTube

Blog | Home | Newsletter | Contact

Page 11: GraphQL or Bust · Preface:Introductionto GraphQL Withinthelastcoupleofyears,therehasbeenaresur-genceofdiscussionaroundAPIdesignstandardssuch as REST, gRPC, GraphQL, and many others

Is GraphQL The End ofREST Style APIs?

The world of APIs is one of innovation and constantiteration. The technologies that once drove the largestand best solutions across the web have been supplantedand replaced by new, more innovative solutions.

That is why it’s surprising, then, that many developershave clung to what they consider the bastions of webAPI development. Such a bastion is the REST architecture.To some developers, REST is an aging and incompletedproposition that does not meet many of the new devel-opment qualifications required by the unique challengesfaced by modern development groups.

Today, we’re going to look at a technology that is poisedto replace, or at the very least, drastically change the wayAPIs are designed and presented — GraphQL. We’ll dis-

Page 12: GraphQL or Bust · Preface:Introductionto GraphQL Withinthelastcoupleofyears,therehasbeenaresur-genceofdiscussionaroundAPIdesignstandardssuch as REST, gRPC, GraphQL, and many others

Is GraphQL The End of REST Style APIs? 2

cuss a little bit of history, what issues REST suffers from,and what GraphQL does differently, tracking a presenta-tion given by Joakim Lundborg at our Platform Summit.

“The way we design our APIs structures the waywe think [about] the tools and applications webuild.” - Joakim Lundborg, Wrapp

Defining REST and its Limitations

REST or Representational State Transfer, is an API designarchitecture developed to extend and, in many cases,replace older architectural standards. Objects in REST aredefined as addressable URIs, and are typically interactedwith using the built-in verbs of HTTP— specifically, GET,PUT, DELETE, POST, etc. In REST, HATEOAS (HypermediaAs The Engine Of Application State) is an architectureconstraint in which the client interacts with hypermedialinks, rather than through a specific interface.

With REST, the core concept is that everything is a re-source. While REST was a great solution when it was firstproposed, there are some pretty significant issues thatthe architecture suffers from. According to Lundberg, thecircumstances have changed, giving rise to the need fornew technical implementations:

“Many things have happened. We have a lotof mobile devices with lots of social and verydata rich applications being produced…Wenowhave very powerful clients, and we have datathat is changing all the time. This brings somenew problems.”

Page 13: GraphQL or Bust · Preface:Introductionto GraphQL Withinthelastcoupleofyears,therehasbeenaresur-genceofdiscussionaroundAPIdesignstandardssuch as REST, gRPC, GraphQL, and many others

Is GraphQL The End of REST Style APIs? 3

Here are some issues Lundberg sees with REST:

Round Trip and Repeat Trip Times

REST’s defining feature is the ability to reference re-sources—theproblem iswhen those resources are com-plicated and relational in a more complex organizationknown as a graph. Fetching these complicated graphsrequires round trips between the client and server, and insome cases, repeated trips for network conditions andapplication types.

What this ultimately results in is a system where themore useful it is, the slower it is. In other words, asmore relational data is presented, the system chokes onitself.

Over/Under Fetching

Due to the nature of REST and the systems which oftenuse this architecture, REST APIs often result in over/underfetching. Over fetching is when more data is fetchedthan required, whereas under fetching is the opposite,when not enough data is delivered upon fetching.

When first crafting a resource URI, everything is fine —the data that is necessary for functionality is delivered,and all is well. As the API grows in complexity, and theresources thus grow in complexity as well, this becomesproblematic.

Applications that don’t need every field or tag still receiveit all as part of the URI. Solutions to fix this, such as ver-sioning, result in duplicate code and “spaghettification” of

Page 14: GraphQL or Bust · Preface:Introductionto GraphQL Withinthelastcoupleofyears,therehasbeenaresur-genceofdiscussionaroundAPIdesignstandardssuch as REST, gRPC, GraphQL, and many others

Is GraphQL The End of REST Style APIs? 4

the code base. Going further, specifically limiting data toa low-content URI that is then extensible results in morecomplexity and resultant under fetching in poorly formedqueries.

Weak Typing and Poor Metadata

REST APIs often unfortunately suffer from poor typing.While this issue is argued by many API providers andcommentators (often with the caveat that HTTP itselfcontains a typing system), the fielding system solutionsoffered simply do not match the vast range and scope ofdata available to the API.

Specifically, this is an argument in favor of strong typingrather than weak typing. While there are solutions thatoffer typing, the delineation between weak and strong isthe issue here, not an argument defusedby simply stating“well there is typing”. The strength and quality of typingdoes matter.

This is more a matter of age and mobility rather than anintrinsic problem, of course, and can be rectified usingseveral solutions (of which GraphQL is one).

Improper Architecture Usage

REST suffers from the fact that it’s often used for some-thing it wasn’t really designed for, and as a result, it oftenmust be heavily modified. That’s not to say that RESTdoesn’t have its place — it’s only to say that it may notbe the best solution for serving client applications. AsFacebook says in its own documentation:

Page 15: GraphQL or Bust · Preface:Introductionto GraphQL Withinthelastcoupleofyears,therehasbeenaresur-genceofdiscussionaroundAPIdesignstandardssuch as REST, gRPC, GraphQL, and many others

Is GraphQL The End of REST Style APIs? 5

“These attributes are linked to the fact that“REST is intended for long-lived network-basedapplications that span multiple organizations”according to its inventor. This is not a require-ment for APIs that serve a client app built withinthe same organization.”

All of this is to say that GraphQL is functionally the endof REST — but not in the way that terminology implies.Until now, REST has been seen as the foundational archi-tecture of modern APIs, and in a way, the last bastion ofclassic API design. The argument here is not made to fullysever REST from our architectural lexicon, but instead toacknowledge that there are several significant issues thatare not properly and fully rectified by the solutions oftenproffered by its proponents. Therefore, the answer to thequestion of this piece— is GraphQL The End of REST StyleAPIs? — is quite simple. Yes, using GraphQL is the end ofREST style APIs as we know it — specifically through theextension of base functionality and a reconsideration ofdata relations and functions. ## 4 Things GraphQL DoesBetter than REST

“GraphQL declares everything as a graph… Yousay what you want, and then you will get that.”

Now that we’ve seen the issues with REST, how, exactly,does GraphQL solve them?

REST Has Many Roundtrips - GraphQL HasFew

The biggest benefit of GraphQL over REST is the simplefact that GraphQL has fewer roundtrips than REST does,

Page 16: GraphQL or Bust · Preface:Introductionto GraphQL Withinthelastcoupleofyears,therehasbeenaresur-genceofdiscussionaroundAPIdesignstandardssuch as REST, gRPC, GraphQL, and many others

Is GraphQL The End of REST Style APIs? 6

and more efficient ones at that. GraphQL unifies datathat would otherwise exist in multiple endpoints (or evenworse, ad hoc endpoints), and creates packages.

By packaging data, the data delivery is made more effi-cient, and decreases the amount of resources requiredfor roundtrip calls. This also fundamentally restructuresthe relationship between client and server, placing moreefficiency and control in the hands of GraphQL clients.

REST Has Poor Type Systems - GraphQL Hasa Sophisticated One

While REST can have a type system through implemen-tations of HTTP, REST itself does not have a very so-phisticated typing system. Even in good implementations,you often end up with variants of type settings — forexample, clientdatamobile and clientdatadesktop — to fitREST standard calls.

GraphQL solves this with a very sophisticated typing sys-tem, allowing for more specific and powerful queries.

REST Has Poor Discoverability - GraphQLHas Native Support

Discoverability is not native to REST, and requires specificand methodical implementations of HATEOAS, Swagger,and other such solutions in order to be fully discover-able. The key there is “fully discoverable” — yes, RESThas HATEOAS as a “native” discovery system, but it lackssome important elements of effective discoverability—

Page 17: GraphQL or Bust · Preface:Introductionto GraphQL Withinthelastcoupleofyears,therehasbeenaresur-genceofdiscussionaroundAPIdesignstandardssuch as REST, gRPC, GraphQL, and many others

Is GraphQL The End of REST Style APIs? 7

namely known document structure, server response con-straint structures, and an independence from standard,restrictive error mechanisms in HTTP.

While this and many other points of negative consider-ation towards REST is often answered with “but you canadd that functionality!”, the fact that it lacks it by defaultonly adds to the complexity we’re trying to move awayfrom.

Because GraphQL is based on relational data and, whenoperating on a properly formed schema, is self describ-ing, GraphQL is by design natively discoverable. Discov-erability is incredibly important, both in terms of allowingfor extensible third-party functionality and interactionsand for on-boarding developers and users with an easyto understand, easy to explore system of functions.

REST Is Thin Client/Fat Server - GraphQL isFat Client/Fat Server

In REST design, the relationship between client and serveris well-defined, but unbalanced. REST uses a very thinclient, depending on processing from the server andthe endpoints that have been defined for it. Since thebulk of the processing and control is placed firmly onthe server, this strips power from the client, and alsostresses server side resources. Until now that has beenfine, but as devices grow in processing power and ability,this client/server relationship may need rethinking.

GraphQL, however, is different. By offloading specifica-tion of expected data format to the client and structuringdata around that call on the server side, we have a FatClient/Fat Server (or even a Thin Client/Thin Server de-

Page 18: GraphQL or Bust · Preface:Introductionto GraphQL Withinthelastcoupleofyears,therehasbeenaresur-genceofdiscussionaroundAPIdesignstandardssuch as REST, gRPC, GraphQL, and many others

Is GraphQL The End of REST Style APIs? 8

pending on approach) in which both power and controlare level across the relationship.

This is very powerful when one considers that the datatype being requested will be used for specific purposesas regulated and requested by the Client itself— it makessense, then, that moving from a Thin/Fat relationship toa Fat/Fat or Thin/Thin relationship would improve thisfunctionality on the Client side while freeing up Server re-sources. Of course, this assumes that the client is capableof handling this burden.

The End Of The Status Quo

There’s a tendency in the tech space for providers anddevelopers of new technologies to proclaim the end of anera with each solution. While it’s common to discussionin the field, the fact is that there are very few completeparadigm shifts that signal an irrevocable end to existingtechnologies.

Innovation depends on prior technologies to create newfunctionality. Therefore, when a new solution is designed,it’s not replacing the solution, but rather iterating. Thesame is true here. While GraphQL may not be the com-plete demise of REST, it is the end of the status quo.While there are a great many solutions to the issuesraised here, they all depend on further integrations andmodifications. GraphQL is essentially an overhaul, andonewhich improves the base level functionality of the APIitself.

Page 19: GraphQL or Bust · Preface:Introductionto GraphQL Withinthelastcoupleofyears,therehasbeenaresur-genceofdiscussionaroundAPIdesignstandardssuch as REST, gRPC, GraphQL, and many others

Is GraphQL The End of REST Style APIs? 9

Conclusion

What we have here is a basic value proposition. GraphQLdoes what it does well, but the question of integration liesdirectly on what kind of data you’re processing, and whatissues your API is creating. For simple APIs, REST worksjust fine, but as data gets more complex and the needs ofthe data providers climbs, so too will the need for morecomplex and powerful systems.

Adopting GraphQL as an adjunct or extension of the RESTideology, while removing REST from the intellectual spaceof “too big to not use”, will directly result inmore powerfulAPIswith easier discoverability and greatermanageabilityof the data they handle.

Page 20: GraphQL or Bust · Preface:Introductionto GraphQL Withinthelastcoupleofyears,therehasbeenaresur-genceofdiscussionaroundAPIdesignstandardssuch as REST, gRPC, GraphQL, and many others

5 Potential Benefits ofIntegrating GraphQL

GraphQL is incredibly powerful — so powerful, in fact,that it is used by corporations such as Facebook to drivetheir large, complex social systems for billions of users.Despite this, the language is still relatively nascent, andits usage has yet to reach the dizzying heights that thoselanguages it replaces and augments occupy.

In this piece, we’ll discover what GraphQL is, and whatmakes it so powerful. We’ll give you five compelling rea-sons to adopt it as part of your system and ecosystem,andhighlight somepublic use cases that demonstrate thesuccess of such adoption and integration.

Page 21: GraphQL or Bust · Preface:Introductionto GraphQL Withinthelastcoupleofyears,therehasbeenaresur-genceofdiscussionaroundAPIdesignstandardssuch as REST, gRPC, GraphQL, and many others

5 Potential Benefits of Integrating GraphQL 11

What is GraphQL

GraphQL is an application layer query language. Whatthis means is that GraphQL is designed to interpret astring from a server or client and return that data in anunderstandable, stable, and predictable format. As theofficial website for GraphQL puts it, “Describe your data,ask for what you want, get predictable results.”

GraphQL does this via simple, plain to understand re-quests and statements. A simple example from the of-ficial website highlights this simplicity perfectly. This is avalid descriptor within GraphQL:

type Project {

name: String

tagline: String

contributors: [User]

}

Which, when paired with an effective and simple request:

{

project(name: "GraphQL") {

tagline

}

}

Returns a clean, easy, and simple result:

Page 22: GraphQL or Bust · Preface:Introductionto GraphQL Withinthelastcoupleofyears,therehasbeenaresur-genceofdiscussionaroundAPIdesignstandardssuch as REST, gRPC, GraphQL, and many others

5 Potential Benefits of Integrating GraphQL 12

{

"project": {

"tagline": "A query language for APIs"

}

}

The simplicity and power behind the language comesfrom its chief architects. GraphQL is principally an effortfrom Facebook, with a variety of additional contibutorsdedicating their efforts to boost efficency.

GraphQL came from the result of Facebook’s transitionaway from HTML5 applications on mobile to support-ing more robust, native applications. As the need fora stronger backend and easier universal interface pre-sented itself, GraphQL quickly emerged as the languageof choice.

A quick word on GraphQL’s implementations— there is a client often used as an entry pointto GraphQL known as Relay which we willspecifically cover in a following piece.

With all this said, what makes GraphQL so powerful?

1 - More Elegant Data Retrieval

GraphQL is all about simplicity— and with that simplic-ity comes a more elegant methodology and experienceconcerning data retrieval. Because data is collected undera common endpoint or call that is variable concerningthe type of data and request as stated in the initial call,several huge benefits are intrinsic to the call system.

Page 23: GraphQL or Bust · Preface:Introductionto GraphQL Withinthelastcoupleofyears,therehasbeenaresur-genceofdiscussionaroundAPIdesignstandardssuch as REST, gRPC, GraphQL, and many others

5 Potential Benefits of Integrating GraphQL 13

First and foremost, using GraphQL eliminates ad hocendpoints and roundtrip object retrievals. Imagine youwere a delivery driver looking at amap of where to delivera package. On that map, you have fifteen possible entrypoints to streets near the street you need to get to—eachwith their own speed limits, limitations of cargo weight,and allowed vehicle type.

The complexity incurred in this situation is absolutelyincredible, so much so that it would delay delivery. Nowimagine the same situation, but with only a single streetand will well-defined, commonly known rules — that’swhat GraphQL can provide.

2 - More Backend Stability

With simplicity comes stability — this is a basic fact oflife. The more simple a process is, the less likely there areto be faults in the planning, construction, execution, andcontinued operation over time. GraphQL makes queriesmore simple and elegant — and as a result, improves thestability of the entire process.

How GraphQL does this is quite complex, but there’sone methodology in particular that is worth mentioning.Because data is delivered in a structured, defined way in-dependent on the client request (as the rules are dictatedby GraphQL itself, not the application per se), data can bemanipulated, changed, and altered in the backend codebase without directly requiring changes in how the clientfunctions.

In the traditional server-client relationship, this is sim-ply not possible — the data is available, queryable, and

Page 24: GraphQL or Bust · Preface:Introductionto GraphQL Withinthelastcoupleofyears,therehasbeenaresur-genceofdiscussionaroundAPIdesignstandardssuch as REST, gRPC, GraphQL, and many others

5 Potential Benefits of Integrating GraphQL 14

usable, but the format and method are dictated largelyby the client. As long as the general request fits intoa standard methodology as dictated by the languageor documentation, that data is delivered successfully.Change how the database works, however, or update theapplication independent of legacy support systems, andyou have a “broken” application.

This is not a problem with GraphQL. The entry pointdefined by GraphQL is almost like a translatable layer —the structure of request is dictated by the server, andthen routed to the necessary resources and systems bythe language path itself. Accordingly, an application back-end can be overhauled without necessitating a completerestructuring of the client application or the common callmethod, as the methodology is controlled directly by theserver in the first place.

3 - Better Query Efficiency

GraphQL unifies data that would otherwise require mul-tiple endpoints, or in the worst case scenario ad hocendpoints and complex repeat retrievals, and gives therequester a single, simple entry point.

Because data is defined on the server with a graph-basedscheme, data can be delivered as a package rather thanthrough multiple calls. For instance, the following codefor a content and comment query would have a singleendpoint in GraphQL:

Page 25: GraphQL or Bust · Preface:Introductionto GraphQL Withinthelastcoupleofyears,therehasbeenaresur-genceofdiscussionaroundAPIdesignstandardssuch as REST, gRPC, GraphQL, and many others

5 Potential Benefits of Integrating GraphQL 15

{

latestPost {

_id,

title,

content,

author {

name

},

comments {

content,

author {

name

}

}

}

}

In traditional API query languages, this would take at least8 calls, and would have to point to specific endpointsto differentiate the content of the post itself and thecomment content.

This doesn’t just increase efficiency of data delivery,either — it fundamentally decreases the amount of re-sources required for each data request. Furthermore,retrieval constraints are declared with a declarative-hier-archical query to a single endpoint, reducing the call datademands less for the client.

The biggest net benefit of this entire process is, of course,a fundamental restructuring of the relationship betweenthe client and the server. In GraphQL, the server pub-lishes clear and explicit rules specific to the application,and the client requests that language with common dataqueries. Simply said — developers are able to imposedata restrictions more naturally and with less impact on

Page 26: GraphQL or Bust · Preface:Introductionto GraphQL Withinthelastcoupleofyears,therehasbeenaresur-genceofdiscussionaroundAPIdesignstandardssuch as REST, gRPC, GraphQL, and many others

5 Potential Benefits of Integrating GraphQL 16

the consumer.

4 - GraphQL Is a Specification

Perhaps one of the greatest benefits of GraphQL is thatthe overhead for adoption is low specifically due to itsstatus as a specification.While there are always new toolson the market, many developers shy away from adoptingthese solutions because they’re “too involved” or “tooinvested” in their REST architecture.

As a specification, GraphQL is a wrapper that can bedefined — you don’t have to replace a REST system.This means that developers can reap the entirety of thebenefits of GraphQL while ignoring the cost overhead ofits incorporation.

A huge benefit of this GraphQL wrapping is also in how itchanges the relationship between data and the systemsthat require said data. Data in GraphQL isn’t limited bythe language or the datatype, and is instead limited bythe server descriptions as defined to the client (so, ineffect, not a limitation at all). Data wrapped in GraphQL,regardless of the underlying language or system, can beshared between variations in standard API schemas andthe wide range of languages which create them.

More specifically, this also means that GraphQL is funda-mentally compatible with anything that REST-centric APIsare compatible with— therefore, the entry point for bothGraphQL and its interactiveness with REST dependentsystems is relatively low.

Page 27: GraphQL or Bust · Preface:Introductionto GraphQL Withinthelastcoupleofyears,therehasbeenaresur-genceofdiscussionaroundAPIdesignstandardssuch as REST, gRPC, GraphQL, and many others

5 Potential Benefits of Integrating GraphQL 17

5 - GraphQL ImprovesUnderstanding and Organization

Perhaps the biggest benefit of implementing GraphQL isone of importance to the API ecosystem as a whole —99%of the time, anAPI can be organized into a simple andunderstandable graph schema, and doing so forces youto better organize and understand your data, the flow ofthat data, and the inefficiencies and errors in that system.

While this has a net benefit to the developer, it has hugepositive implications for the development ecosystemas a whole. Because GraphQL attaches types to data,types errors between applications and your server andGraphQL compliant applications to other applicationsstart to disappear.

What we’re talking about here is a type of “universaltranslator”, providing data translation between differentservices while removing the bottleneck typically encoun-tered, Furthermore, this removes pressure towards appli-cation developers to ensure compatibility andmutations.

A huge benefit to developers and a more positive inter-action in the ecosystem — what’s not to love?

Who Uses It

BecauseGraphQL is extremely powerful, it’s beenusedbyseveral providers who need stable readability with quickspeed and indexing. Most of the use cases for GraphQLare therefore those who require high data throughput

Page 28: GraphQL or Bust · Preface:Introductionto GraphQL Withinthelastcoupleofyears,therehasbeenaresur-genceofdiscussionaroundAPIdesignstandardssuch as REST, gRPC, GraphQL, and many others

5 Potential Benefits of Integrating GraphQL 18

with ease of sorting, which is certainly represented clearlyby its most high profile users.

One example of how powerful GraphQL is when it comesto handling high data throughput in a relational matter isHudl, a sports video analytics provider. Essentially, Hudltakes video of sporting events, practices, and other situa-tions and provides professional feedback for each playerand a general overview incorporating this feedback.

Accordingly, the data processed by Hudl is strictly rela-tional — unlike other solutions, the data being handledisn’t simple one-to-one relational data. Each player be-longs to a team, but each player has their own data whichis attached to specific activities, skills, and approaches.

In a traditional query language, comparing and contrast-ing these hugely discrepant data points between eachplayer and then each team would require a massiveamount of data combination, or at the very least, a hugerange of calls being called multiple times to each serversystem each second.

With GraphQL, each item is described clearly, and re-quested specifically by an application. GraphQL allowsfor a small range of endpoints that provide this data ina consumable, easily understandable method. This alsomeans that the data generated by Hudl isn’t strictly tiedto their application, and their application alone — sinceit’s described directly, the data can be imported into teamplanning applications or health tracking applications fortracking of physical health, performance in certain envi-ronments, and other such relational queries.

This interactiveness can be seen in another applicationof GraphQL, AlphaSights. AlphaSights can be seen as a“middle man” of sorts, but one of incredible power —

Page 29: GraphQL or Bust · Preface:Introductionto GraphQL Withinthelastcoupleofyears,therehasbeenaresur-genceofdiscussionaroundAPIdesignstandardssuch as REST, gRPC, GraphQL, and many others

5 Potential Benefits of Integrating GraphQL 19

connecting clients with experts and the services that theycan provide.While this seems simple on its face value, theunderlying data is very valuable, not just to AlphaSights,but to those they provide this data to.

The engineers at AlphaSights stated themselves the hugevalue of integrating GraphQL into their system to reducecomplexity and improve exchange of data:

“GraphQL gave us one way in, and one wayout. All data was resolved through one object,Graph::QueryType. The presence of only one ob-ject provided a much easier learning curve fornew developers looking at the code base, andthe higher level concepts each have their ownresolver making it easy to narrow down whateach term meant right down to the databaselevel. The mapping of types from a query intoruby objects is very intuitive … By making theserver to consumer contract flexible, we getthe benefit of much more agile teams, and lessdebate on how and if the consumer receivesthat data. We have also found that maintainingthe services is much easier. There are no “v2”routes to be added, and the type system allowsthe consumer to easily discover updates. Wehave also taken advantage of “GraphApi::Schema.middleware”tomonitor which attributes are being used, andhelp identify legacy types/fields that we canremove, which we are going to open source inthe future.”

Being able to not only provide data in an easy format,but to make that data easily interactable and digestibleby novice developers is a huge benefit, and makes datagenerated truly extensible.

Page 30: GraphQL or Bust · Preface:Introductionto GraphQL Withinthelastcoupleofyears,therehasbeenaresur-genceofdiscussionaroundAPIdesignstandardssuch as REST, gRPC, GraphQL, and many others

5 Potential Benefits of Integrating GraphQL 20

GraphQL isn’t only for huge complex databases, either —it can easily be used to create relatively simpledatabaseswith greater efficiency. A great example of this is Beek.io.It’s fundamentally a social network, albeit a niche one,focusing on books and those who love them. While thedatabase itself is relatively simple—author, name, genre,etc. — the way this content is handled is supremelysimplified under GraphQL.

By simplifying calls to a single entry point, you preventdifferent endpoints from providing the same data in dif-ferent ways, and increase the understandability of thedata that is delivered. Because of this, while Beek.io is arather simple incarnation of the social media sphere, itis extremely responsive, and delivers data in a way thatbook lovers can actually use to better their reading library(and perhaps their friends list).

Conclusion: Assess

While GraphQL is obviously powerful, there are somearguments against it — chiefly that it’s still in its infancy.API Evangelist sees GraphQL as a way around “properlygetting to know your API resources,” doubting whetherthe majority of non-technical API consumers will findit useful. Others have expressed that an organizationshouldn’t integrate GraphQL simply because a behemothlike Facebook or Github has a GraphQL API.

ThoughtWork’s 2017 Technology Radar, which reachesaction verdicts for emerging Techniques, Tools, Platforms,and Languages, labels GraphQL asASSES. Whether or notto adopt GraphQL should at the very least be assessed;For as we’ve seen through this chapter, it can help ensure

Page 31: GraphQL or Bust · Preface:Introductionto GraphQL Withinthelastcoupleofyears,therehasbeenaresur-genceofdiscussionaroundAPIdesignstandardssuch as REST, gRPC, GraphQL, and many others

5 Potential Benefits of Integrating GraphQL 21

data is efficiently generated and accessed, and can makethe applications powered by the server that much morepowerful and extensive.

Page 32: GraphQL or Bust · Preface:Introductionto GraphQL Withinthelastcoupleofyears,therehasbeenaresur-genceofdiscussionaroundAPIdesignstandardssuch as REST, gRPC, GraphQL, and many others

How to Wrap a REST APIin GraphQL

As we saw in the last chapter, GraphQL is a powerful tool.As with any emergent tool in the API space, however,there’s some disagreement on exactly how to implementit, and what the best practices for its implementation anduse case scenarios are.

Have no fear, dear reader — we’re here to sort this allout.We’re going to discussGraphQL, where it came from,where it’s going, and why you should consider imple-menting it. We’ll focus on how to wrap a RESTful APIwithGraphQL, and how this functions in everyday usage.

Page 33: GraphQL or Bust · Preface:Introductionto GraphQL Withinthelastcoupleofyears,therehasbeenaresur-genceofdiscussionaroundAPIdesignstandardssuch as REST, gRPC, GraphQL, and many others

How to Wrap a REST API in GraphQL 23

What is GraphQL?

For those who are unfamiliar, GraphQL is an applicationlayer query language. It interprets a string from a serveror client, returning the data in a pre-defined schema asdictated by the requester. As the GraphQL official sitestates: “Describe your data, ask for what you want, getpredictable results.”

The way data is requested is quite clean and elegant. Thefollowing is a valid data descriptor:

type Project {

name: String

tagline: String

contributors: [User]

}

When this is requested as such:

project(name: "GraphQL") {

tagline

}

}

It returns a clean, easy, and simple result:

{

"project": {

"tagline": "A query language for APIs"

}

}

Page 34: GraphQL or Bust · Preface:Introductionto GraphQL Withinthelastcoupleofyears,therehasbeenaresur-genceofdiscussionaroundAPIdesignstandardssuch as REST, gRPC, GraphQL, and many others

How to Wrap a REST API in GraphQL 24

A GraphQL implementation results in more elegant dataretrieval, greater backend stability,more efficient queries,and improved organization with a language that has lowadoption overhead. With this being said, let’s get into themeat of how exactly we can implement GraphQL in aRESTful API.

Defining a Schema

The first step to wrapping a RESTful API is to define aschema. Schemas are essentially like phonebooks — astated, common methodology of recognizing and orga-nizing your data and the interactions concerning saiddata.

When properly wrapped, a RESTful API will funnel allinflux andoutflux of data through the schema itself— thisis the main power of the GraphQL system, and is whereit gets its universality.

In following with the official GraphQL documentation, theimplementation we’re going to show today is simplified,with some issues in terms of performance against morecomplex and time-consuming alternative implementa-tions. This solution, however, requires no architectural orserver augmentations, and is a perfect stepping off pointthat we can take to move forward.

The implementation as suggested by the GraphQL docu-mentation is as follows:

Page 35: GraphQL or Bust · Preface:Introductionto GraphQL Withinthelastcoupleofyears,therehasbeenaresur-genceofdiscussionaroundAPIdesignstandardssuch as REST, gRPC, GraphQL, and many others

How to Wrap a REST API in GraphQL 25

import {

GraphQLList,

GraphQLObjectType,

GraphQLSchema,

GraphQLString,

} from 'graphql';

const BASE_URL = 'https://myapp.com/';

function fetchResponseByURL(relativeURL) {

return fetch(`${BASE_URL}${relativeURL}`).then(res => r\

es.json());

}

function fetchPeople() {

return fetchResponseByURL('/people/').then(json => json\

.people);

}

function fetchPersonByURL(relativeURL) {

return fetchResponseByURL(relativeURL).then(json => jso\

n.person);

}

const PersonType = new GraphQLObjectType({

/* ... */

fields: () => ({

/* ... */

friends: {

type: new GraphQLList(PersonType),

resolve: person => person.friends.map(getPersonByUR\

L),

},

}),

});

Page 36: GraphQL or Bust · Preface:Introductionto GraphQL Withinthelastcoupleofyears,therehasbeenaresur-genceofdiscussionaroundAPIdesignstandardssuch as REST, gRPC, GraphQL, and many others

How to Wrap a REST API in GraphQL 26

const QueryType = new GraphQLObjectType({

/* ... */

fields: () => ({

allPeople: {

type: new GraphQLList(PersonType),

resolve: fetchPeople,

},

person: {

type: PersonType,

args: {

id: { type: GraphQLString },

},

resolve: (root, args) => fetchPersonByURL(`/people/\

${args.id}/`),

},

}),

});

export default new GraphQLSchema({

query: QueryType,

});

What this schema is basically doing is attaching JavaScriptmethods to the variables, and establishing themethodol-ogy by which the data is returned. The beginning and endis a necessary statement — the import of the GraphQLstrictures, and the export of theGraphQL schemaproper:

import { GraphQLSchema } from 'graphql';

export default new GraphQLSchema({

query: QueryType,

});

By establishing two constants— a data type, and a query

Page 37: GraphQL or Bust · Preface:Introductionto GraphQL Withinthelastcoupleofyears,therehasbeenaresur-genceofdiscussionaroundAPIdesignstandardssuch as REST, gRPC, GraphQL, and many others

How to Wrap a REST API in GraphQL 27

type — data is collated internally through the API, whileallowing for fetching given a specific set of argumentsgiven by the requester:

const PersonType = new GraphQLObjectType({

/* ... */

fields: () => ({

/* ... */

friends: {

type: new GraphQLList(PersonType),

resolve: person => person.friends.map(getPersonByUR\

L),

},

}),

});

const QueryType = new GraphQLObjectType({

/* ... */

fields: () => ({

allPeople: {

type: new GraphQLList(PersonType),

resolve: fetchPeople,

},

person: {

type: PersonType,

args: {

id: { type: GraphQLString },

},

resolve: (root, args) => fetchPersonByURL(`/people/\

${args.id}/`),

},

}),

});

What this functionally does is establish the data and ac-cepted query methodology for email, id, and username, and

Page 38: GraphQL or Bust · Preface:Introductionto GraphQL Withinthelastcoupleofyears,therehasbeenaresur-genceofdiscussionaroundAPIdesignstandardssuch as REST, gRPC, GraphQL, and many others

How to Wrap a REST API in GraphQL 28

resolves the data by accessing the properties of the person

object as attached in the code. While this technique relieson some functionality in Relay, a companion to GraphQLoften considered inseparable, the principle remains thesame — predictable, queryable data.

Of note for this approach, however, is the fact that thetypes in questionwere hand-defined.While this works forsmall systems, it’s not a tenable solution for larger APIs.In such a case, solutions like Swagger can define typedefinitions automatically, which can then be “typified” forthe GraphQL schema with relative ease.

Alternatives to this Method

Thankfully, there are some very enterprising developerswho have taken GraphQL to its logical extent, automat-ing the process of creating the schema itself. One suchsolution is the graphql-rest-wrapper. Designed to easilycreate wrapped REST APIs, this technique is simple toemploy:

const wrapper = new gqlRestWrapper('http://localhost:9090\

/restapi', {

name: 'MyRestAPI',

generateSchema: true,

saveSchema: true,

graphiql: true

})

app.use('/graphql', wrapper.expressMiddleware())

This solution is rather simple, but elegant in how it han-dles the schema production. The “gqlRestWrapper” class

Page 39: GraphQL or Bust · Preface:Introductionto GraphQL Withinthelastcoupleofyears,therehasbeenaresur-genceofdiscussionaroundAPIdesignstandardssuch as REST, gRPC, GraphQL, and many others

How to Wrap a REST API in GraphQL 29

creates a GraphQL schema from the REST response. In away, this is similar to a game of telephone, wherein themiddle man takes the data being passed through, anddefines it into a usable schema for future interaction.

A few steps need to be taken. First, the npmpackagemustbe installed. Then, it needs to be imported. Finally, thecode function as stated above needs to be instantiated:

npm i graphql-rest-wrapper

var gqlRestWrapper = require(graphql-rest-wrapper)

new gqlRestWrapped([apiEndpoint], [variableOptions])

Then, middleware, or the interpreter in the telephonegame, needs to be attached to the route proper:

app.use([ROUTE], wrapper.expressMiddleware())

And finally, an HTTP GET/POST request can be made:

fetch("http://localhost:9090/graphql",

{

headers: {

'Accept': 'application/json',

'Content-Type': 'application/json'

},

method: "POST",

body: "{'query': 'query { MyRestAPI { id, name } \

}'}"

})

.then(function (res) {

console.log(res);

})

Page 40: GraphQL or Bust · Preface:Introductionto GraphQL Withinthelastcoupleofyears,therehasbeenaresur-genceofdiscussionaroundAPIdesignstandardssuch as REST, gRPC, GraphQL, and many others

How to Wrap a REST API in GraphQL 30

The benefit of this style of wrapping is that it’s entirelyautomated when properly organized. Whereas the firstprocess is entirely by hand, the second process is entirelyhandled by an automatic and effective system. This lendsitself to problems that the hand-coded method misses,of course — principally, the fact that more complex codecan be missed or result in broken schemas.

To Wrap or Not to Wrap

Of course, this begs the question — should we reallybe wrapping a RESTful API in GraphQL in the firstplace? This assumes that the API in question is beingleft in REST for the sole purpose that development of aGraphQL compliant endpoint over a series of hundredsof use cases would be an unworthy time sink.

That may not be true, however, when one considers thelengths to which a provider must go in order to get whatthey want out of their API. It may simply be more usefulto code a GraphQL compliant series of endpoints ratherthan try to wrap an API in a new skin.

This isn’t an all or nothing proposition, either. At theNordic APIs 2016 Platform Summit, Zane Claes spoke onthemovement from an internal, legacy, monolithic API, toamore consistent group of API functionalities that serveddata given specific devices, specific use cases, and specificrequirements.

It is entirely possible to use a legacy API for a time, andslowly migrate to a GraphQL compliant API, rather thanwrapping an existing API as a “stop gap”. What we’retalking about here is the difference between a band-

Page 41: GraphQL or Bust · Preface:Introductionto GraphQL Withinthelastcoupleofyears,therehasbeenaresur-genceofdiscussionaroundAPIdesignstandardssuch as REST, gRPC, GraphQL, and many others

How to Wrap a REST API in GraphQL 31

aid and a full-blown hip replacement — the extent ofdifficulty may not be known until it’s actually attempted.

Conclusion: Wrap or Recode

Thankfully, the methodology of wrapping an existing APIcomes down to how complicated the situation is. Formost API providers, a simple wrapping as stated abovewould work, with the automated solution being entirelyacceptable.

For others, however, especially APIs that are simplymono-lithic, the process of re-coding an API to be GraphQLcompliant is a more effective choice.

Page 42: GraphQL or Bust · Preface:Introductionto GraphQL Withinthelastcoupleofyears,therehasbeenaresur-genceofdiscussionaroundAPIdesignstandardssuch as REST, gRPC, GraphQL, and many others

Best Practices for AHealthy GraphQLImplementation

We’ve discussed GraphQL at length previously – andwhile the discussions on how GraphQL works are obvi-ously very powerful, we’ve yet to dive into some of thebest practices that should be adopted when developinga GraphQL-centric API.

Today, we’re going to do exactly that. We’re going to dis-cuss the best practices for healthy GraphQL implemen-tation, and describe why these practices are so advised.By properly integrating these best practices as a matterof course, your GraphQL-driven implementation and itsassociated API structure can be more powerful, efficient,and practical.

Page 43: GraphQL or Bust · Preface:Introductionto GraphQL Withinthelastcoupleofyears,therehasbeenaresur-genceofdiscussionaroundAPIdesignstandardssuch as REST, gRPC, GraphQL, and many others

Best Practices for A Healthy GraphQL Implementation 33

Dogma vs Practices

Before we dive too heavily into this, it must be said —these are suggested best practices, not absolute dogma.While the majority of the practices herein are applicableto most API installation, use case, and design, there aresome situations in which your API design or applicationwill not work well with some aspects of GraphQL, whilerequiring other aspects of it.

In such cases, these best practices should be considereda guideline, not a dogmatic instruction on how GraphQLshould be implemented.

URIs and Routes

While GraphQL is fundamentally RESTful, it does dropsome elements that have become core to RESTful de-sign, such as resources. Wherein most REST APIs useresources as a basic conceptualization for how data isprocessed and returned, GraphQL eschews this and in-stead depends on entities as defined by an entity graph.This entity graph drives all traffic to a single URL orendpoint, which is the forward facing entrance into thesystem.

Accordingly, URIs and routes should all lead back to asingle endpoint — this is the fundamental use case ofGraphQL, and is principle in its functionality.

Page 44: GraphQL or Bust · Preface:Introductionto GraphQL Withinthelastcoupleofyears,therehasbeenaresur-genceofdiscussionaroundAPIdesignstandardssuch as REST, gRPC, GraphQL, and many others

Best Practices for A Healthy GraphQL Implementation 34

Endpoint Collation and HTTP

By its nature, GraphQL serves verb requests over a singleendpoint in HTTP. This aspect of GraphQL is fundamentalto its design and approach towards endpoint collation— as such, using a methodology other than a collatedendpoint in HTTP is locking a lot of functionality away.

In classic REST format, resources are exposed via a suiteof URLs, and each URL has a specified endpoint that istied into as part of the formatted request. While GraphQLcan certainly co-exist with this kind of setup, having sucha collection of resources behind URIs defies the purposeof GraphQL implementation in the first place.

Accordingly, if you need to adopt such a practice of hy-brid linking (aka a single collated point and then a groupof URLs representing individual resources), it would beadvisable to look into your design, schema, and format,and address whether or not this is actually intendedbefore proceeding with such a system in GraphQL.

API Versioning

GraphQL is a schema, and as such, there’s nothing stop-ping your API from versioning however it desires. Thatbeing said, GraphQL has stated a strong avoidance ofversioning from a philosophical standpoint. GraphQL’sstated viewpoint is as follows:

“Why do most APIs version? When there’s lim-ited control over the data that’s returned froman API endpoint, any change can be considereda breaking change, and breaking changes re-quire a new version. If adding new features to

Page 45: GraphQL or Bust · Preface:Introductionto GraphQL Withinthelastcoupleofyears,therehasbeenaresur-genceofdiscussionaroundAPIdesignstandardssuch as REST, gRPC, GraphQL, and many others

Best Practices for A Healthy GraphQL Implementation 35

an API requires a new version, then a tradeoffemerges between releasing often and havingmany incremental versions versus the under-standability and maintainability of the API.”

Accordingly, GraphQL takes the view that, since the so-lution only returns explicitly requested data, there’s nosuch thing as a “breaking change” in properly designedGraphQL APIs. This is a definite shift from versioned APIto versionless, and is part of the design ethos of GraphQLitself.

That’s not to say of course that versioning needs to bean all or nothing practice. It’s very easy to simply versionby documenting changes and referring to the API by astated version number – this is much more an internalorganizational consideration, though, and as thus fallsoutside of the common definition of true versioning. Assuch, it’s better to call this a revision process rather thana versioning process.

Nullability and Default Typing

APIs typically handle nullability in two steps: with a “null”common type, and then a “nullable” version of that type,specifically to separate the two types from one anotherwhile allowing for nullification by specific declaration ofsaid type. This is all well and good, and in fact is a goodpractice in and of itself, but because of how GraphQL isstructured and defined, this actually does not work withinthe schema.

Accordingly, the best practice for nullification in GraphQLis to remember that this null type is in fact a default

Page 46: GraphQL or Bust · Preface:Introductionto GraphQL Withinthelastcoupleofyears,therehasbeenaresur-genceofdiscussionaroundAPIdesignstandardssuch as REST, gRPC, GraphQL, and many others

Best Practices for A Healthy GraphQL Implementation 36

setting for every single field. This was integrated intoGraphQL as a methodology for managing failures froma variety of internal and external causes, and as such,works well for its intended purposes.

As a corollary to this, keep in mind that if a non-null valueis required, it can be set as a non-null type — regard-less, it’s important to remember this default nullabilityapproach when addressing issues in the return stage ofdata retrieval.

Pagination

Pagination in GraphQL is almost entirely the purviewof the developer. GraphQL allows for listed values as areturn, and as those listed values grow in length, how theyare returned is dictated by the strictures created by theAPI owner themselves.

GraphQL allows for a pattern known as “Connections.”This element of GraphQL allows for not only discoveringinformation about specific related items, but about therelationships themselves. Adopting Collections is a bestpractice, as it ties into other GraphQL suites and toolslike Relay, which can automatically support client-sidepagination in that common format.

JSON and GZIP Dependency

GraphQL is designed to respond to requests using JSON.Despite this, it’s not expressly required in the specifica-tion, and in fact GraphQL can work with a variety of re-sponse types. That being said, it’s a best practice to adopt

Page 47: GraphQL or Bust · Preface:Introductionto GraphQL Withinthelastcoupleofyears,therehasbeenaresur-genceofdiscussionaroundAPIdesignstandardssuch as REST, gRPC, GraphQL, and many others

Best Practices for A Healthy GraphQL Implementation 37

JSON due to its text-centric organization, as GraphQL isdesigned expressly toworkwith high-ratio GZIP compres-sion.

Interestingly, GraphQL is designed with the syntax ofJSON in mind, and as such, it is a good idea to keepthis syntax consistent through both design and response.Likewise, GraphQL suggests that clients respond with thefollowing appended in the header:

Accept-Encoding: gzip

This will allow for even further compression of the re-sponse data, and should result in lower overhead andgreater network performance. You don’t necessarily haveto adopt JSON, especially if you are adopting GraphQLafter your API has already been designed and given aspecified output format, but failure to adopt JSON canresult in decreased efficiency and confusion amongstthe user base when comparing output with the code thatgenerates said output.

Batching to Address Chattiness

GraphQL is, by default, extremely chatty. This is simplydue to how GraphQL is formed, how the data is collectedand returned, and how the server address requests. Thischattiness can be a hindrance, especially when doinglarge scale data requests from a database.

Under GraphQL, the solution is to simply batch theserequests over a given period of time, collating them, andthen submitting themultiple requests as a single, collatedrequest to the system in question.

Page 48: GraphQL or Bust · Preface:Introductionto GraphQL Withinthelastcoupleofyears,therehasbeenaresur-genceofdiscussionaroundAPIdesignstandardssuch as REST, gRPC, GraphQL, and many others

Best Practices for A Healthy GraphQL Implementation 38

This in turn eliminates much of the chattiness, as youare no longer issuing multiple packed, collated requeststo multiple elements of a GraphQL enabled server —instead, you are bundling bundles of requests, resultingin a passive GraphQL into GraphQL solution that createsa relatively “quiet” system for the amount of data that isbeing requested.

This does not have to be enabled, of course, and forsmaller projects, it mightmake sense not to do so, so thatissues in requesting can be identified and singled out.That being said, when handling any substantial amountof data, adopting batching is probably a good idea.

GraphQL is designed in a way that allows you to writeclean code on the server, where every field on every typehas a focused single-purpose function for resolving thatvalue. However without additional consideration, a naiveGraphQL service could be very “chatty” or repeatedly loaddata from your databases.

Of note: GraphQL suggests that some of thisbatching can be done using GraphQL toolssuch as DataLoader. While this is absolutelyan acceptable method, adopting batching in-ternally as part of your codewill bemore pow-erful than any third party tool can ever be, andif needed, should very much be implementedas part of the base architecture.

Disabling GraphiQL in ProductionEnvironments

GraphiQL is a big selling point formanyGraphQLadoptees,

Page 49: GraphQL or Bust · Preface:Introductionto GraphQL Withinthelastcoupleofyears,therehasbeenaresur-genceofdiscussionaroundAPIdesignstandardssuch as REST, gRPC, GraphQL, and many others

Best Practices for A Healthy GraphQL Implementation 39

but even though it’s extremely powerful, it should be dis-abled in production. This recommendation comes fromthe official GraphQL documentation. GraphiQL should bedisabled due to various vulnerabilities that could inadver-tently expose internal API functionality by exploring theprimary forward-facing endpoint. Enabling GraphiQL es-sentially negatesmany of the reasons you are integratingGraphQL in the first place.

GraphQL Authorization Practices

GraphQL specifically notes in its specification documen-tation that all authorization must be done in the busi-ness logic layer. This is specified due to how GraphQLfunctions. Using authorization logic that checks for ele-ments of the entry point validation process, such as “hasauthor ID” or “carries correct token” would mean that, forevery possible entry point, this logic would have to beduplicated, which leads to incredibly complex implemen-tations for even small amounts of authorization controls.

Accordingly, GraphQL dictates that this should be done atthe business logic layer so that the authorization controlsonly need to be specified once for the entirety of thatspecific class. GraphQL notes that this is fundamentallyconsidered having a “single source of truth for authoriza-tion.”

GraphQL Pipeline Model

As part of this approach towards Authorization, GraphQLadvises that all authentication middleware should comebefore the GraphQL implementation to avoid the same

Page 50: GraphQL or Bust · Preface:Introductionto GraphQL Withinthelastcoupleofyears,therehasbeenaresur-genceofdiscussionaroundAPIdesignstandardssuch as REST, gRPC, GraphQL, and many others

Best Practices for A Healthy GraphQL Implementation 40

issues with authentication. Any filters, plugins, extensions,etc. should all be placed before GraphQL to allow sessionand user information in its final form for granular andsingular control.

Conclusion

As stated at the beginning of this piece, we’ve aimed toshare advice rather than dogma when we discuss thesebest practices. The best practice of all is to adopt so-lutions that fit with your specific use case. Considerthese GraphQL best practices as guidelines rather thanset-in-stone rules, but for the most part, adopting thesebest practices and implementing GraphQL as designedwill lead to a more powerful, leaner, and more efficientsystem. Failure to adhere can result in many of the ben-efits to GraphQL disappearing as quickly as your numberof endpoints.

Page 51: GraphQL or Bust · Preface:Introductionto GraphQL Withinthelastcoupleofyears,therehasbeenaresur-genceofdiscussionaroundAPIdesignstandardssuch as REST, gRPC, GraphQL, and many others

Security Concerns toConsider Before

Implementing GraphQL

GraphQL is a very powerful query language that doesa great many things right. When implemented properly,GraphQL offers an extremely elegant methodology fordata retrieval,more backend stability, and increasedqueryefficiency.

The key here though is that simple phrase — “whenimplemented properly”. GraphQL has had somewhat of agold rush adoption, with smaller developers respondingto the media hype and big name early adopters withtheir own implementations. The problem is, many peo-ple aren’t considering what adopting GraphQL actuallymeans for their system, and what security implications

Page 52: GraphQL or Bust · Preface:Introductionto GraphQL Withinthelastcoupleofyears,therehasbeenaresur-genceofdiscussionaroundAPIdesignstandardssuch as REST, gRPC, GraphQL, and many others

Security Concerns to Consider Before Implementing GraphQL 42

come with this adoption.

GraphQL is a paradigm shift in many ways — and withthat, security concerns have changed. While some secu-rity concerns have gone away, replaced by architecturaldifferences and nuances, other concerns have been am-plified.

In this piece, we’re going to talk about those issues,highlighting some general concerns in regards to securityin an API system supporting GraphQL. While GraphQLitself is not the primary driver of these concerns, theseissues should be addressed within the greater frameof a GraphQL system, and all of the implications thatsuggests.

GraphQL - A Summary

Quickly, let’s summarize what GraphQL is, and how itdoes what it does. Simply put, GraphQL is an applicationlayer query language designed to interpret a string froma server or client, and return that data to the requestingclient in the form that they request.

GraphQL was developed by Facebook as a means totransition away from HTML5 applications on mobile to-wards robust, native applications. This was facilitated byallowing easier backend queries through the unificationof multiple interior endpoints to a single forward facingendpoint.

With that in mind, what are some concerns in regards tosecurity and best practices in terms of GraphQL?

Page 53: GraphQL or Bust · Preface:Introductionto GraphQL Withinthelastcoupleofyears,therehasbeenaresur-genceofdiscussionaroundAPIdesignstandardssuch as REST, gRPC, GraphQL, and many others

Security Concerns to Consider Before Implementing GraphQL 43

Implied Documentation vs. ActualDocumentation

Another serious concern when implementing GraphQL ishowdocumentation is handledbetween versions. GraphQLdoes not have versioning support in the same way othersystems do. That’s not to say that you can’t version inGraphQL, but simply that by design, GraphQL is designedto API evolution without version control being required.

While this is certainly a fair approach, there are a goodnumber of developers who depend on versioning to com-municate changes in field values, endpoints, and declara-tions. While this is not good practice, that doesn’t stopit from being relatively common — and unfortunately,when GraphQL is brought into the mix, the issue onlybecomes worse.

Let’s say an API changes a fundamental endpoint or in-ternal construct. In a traditional API, this change wouldbe documented as a version change, with in-built doc-umentation as such. In GraphQL implementations, thisisn’t the case, and so many developers might learn aboutthis deprecated endpoint or construct by attempting touse it, and being turned away.

So what’s the security issue here? The problem is that,without proper documentation, you can very quickly runinto a situation where an endpoint is no longer valid, butdata is still being sent and requested from that endpoint.This can result in collisions and unintended functionality.More to the point, if your application is still attempting topoll a non-existent GraphQL endpoint, an emulated end-point from aman-in-the-middle attack could theoreticallystep almost seamlessly into the data stream.

Page 54: GraphQL or Bust · Preface:Introductionto GraphQL Withinthelastcoupleofyears,therehasbeenaresur-genceofdiscussionaroundAPIdesignstandardssuch as REST, gRPC, GraphQL, and many others

Security Concerns to Consider Before Implementing GraphQL 44

There aremanyways tomitigate this, and adopting a con-tinuous versioning strategy is absolutely paramount as asolution. That being said, this is much more a problemwith developer practices than GraphQL itself. That com-ment aside, the issue dramaticallymagnified byGraphQL,and should be considered prior to any GraphQL imple-mentation.

Unified Failures

Perhaps the biggest issue with a GraphQL implementa-tion is inherent in the approach itself. GraphQL has theextremely powerful ability to unify multiple endpointsinto a single queryable point — this is the entire cruxof what makes GraphQL powerful. The problem here,though, is in the fact that a single endpoint, even if itconnects to multiple internal endpoints, functions as asingle point to the consumer.

We often tend to think of APIs from an “interior to edge”way — we think from the code base out to the consumerexperience. Typically, this is fine, as the consumer is asingle point accessing multiple endpoints, which thencall multiple functions, which might relay to even moredatabases or resources.Whenwe’re talking aboutGraphQL,however, we’re actually creating an “interior to edge tointerior” style system, in which the codebase narrows toa single point or collection of single points, which thenexpands to the user.

In a poorly defined GraphQL request from the consumer(or, for that matter, a poorly formed GraphQL endpointdefined by the developer), a single failure means a total

Page 55: GraphQL or Bust · Preface:Introductionto GraphQL Withinthelastcoupleofyears,therehasbeenaresur-genceofdiscussionaroundAPIdesignstandardssuch as REST, gRPC, GraphQL, and many others

Security Concerns to Consider Before Implementing GraphQL 45

failure to access internal resources. If improperly ab-stracted, documented, and specified, you’re essentiallyputting all your eggs in a basket.

Functionally speaking, this entire issue could be summedup thusly: call failures equate to insecurity for the devconsumer. Minimizing these failures is an entire industryin and of itself, and poorly adopting GraphQL negatesmuch of the efforts developers have made to this end.

Data and Server TransactionVolumes

GraphQL has another fundamental problem related toits foundational aspects — queries are often larger andmore complex than in traditional REST APIs. In GraphQL,a single request might combinemultiple requests tomul-tiple endpoints, resulting in an unpredictable amount ofdata for each request over time.

Consumers are in control of their requests — and insome ways, this is dangerous. Not every provider is goingto have huge scalable infrastructure or cloud serverson retainer, and thus not every provider is going to becomfortable with the idea of allowing for variable contentrequests based on the whim of a user.

There’s also the concern of limiting the actual requestin a reasonable way. Consumers aren’t always the mostjudicious with their requests — sometimes, a consumermay request more data than they really need, and over along time and large amount of requests, this adds up tosignificant overhead that did not exist in a non-GraphQLsolution.

Page 56: GraphQL or Bust · Preface:Introductionto GraphQL Withinthelastcoupleofyears,therehasbeenaresur-genceofdiscussionaroundAPIdesignstandardssuch as REST, gRPC, GraphQL, and many others

Security Concerns to Consider Before Implementing GraphQL 46

Information Hiding and Chattiness

Let’s get this out of the way first — neither GraphQL orREST enforces any significant amount of data hiding. Theproblem with GraphQL specifically comes when peoplerush to adopt it, and instead of logically thinking outthe mapping of public endpoints to private models, theysimply map a 1:1 relationship.

While this is functional, it’s incredibly dangerous. Theentire point of GraphQL is to allow the client to requestthe data the way that they want it to be requested —but this also means that GraphQL enables data in a waythat may not be intended, and when 1:1 relationshipsare established, you lose some very important control ofinternal assets.

This is, just as with any REST API, entirely manageablewith proper GraphQL schema design. Third party clientsand APIs should be able to interact with your GraphQLendpoint without knowing the internal workings of theAPI.

GraphQL can be done in a way to have this be a limitationof the endpoint, but this comes with the threat of arushed adoption, possibly resulting in exposing muchmore than was intended. Depending on how GraphQL isset up and how queries are handled, the actual endpointsdefined can insist on “chattiness”, rather than allow it.

This isn’t just a matter of schema revelation, either. Whenan endpoint unifies multiple internal endpoints and func-tionalities, this endpoint can be improperly implementedto retrieve farmore data thanwas ever intended. This hassome serious implications.

First, there is the server implication. If the data is being

Page 57: GraphQL or Bust · Preface:Introductionto GraphQL Withinthelastcoupleofyears,therehasbeenaresur-genceofdiscussionaroundAPIdesignstandardssuch as REST, gRPC, GraphQL, and many others

Security Concerns to Consider Before Implementing GraphQL 47

retrieved first and then stripped of irrelevant data beforebeing transferred to the client, we’re being extremelywasteful. Imagine if every single time you want to drive,you had to burn an entire tank of petrol, regardless ofdistance travelled.

In some cases, this would make sense — a two hundredmile trip would easily eat through your tank, and possiblymore. For a short trip, this would be absolutely wasteful,and over time, would lead to excessive wear and tear.

The same is true on the server side — limiting this chatti-ness is incredibly important.

Then there is the aforementioned security internal expo-sure issue. This has already been somewhat discussed,but it bears repeating—allowing for unlimited access to avariety of endpoints in amanipulatable way is the perfectstorm for penetration testing, and makes identifying thestructure and scheme of the backend trivial in manycases.

Authorization and GraphQL

Another point of potential issue is improper implementa-tion of authorization in GraphQL-dependent APIs. Again,this is much less an issue with GraphQL itself, and morean issue with adoption.

In GraphQL, authentication can be handled handled us-ing “query context”. The basic idea here is that the requestcan be injected with arbitrary code that is then passedthrough to the request, which allows very fine, granularcontrol of authorization by the developer proper. Thisis a very secure system – it’s arguably much stronger

Page 58: GraphQL or Bust · Preface:Introductionto GraphQL Withinthelastcoupleofyears,therehasbeenaresur-genceofdiscussionaroundAPIdesignstandardssuch as REST, gRPC, GraphQL, and many others

Security Concerns to Consider Before Implementing GraphQL 48

than other solutions when it comes to SQL injection andLangsec issues.

The problem comes with developers not actually under-standing that this is a possibility. Developersmight look attheir current authorization logic, decide they don’t wantto change anything fundamentally, and instead insertthis logic into the GraphQL layer itself rather than thebusiness logic layer.

This is fundamentally flawed, and is advised against inthe GraphQL specification itself. Placing this logic in theGraphQL layer opens the security system up to codeinjection, sniffing, and other attacks that could easilyexpose the internal authorization structure, thereby ren-dering it null.

Measured Optimism

This isn’t to say that GraphQL is a poor choice, or that youshould be wary of implementing it. Quite the opposite, infact—proper implementation of GraphQL is possibly oneof the best things that can be done for a large API with avariety of data on the backend that must be delivered ina sensible, consumer-controlled way.

What this is to say, though, is that our optimism shouldbe tempered. As with any new technology or implemen-tation, we need to prove that the theoretical is provable inthe actual implementation.With somany potential issuessprouting from improper implementation, it’s incrediblyimportant for developers to look at GraphQL in the frameof “how do I make sure I do this right” rather than “movefast and break things”.

Page 59: GraphQL or Bust · Preface:Introductionto GraphQL Withinthelastcoupleofyears,therehasbeenaresur-genceofdiscussionaroundAPIdesignstandardssuch as REST, gRPC, GraphQL, and many others

Security Concerns to Consider Before Implementing GraphQL 49

We’re not alone in this advice for measured optimism,either.

ThoughtWorks, a software company which delivers ver-dicts to the industry on new technologies, advised thatdevelopers should “assess” whether or not GraphQL isthe correct solution given their use case. API EvanelistKin Lane was likewise cautious, stating that during aconversation in the API Evangelist Slack channe:

“the consensus seemed to be that GraphQL isa way to avoid the hard work involved withproperly getting to know your API resources,and it is just opening up a technical windowto the often messy backend of our database-driven worlds.”

The simple fact is that, as with any solution, we need tobe cautious and ensure the following:

We are using GraphQL for an appropriate use, and notadopting it in the “flavor of the week” mentality; Ourendpoints are well documented, with secondary paths inthe case of failure; We are properly hiding the internalschema and structure of our server; Finally, we are limit-ing the amount of interactions allowed to a “reasonable”measure.

If andwhen these situations are validated, GraphQLmakesfor an amazing implementation.

Page 60: GraphQL or Bust · Preface:Introductionto GraphQL Withinthelastcoupleofyears,therehasbeenaresur-genceofdiscussionaroundAPIdesignstandardssuch as REST, gRPC, GraphQL, and many others

7 Unique Benefits ofUsing GraphQL inMicroservices

We’ve talked about GraphQL at length previously, andfor very good reason – GraphQL is, in many ways, oneof the more powerful tools an API provider has in termsof providing singular endpoints to the consumer andcontrolling data flow. While this value has been proventime over time, however, it seems that some of the moresalient and special benefits of adopting GraphQL areoften lost in the conversation.

Today, we’re going to talk about these unique benefits,and what they actually mean to a production API. Manyare familiar with microservices, so in this piece we’lldiscover positive impacts GraphQL brings a microser-

Page 61: GraphQL or Bust · Preface:Introductionto GraphQL Withinthelastcoupleofyears,therehasbeenaresur-genceofdiscussionaroundAPIdesignstandardssuch as REST, gRPC, GraphQL, and many others

7 Unique Benefits of Using GraphQL in Microservices 51

vices arrangement, such as data owner separation, gran-ular data control, parallel execution, service caching, andmore.

Clearly Separated Data Owners

One of the main benefits of having everything behinda single endpoint is that data can be routed more ef-fectively than if each request had its own service. Whilethis is the often touted value of GraphQL, a reduction incomplexity and service creep, the resultant data structurealso allows data ownership to be extremely well defined,and clearly delineated.

This is in large part because the request itself is pointedtowards a single endpoint, and that request must pack-age the expected data format and the resource ownerdesignation, whether it be for a specific function or aspecific data type, is thus intrinsically tied to that request.

This is different from a typical REST API, in which therequest to each microservice might be requesting datathat themicroservice endpoint doesn’t support or cannotdeliver, which would then be passed on to another end-point, and so on. This ends up creating a web of requestsand passed communication, and to the average viewer,who actually owns the requested resource is thus hardto decipher.

Page 62: GraphQL or Bust · Preface:Introductionto GraphQL Withinthelastcoupleofyears,therehasbeenaresur-genceofdiscussionaroundAPIdesignstandardssuch as REST, gRPC, GraphQL, and many others

7 Unique Benefits of Using GraphQL in Microservices 52

Data Load Control Granularity

Another benefit of adopting GraphQL is the fact that youcan fundamentally assert greater control over the dataloading process. Because the process for data loadersgoes into its own endpoint, you can either honor the re-quest partially, fully, or with caveats, and thereby controlin an extremely granular way how data is transferred.

In many ways, this granularity is what REST has tried toachieve with some degree of success when implementingspecific schemas and request forms. That being said,GraphQL integrates this as a specific structural elementof how it works, and as such, does so much more effec-tively than most other solutions.

Parallel Execution

Because a single GraphQL request can be composed ofmany requested resources, and because GraphQL canchoose dynamically when, how, and to what extent aresponse is issued to such a request bundle, GraphQLcan leverage a sort of parallel execution for resourcerequests. What this functionally results in is the ability forGraphQL requests to partially fail, but for the responseto deliver more useful data to more requests in a singleissuance.

This ultimately has the benefit of allowing a single re-quest, even when partially failed, to serve the place ofwhat would traditionally be multiple requests to multipleservices over multiple servers. This also allows a singlerequest to use a relatively more restrained amount of

Page 63: GraphQL or Bust · Preface:Introductionto GraphQL Withinthelastcoupleofyears,therehasbeenaresur-genceofdiscussionaroundAPIdesignstandardssuch as REST, gRPC, GraphQL, and many others

7 Unique Benefits of Using GraphQL in Microservices 53

processor time and power to deliver the same amountof information that would otherwise be required of thosemultiple requests, thereby delivering greater power withless requirements.

“Instead of having six sequential calls, what [aparallel dataloader] will do is give you all sixIDs in one go, so you can make one requestinstead of six. This will make your downstreamdatabases and APIs way happier – no one willbe on fire, no one getting paid at 2 am in themorning.” -Tomer Elmalem

Request Budgeting

In GraphQL, requests can be given a “maximum execu-tion time”, and this value can then be used to budgetrequests. Each request is given a value, and from that, theserver budget is calculated and calls are prioritized. As anexample, let’s assume our server has a total budget of 2seconds, and look at a sample batch of requests.

We receive four requests – one is a single second, twoof them half a second, and the final request a full twoseconds. When budgeting our requests, the GraphQLserver can accept the first three requests, and eitherdelay or refuse the last request, as it would exceed theallotted time that the server has open for requests of itsnature.

What this in effect does is allow the server to prioritizerequests and grant them where appropriate, which endsup reducing timed out requests in the long run. Addition-ally, this system can return information to the requester

Page 64: GraphQL or Bust · Preface:Introductionto GraphQL Withinthelastcoupleofyears,therehasbeenaresur-genceofdiscussionaroundAPIdesignstandardssuch as REST, gRPC, GraphQL, and many others

7 Unique Benefits of Using GraphQL in Microservices 54

– such as would be the case with a 6 second request, forinstance – that can then inform the user to break theirrequests into smaller pieces or wait for a low-budget timeto make the request.

“[As an example] we set the maximum bud-get to one second. Some sleep function takesabout half a second, and we’ve got about halfa second in budget remaining. […] Our budgetis one second, but we have some function thattakes a second and a half, so we’re actuallynegative 500 milliseconds in terms of budget– so everything downstream fails. If this hap-pens on the first service call, then we can skipexecuting the next 6 calls [which avoids] a lotof wasted processing power when requests aretiming out.”

Powerful Query Planning

Combining twoof thesemajor benefits – parallel requestsand budgeting – allows us tomore effectively plan out ourquery schedules. By being able to send some queries toan endpoint, and have others execute in parallel at a latertime per their weight and processor demand, you caneffectively plan out those queries over a relatively broadset of criteria and per the time allotted.

While this seems simple, the ability to plan out queriesover time and address per priority is one of the elementsof GraphQL that is so incredibly powerful.

Page 65: GraphQL or Bust · Preface:Introductionto GraphQL Withinthelastcoupleofyears,therehasbeenaresur-genceofdiscussionaroundAPIdesignstandardssuch as REST, gRPC, GraphQL, and many others

7 Unique Benefits of Using GraphQL in Microservices 55

Service Caching

GraphQL utilizes Object Identifiers for one of the biggestsavers in terms of server processing demands – caching.By being able to cache resource for services which re-quest them, GraphQL can essentially build a cache ofoften-requested data and save processor time and effort.

According to Elmalen, this is rather easy to implement,in fact – GraphQL documentation suggests utilizing a sys-tem of globally unique IDs in order to note the resourcesbeing cached, thereby providing them with minimal pro-cessing demand.

“Since you’re handling a lot of network requests,you don’t want to have to keep making thoserequests over and over and over again if you’reseeing the same data frequently.”

Easy Failure Handling and Retries

GraphQL is unique, in that, in a normal connection andrequest cycle, there is no real “fail” or “succeed” – every-thing is either succeed or partially fail. GraphQL requestscan partially succeed, returning only elements of the datarequested or specific datasets as allowed, and this controlcan be very granular.

As a result of this, a resolver to a request can be morethan “all or nothing”, partially resolving as a single re-solver delivers content, and the rest of the request isdumped. This means that GraphQL is in a position tohandle failure rather gracefully, notifying the requester of

Page 66: GraphQL or Bust · Preface:Introductionto GraphQL Withinthelastcoupleofyears,therehasbeenaresur-genceofdiscussionaroundAPIdesignstandardssuch as REST, gRPC, GraphQL, and many others

7 Unique Benefits of Using GraphQL in Microservices 56

the failure but returning useful, actionable data alongsidethe noted failure and what caused said failure.

As part of this, GraphQL requests can be parsed to findthe null fields returning in a failed request, and notewhat the error actually was. If the error was a simplemisconfiguration or poorly formed call, it can be made ina better format upon instruction from the GraphQL layeritself – if the data is prohibited or absent, the requestercan also ascertain this. This means that automatic retriesare possible, as are granular levels of call termination andauto-failure handling.

“In GraphQLwe have a lot of flexibility with howthe resolvers work. Query execution doesn’thave to be all or nothing like it might be in aREST API, where if one endpoint call throws anexception everything might blow up. Resolversexecute independently of everything else, soone resolver can fail but the entire query canstill resolve.”

Case Study of Microservices InAction: How GraphQL Benefits Yelp

To see what GraphQL is so useful in a microservicesapproach, we can look at Tomer’s argument in favor ofintegration at Yelp. Yelp is foundationally a business thatties to additional businesses, and as such, utilizes a publicAPI rather heavily. Their public API is supposed to giveclients data connections by which the resources can becollected, reviewed, and collated.

Page 67: GraphQL or Bust · Preface:Introductionto GraphQL Withinthelastcoupleofyears,therehasbeenaresur-genceofdiscussionaroundAPIdesignstandardssuch as REST, gRPC, GraphQL, and many others

7 Unique Benefits of Using GraphQL in Microservices 57

In their original Yelp API, this external demand for datacauses a significant problem. The API was too large, hadtoo many endpoints, and as more data was requestedfrom outside partners, the API was expanded either withmore bloated endpoints or with additional endpoints tofeed out the data. This resulted in an extremely largesolution that was hard to maintain, hard to iterate upon,and generally less agile and was desired.

As a solution, Yelp began to implement a new designparadigm in GraphQL. Their chief reasoning was the factthat, for their outside businesses, those partners wantedto make a single request for the data they needed, andnothing more. GraphQL fit this requirement perfectly,as a single endpoint could now serve a multitude ofresources in a defined and predictable way. More impor-tant, only a single request would have to be made, asthat request could be formed in the way that the datarequester needed the data and it could be served basedupon the agreed data served by the provider.

This process and choice really encapsulates the purposeof GraphQL in a microservices architecture. While it istrue that Yelp could have simply added more endpoints,createdmoremicroservices, expanded the resource han-dling, and progressed the bloat process of their API. Allthis would have done, however, is increased complexity,bloat, and the cost to maintain the API.

By adopting GraphQL, however, their microservice-ori-ented design functions more agile, more responsively,and, perhaps most importantly, more adherent to thedesign requirement at hand – a single request deliveringthe data as requested.

Page 68: GraphQL or Bust · Preface:Introductionto GraphQL Withinthelastcoupleofyears,therehasbeenaresur-genceofdiscussionaroundAPIdesignstandardssuch as REST, gRPC, GraphQL, and many others

7 Unique Benefits of Using GraphQL in Microservices 58

Final Thoughts

It should be noted that GraphQL is extremely powerful,and that the benefits at hand are especially powerful formost microservice structures – though not all. In somecases, especially in cases in which the data does notchange, new endpoints are not added, and additionalfunctions are not required, GraphQL may add additionalunwarranted complexity.

GraphQL has often been sold as a perfect solution forevery problem, but the reality is that itmeets one require-ment better thanmost other, and if that’s not part of yourrequirements, it may not be the best solution for yourimplementation.

For situations like that faced by Yelp, however, GraphQLfits perfectly and solves the major issues at hand. Forthis reason alone, should developers find themselves ina microservice architecture and requiring a greater flex-ibility in data delivery and structuring, GraphQL shouldabsolutely be a top consideration.

Page 69: GraphQL or Bust · Preface:Introductionto GraphQL Withinthelastcoupleofyears,therehasbeenaresur-genceofdiscussionaroundAPIdesignstandardssuch as REST, gRPC, GraphQL, and many others

Comparing GraphQLWith Other Methods to

Tether API Calls

From the very beginning, developers have sought tomaketheir systems runmore efficiently, delivering greater amountsof data and functionality in a slimmer,moreusefulmethod-ology. Increased efficiency usually equates tomoney saved,so there is a very real drive behind the constant need forcondensing and code tweaking.

Though there are a variety of approaches taken towardsthis end, one method remains a popular suggestion —

Page 70: GraphQL or Bust · Preface:Introductionto GraphQL Withinthelastcoupleofyears,therehasbeenaresur-genceofdiscussionaroundAPIdesignstandardssuch as REST, gRPC, GraphQL, and many others

Comparing GraphQL With Other Methods to Tether API Calls 60

tethering API calls. A simple process in theory becomesone more complex in application — with interesting re-sults in certain use cases.

In this chapter, we’ll discuss some general methods usedto combine API calls, and how to implement them. We’lltake a look at the various strengths and weaknessesof this approach, as well as highlight some use casesthat would benefit from its implementation. We’ll alsocompare it to a chief alternative competitor, GraphQL,and examine whether or not one comes out on top.

What Do We Mean By Tethering APICalls?

Tethering is the act of initiating multiple data requeststo various parameters, APIs, or microservices, in a singlecall. The idea is that by combining these requests, yourplatform gains efficiency and speed. However, there aresome caveats that we’ll discuss shortly.

One way to consider tethering is to think about howmail is handled via the hub-and-spoke model. When youwrite a letter, this letter is dropped off in a post box. Thepostman then collects these letters and parcels, bindingthem together for processing. At the processing shop,these bundles from everywhere in your city are bundledtogether into even larger crates depending on their des-tination and purpose.

Tethering works much the same. The big benefit of thismethod arises in that postal metaphor — the joining ofunrelated resources within a single action.

Page 71: GraphQL or Bust · Preface:Introductionto GraphQL Withinthelastcoupleofyears,therehasbeenaresur-genceofdiscussionaroundAPIdesignstandardssuch as REST, gRPC, GraphQL, and many others

Comparing GraphQL With Other Methods to Tether API Calls 61

Let’s say you have a collection of APIs in a microservicearchitecture, each manipulating data across a suite ofapplications. While there is no need for a music discov-ery application to access the contacts on an iOS deviceregularly, a new update has enabled a significant socialnetworking service on the discovery application.

Luckily, your users also largely use another one of yourproducts, a video sharing app akin to Vine, with userscollated from their contact list. While pulling straight fromthe contact list and comparing to accounts might get yousome users, you are likely to have a much greater chanceof adding new users to your new social platform thatalready actively use your suite.

With linking API calls, a request can be done to the videosharing application API to issue a friend request on behalfof the user, while avoiding sending new requests to userswho are not represented on any of your suite’s applica-tions.

In this case, what would typically take several calls — a “isthis user on the video app?” call, a “are they on the user’scontact list?” call, and finally a “friend request sent!” call— can be condensed to a singular call.

Benefits of Tethering API Calls

There’s quite a number of benefits to this approach inparticular. First and foremost is speed — when an APIonly has to issue a single call that is handled by therelational processing betweenmicroservice APIs, calls arereturned quicker and with greater accuracy. Light canonly travel so fast, and thus processing is fundamentally

Page 72: GraphQL or Bust · Preface:Introductionto GraphQL Withinthelastcoupleofyears,therehasbeenaresur-genceofdiscussionaroundAPIdesignstandardssuch as REST, gRPC, GraphQL, and many others

Comparing GraphQL With Other Methods to Tether API Calls 62

limited — reducing the number of calls that must bemade reduces latency,making combining calls a powerfulway to optimize APIs for mobile apps.

In the same vein, comibining calls is muchmore efficientthan traditional calls. By using the connection betweenAPIs rather than creating a singular “filter” or “intersec-tion” style API that attempts to combine all calls afterthey’re made, you can perform the same function whilenot creating bloat inside your ecosystem. Tethering callsis like the world’s greatest game of telephone — you askyour neighbor for sugar, milk, and eggs, and they in turnask their neighbor for what they don’t have, and so on,until you get what you need—without this, you’d have towalk to each neighbor individually.

There is of course an implicit increase in security forthis function as well. While it seems counter-intuitive,what with more resources being accessed with only asingle call, the end result is a reduction in attack vectorfor the simple reason of having less calls.If you had 100armored vans transporting money through a high-crimearea, or a single armored van transporting money, youwould have greater security through reduction in tripsover time, even if the actual security of the single result isthe same.

Thismode of combined communication also has the ben-efit of making the API more friendly to automation. Bymoving the logic of the call to a higher level, and openingthe call itself to shared resources, the ultimate result is aneasier to deploy, more automatic, less code-heavy, andfaster solution.

What this all means is that, as long as it’s properly im-plemented, both the provider and consumer can have amuch better, streamlined experience. While consumers

Page 73: GraphQL or Bust · Preface:Introductionto GraphQL Withinthelastcoupleofyears,therehasbeenaresur-genceofdiscussionaroundAPIdesignstandardssuch as REST, gRPC, GraphQL, and many others

Comparing GraphQL With Other Methods to Tether API Calls 63

benefit from combined calls and more simple call struc-tures for large amounts of data, the provider has a muchreduced amount of documentation and data bandwidthimplications.

Drawbacks of Tethering API Calls

That’s not to say, however, that joining API calls is perfect— there are some caveats to consider before implement-ing this methodology.

The first and most dramatic possible drawback is the factthat it lends itself to circular logic, if you’re not careful.Becausemultiple resources are being called, andmany ofthese resources can be augmented by calls, it is possibleto call a chain that results in an infinitely changing result.

These unexpected results can be negated, of course,and much of the drawback of circular references can beconverted into a net benefit with proper redirects andinterceptors, but the threat is very real, and easy to fallinto if not mitigated from the onset.

Another is lack of support. Unfortunately, tethering issimply not supported by common and publically usedschemas and API patterns. Because of this facet, wherecommunication logic and business logic are separate andarchitecturally limited, anAPImust be redesigned atworse,or augmented with abstraction layers at best, which canin turn negate many of the benefits inherent to the sys-tem.

Adding complexity to the call canmean a greater barrierto users and additional developers. With this also comesthe risk of easier denial of service attacks and other

Page 74: GraphQL or Bust · Preface:Introductionto GraphQL Withinthelastcoupleofyears,therehasbeenaresur-genceofdiscussionaroundAPIdesignstandardssuch as REST, gRPC, GraphQL, and many others

Comparing GraphQL With Other Methods to Tether API Calls 64

such attacks that can use the increased ability to makecombined calls to break the system.

This can be negated widely by simply enabling rate limit-ing, but all in all, it may be a negative that makes integra-tion not worth it.

Use Cases

Combining API calls is a helpful methodology in somecircumstances. Since the circumstances themselves areoften specific to the application, we must speak broadlyas to the qualities that make API tethering a good choice.

• UnrelatedDatabases:Whenmultiple databases arepresent with typically unrelated data, and data mustbe pulled from both to form a relation, combiningAPI calls is a good idea. While it would be best insome cases to create a relational link between thesedatabases, the problem arises in the frequency — ifthe data is not expected to constantly be referencedin a concrete way, tethering can get around thisproblem with relatively low overhead.

• Unexpected Data Requirements: When the spe-cific requirements for a function or the given evolu-tion of a product are unknown, tethering can coverthis facet. Because not every facet of evolution inan API can be predicted, developers often suggestmicroservices as a solution. This is fine, but it limitsthe choice of development tracks into the realm ofwhat already exists and forces concrete develop-ment relations. Tethering calls can eschew this.

Page 75: GraphQL or Bust · Preface:Introductionto GraphQL Withinthelastcoupleofyears,therehasbeenaresur-genceofdiscussionaroundAPIdesignstandardssuch as REST, gRPC, GraphQL, and many others

Comparing GraphQL With Other Methods to Tether API Calls 65

• High Volume Calls: When high volume calls arethe name of the game, combining calls can reducethe total impact of the simple volumetric issues bycombining calls into single returns. This also hasthe added benefit of more secure communications,as the number of calls is reduced. While this couldbe touted as a feature, unfortunately, reception oftethering has not been as widespread as before,meaning that security in the API space doesn’t al-ways flow over into chained requests. This can benegated with training, however.

Alternatives — GraphQL

This isn’t the only solution to the problem of such com-plex calls, of course. GraphQL can be used to replicatemuch of the effect gained alternative strategies, albeit viaa differentmethodology. Because data can be defined viathe GraphQL query, multiple datapoints can be collatedinto a single database or collection and then returned inthe requested format for easier parsing.

For example, this call queries multiple endpoints througha singular call:

Page 76: GraphQL or Bust · Preface:Introductionto GraphQL Withinthelastcoupleofyears,therehasbeenaresur-genceofdiscussionaroundAPIdesignstandardssuch as REST, gRPC, GraphQL, and many others

Comparing GraphQL With Other Methods to Tether API Calls 66

{

latestPost {

_id,

title,

content,

author {

name

},

comments {

content,

author {

name

}

}

}

}

This is done via a completely differentmethodology, though,so some of the benefits of tethering — specifically thereduction in call volumeandprocessing—are fundamen-tally lost. The architecture itself is simply being maskedwith GraphQL — none of the processing is changed on abase level, and the traditionally poor processing architec-ture marches on unbeknownst to the user.

While multiple endpoints are brought into a single end-point, the result is still functionally the same — multiplecalls are still called. The only difference is in the percep-tion of the returned data and latency in returning thatdate.

There is a big benefit in integrating GraphQL, however, inthe fact that the data can be pre-formed and pre-deter-mined by the requesting entity. Whereas tethering simplyreturns the data for interpretation, GraphQL specificallyissues a schema for data display, thus controlling the

Page 77: GraphQL or Bust · Preface:Introductionto GraphQL Withinthelastcoupleofyears,therehasbeenaresur-genceofdiscussionaroundAPIdesignstandardssuch as REST, gRPC, GraphQL, and many others

Comparing GraphQL With Other Methods to Tether API Calls 67

output more effectively.

Conclusions

API tethering is very powerful, but quite problematicwhennot properly implemented. Because of this, it’s often saidthat using tethering is outside of best practices, both dueto lack of training and the avoidance to call through aproxy loopback. However, it is within “best practices” foran untrained pilot to not fly a 747 — that doesn’t meanthe 747 isn’t useful to those who know how to utilize it. It’salso less efficient to transport the Space Shuttle inside a747— but in some use cases, it’s had to be done. Neitherargument is really one against implementation — they’rebest categorized as perhaps “too strong” precautionsagainst poor implementation.

Though many of the criticisms against API tethering arevalid, they can be negated by proper implementation. Thechoice to combine API calls will depend entirely on yourcircumstance and the needs to the application itself. Inthe right situation, with the right user base, API tetheringis incredibly powerful.

Page 78: GraphQL or Bust · Preface:Introductionto GraphQL Withinthelastcoupleofyears,therehasbeenaresur-genceofdiscussionaroundAPIdesignstandardssuch as REST, gRPC, GraphQL, and many others

The Power of Relay: TheEntry Point to GraphQL

Inmanyways, GraphQL is a futuristic approach to dealingwith all the headaches surrounding high-data transfer,large-volume relational content. As more is written aboutthe technology and as its implementation is discussed, itgoes without saying that related components are becom-ing increasingly more interesting as well.

One of these components, Relay, often falls to the way-side in the conversation — and that’s a shame, given thatRelay is incredibly powerful, useful, and interesting, giventhe right use cases.

Accordingly, this piece will focus on Relay as an extensionof GraphQL per Facebook’s stated development guide-lines and documentation. We’ll discuss how Relay doeswhat it does, what specifically makes it special, and why

Page 79: GraphQL or Bust · Preface:Introductionto GraphQL Withinthelastcoupleofyears,therehasbeenaresur-genceofdiscussionaroundAPIdesignstandardssuch as REST, gRPC, GraphQL, and many others

The Power of Relay: The Entry Point to GraphQL 69

pairing Relay with some — but not all — GraphQL imple-mentations is a good idea.

What’s the Difference BetweenGraphQL and Relay?

While GraphQL and Relay are often pushed in the samesentence (and are treated like a package by Facebookand many other advocates), they are actually two verydifferent parts of a greater mechanism.

GraphQL is, fundamentally, a way to model and exposedata in the native application. That is to say that GraphQLis the methodology by which all of its extended function-ality is prepared for fetching and interaction.

Relay, on the other hand, is the client-side data-fetch-ing solution that ties into this stated model to renderdata efficiently for the end user. It ties into the GraphQLschema, it uses the GraphQL schema, and with furtherserver-side additions, it augments GraphQL schema, butto say they’re one in the same is like saying “gasoline” and“tires” are one in the same because they’re both used topower a car.

Page 80: GraphQL or Bust · Preface:Introductionto GraphQL Withinthelastcoupleofyears,therehasbeenaresur-genceofdiscussionaroundAPIdesignstandardssuch as REST, gRPC, GraphQL, and many others

The Power of Relay: The Entry Point to GraphQL 70

To further drive home the point, GraphQL is able tobe used entirely independently of Relay, while Relay de-pends onGraphQL (or, at least, GraphQL-like schemas) tofunction. GraphQL can be used with any fetching tech-nology that is designed to handle the query in question(which is easily done with most modern solutions).

The GraphQL specification describes how Relay makesthree core assumptions on what a GraphQL server pro-vides:

1. A mechanism for refetching an object.2. A description of how to page through connections.3. Structure aroundmutations tomake thempredictable.

What is Relay?

So what exactly is Relay? At its most base level, Relay is aJavaScript framework crafted to build React.js services.It was designed as a component to Facebook’s GraphQL,expressly crafted to handle high data throughput andoutput the requested data in a dynamically stated way.

A big power point behind Relay is how it handles thisdata fetching. Relay handles data through declarativestatements in GraphQL, composing the data query intoefficient batches while keeping to the stated data struc-turing. Because of this, Relay is very fast, very efficient,and more important, extensible to the application de-mands in a dynamic manner.

That’s not the only thing that makes Relay users sing itspraises, of course. Colocation is present in Relay, allow-ing for aggregate queries and limited fetching.Mutations

Page 81: GraphQL or Bust · Preface:Introductionto GraphQL Withinthelastcoupleofyears,therehasbeenaresur-genceofdiscussionaroundAPIdesignstandardssuch as REST, gRPC, GraphQL, and many others

The Power of Relay: The Entry Point to GraphQL 71

are supported widely as well, and provides optimisticupdates to create a more seamless user experience bypresenting data as a positive throughput even while theserver is still managing the request.

Essentially, Relay does what it does well, in very specificapplications, and more efficiently than other solutions.

The Good

So with all this in mind, why use Relay at all? If GraphQLdoes so much, and operates outside of Relay, why do weneed it? Well, GraphQL isn’t perfect. It lacks the abilityto poll and reactively update, and it has some built-ininefficiencies that make the system less than optimum.

Relay, on the other hand, fixes many of these issues, ex-tending its usefulness into new heights. With Relay, datarequirements are expressly stated and fetched muchmore efficiently than just standard fetching in GraphQL.This increase in efficiency stems largely from the datacaching built into Relay, allowing existing data to bereused instead of forcing a new fetch for each round tripon the server.

Part of this boost in efficiency comes from aggregationand colocation of queries into single, streamlined data re-quests. While this has a huge benefit in terms of logic, themain benefit is in the network traffic and pure volumetricreduction.

The improvements don’t stop there. Relay offers efficientmutations, and provides for cataloguing, caching, andaltering thesemutations after the fact, including dynamiccolumn/value alteration.

Page 82: GraphQL or Bust · Preface:Introductionto GraphQL Withinthelastcoupleofyears,therehasbeenaresur-genceofdiscussionaroundAPIdesignstandardssuch as REST, gRPC, GraphQL, and many others

The Power of Relay: The Entry Point to GraphQL 72

A huge benefit here is the support for optimistic up-dates. Optimistic updates are an interesting method-ology of client mutations wherein the client simulatesthe mutation as the server commits the mutation to thebackend, allowing the user to interact with the changesthey made and simulate their experience without waitingfor the server to commit.

As part of the support for optimistic updating, Relayprovides a system for Relay mutation updates, statusreporting, and rollback, which allows for more seamlessmanagement of client and server states. Relay also sup-ports rich pagination, easing the heavy burden of largedata returns andmaking themeasier to consume, furtherimproving user experience.

We can see the effectiveness of Relay by looking at itsimplementation. Messaging application Drift is designedto tie customers and providers together using real-timemessaging natively on the provider’s website. Because ofprevious experiences with multiple endpoints and largedata requests, the team at Drift knew that speed wouldbe affected — and dramatically.

When they started a new company, Drift, and saw them-selves falling into the same hole they previously did, theymade the decision to fix the issue early, and integratedGraphQL into their services. When faced with the follow-ing complex data set:

“Customer attributes come from a single re-quest that returns name, title, location, timezone and avatar. But in order to display theaccount owner, we’ll need to query the orga-nization’s team endpoint to fetch that nameand avatar. To render those colorful tags, we

Page 83: GraphQL or Bust · Preface:Introductionto GraphQL Withinthelastcoupleofyears,therehasbeenaresur-genceofdiscussionaroundAPIdesignstandardssuch as REST, gRPC, GraphQL, and many others

The Power of Relay: The Entry Point to GraphQL 73

need to fetch the tag definitions from anotherendpoint. The list of all contact avatars requiresa search for all customers in the same com-pany against our ElasticSearch backend. Thechat count and last contact requires multiplecalls to our Conversation API and one last callto fetch that user’s online status or last activetimestamp.”

They coded the following data query:

{

user(id:1) {

name

title

avatarUrl

timezone

locale

lastSeenOnline

email

phone

Location

accountOwner {

name

avatarUrl

}

tags {

edges {

node {

label

color

}

}

}

accountUsers(first:10) {

Page 84: GraphQL or Bust · Preface:Introductionto GraphQL Withinthelastcoupleofyears,therehasbeenaresur-genceofdiscussionaroundAPIdesignstandardssuch as REST, gRPC, GraphQL, and many others

The Power of Relay: The Entry Point to GraphQL 74

edges {

node {

id

avatarUrl

}

}

pageInfo {

totalAccountUsers

}

}

recentConversations(first:10) {

edges {

node {

lastMessage

updatedAt

status

}

pageInfo {

totalConversationCount

}

}

}

}

}

Their reaction?

“We were able to expand our query based onthe needs of the client and request a ton ofinformation that usually would have takenmul-tiple requests, a lot of boilerplate and unnec-essary code written on both the client and theserver.The payload now conforms to exactlywhat the customer wanted, and it gives theserver the ability to optimize the resources nec-

Page 85: GraphQL or Bust · Preface:Introductionto GraphQL Withinthelastcoupleofyears,therehasbeenaresur-genceofdiscussionaroundAPIdesignstandardssuch as REST, gRPC, GraphQL, and many others

The Power of Relay: The Entry Point to GraphQL 75

essary to compute the answer. Best of all, thiswas all done in a single request. Unbelievable.Welcome to the future.”

Welcome to the future, indeed.

The Bad

There’s a lot of good things about Relay, but there’s someunderlying issues behind each benefit. Take, for instance,the idea of mutation handling within Relay itself. Whenmutations occur, especially when they’re done in an op-timistic update paradigm, you run into some significantissues.

For instance, when querying a database with multiplefields in the GraphQL schema, you’re essentially updatingthe client multiple times, the backendmultiple times, andhoping the related graph part each updates properly.Nine times out of ten, they do — but even a single failurecould have a rolling effect on the backend at large.

Further, the idea of optimistic updates is great in theory,but adds some logic responsibility on the client-side de-veloper that may or may not be useful in all use cases.While large edits would definitely benefit from such anupdate scheme, simple updates and mutations do notrequire simulation. What this means is a ton of logicrequired to be implemented in the client-side team, withthe server-side team having very little responsibility forensuring cross compatibility.

There is, of course, the concern over loss of data andvalidation in such a system as well. With each increasing

Page 86: GraphQL or Bust · Preface:Introductionto GraphQL Withinthelastcoupleofyears,therehasbeenaresur-genceofdiscussionaroundAPIdesignstandardssuch as REST, gRPC, GraphQL, and many others

The Power of Relay: The Entry Point to GraphQL 76

level of complexity in this situation, you’re reducing theefficiency that makes Relay such a good sell in the firstplace.

The main issue raised towards Relay, however, is thatit’s not technically necessary — while the functionalityof Relay is impressive, there’s a bevy of solutions bothunique and already integrated into common languagesand architectures that mirror the functionality such thatRelay might simply be reinventing the wheel.

Standard GraphQL can be used without Relay, especiallyon projects with a smaller scope than Facebook, withoutmuch loss of functionality. Other solutions like Cashaymirror the cache storage solution for domain states in asimpler, more user-friendly format.

A REST Replacement

There’s been some contention over exactly why we needRelay — or even GraphQL, for that matter. The develop-ment of GraphQL and Relay comes from the idea thatthere’s something fundamentally wrong or done poorlyin REST, a prospect that not everyone agrees with.

Let’s state upfront that almost everything that GraphQLdoes can be done in REST, though perhaps less effi-ciently. Fetching complex object graphs is easier done inGraphQL, but the same functionality can be replicatedwith constructing an endpoint around the given data setsas a subset of the greater whole.

These complex requests are made easier with the factthat HTTP can send parallel network requests, thoughwith greater overhead. And what limitations exist in this

Page 87: GraphQL or Bust · Preface:Introductionto GraphQL Withinthelastcoupleofyears,therehasbeenaresur-genceofdiscussionaroundAPIdesignstandardssuch as REST, gRPC, GraphQL, and many others

The Power of Relay: The Entry Point to GraphQL 77

current solution, HTTP/2 is attempting to solve them, and(in some opinions) to great effect.

There’s also the issue of just what Relay and GraphQLare designed to handle. The two were developed by Face-book for Facebook — a site that deals with thousands ofmetadata points and relations that the average developermay never come across. In this case, for many people, it’sa case of killing weeds with a flamethrower — yes, it’s asolution, but it’s an over-engineered one.

A good portion of criticism towards GraphQL and Relay inprinciple is the fact that many of the issues people havewith REST aren’t issueswith RESTful architecture, but withthe common implementations. REST supports contentnegotiation, is feature rich with everything HTTP has tooffer, and has basic over and under fetching preventionsolutions.

Essentially speaking, the problems that Facebook set outto fix are, in the eyes of many people issues of poor RESTimplementations and improper coding techniques, notthe actual REST architecture itself.

Regardless of which side you fall on, it basically boilsdown to this — is adopting GraphQL and Relay worththe effort when considering that many of its features canbe replicated somewhat in REST? What are your specificneeds? Do you have Facebook level (and style) data tomanage? If not, GraphQL, and thereby Relay, may not bethe best choice in the world.

Page 88: GraphQL or Bust · Preface:Introductionto GraphQL Withinthelastcoupleofyears,therehasbeenaresur-genceofdiscussionaroundAPIdesignstandardssuch as REST, gRPC, GraphQL, and many others

The Power of Relay: The Entry Point to GraphQL 78

Conclusion

Relay is powerful — but like GraphQL, it’s not a magicbullet. High-volume data in Relay is the gold standard forefficient data handling, but for standard data handling,you really have to questionwhether or not it is truly betterthan proper RESTful design.

That being said, Relay is still in its infancy. It came fromFlux, and just like Flux, is constantly being iterated uponand expanded into bigger, better things. As time goes on,much of the concern about Relay will likely be assuaged,with its functionality expanded further while being mademore efficient.

Page 89: GraphQL or Bust · Preface:Introductionto GraphQL Withinthelastcoupleofyears,therehasbeenaresur-genceofdiscussionaroundAPIdesignstandardssuch as REST, gRPC, GraphQL, and many others

10 GraphQL Consoles inAction

Most web API providers probably already know aboutGraphQL by now. It’s the API query modeling languagemaking waves throughout the API industry, allowing de-veloper users to interact with a web API in an arguablycleaner method. The industry is still divided, though.While some venture to say it will replace REST in itsentirety, others question whether GraphQL is worth it.Outside of Facebook, the founders of GraphQL, there areactually quite a few API providers actually implementingGraphQL in practice. Usage keeps popping up in newenvironments throughout many public APIs, often uti-lizing GraphiQL, the official open source visual consolefor interacting with API calls. These visual interactiveaids are designed to help developer users query data

Page 90: GraphQL or Bust · Preface:Introductionto GraphQL Withinthelastcoupleofyears,therehasbeenaresur-genceofdiscussionaroundAPIdesignstandardssuch as REST, gRPC, GraphQL, and many others

10 GraphQL Consoles in Action 80

and perform mutations. So, to add a little validation ofthe technology, let’s check out some companies officiallyimplementing it with their public API programs. We’lllist 10 APIs using GraphQL, and test out their GraphiQLconsoles with mock use cases to sample the behavior.

GraphiQL: GraphQL API Explorer

GraphiQL is an open source IDE console for exploring aGraphQL server. It displays a code editor with autocom-plete on the far left, comes with error highlighting, queryresults in the middle column, and a documentation ex-plorer on the far right. You can demo the Star Wars API totest it out. The Query Variables on the bottom left showwhat is actually being manipulated in the request. Fora developer consumer, a Graph_i_QL interface could behelpful for building GraphQL queries, viewing the typesof data that are available, and more.

An empty GraphiQL console

Page 91: GraphQL or Bust · Preface:Introductionto GraphQL Withinthelastcoupleofyears,therehasbeenaresur-genceofdiscussionaroundAPIdesignstandardssuch as REST, gRPC, GraphQL, and many others

10 GraphQL Consoles in Action 81

1: GraphQL Hub

First off, let’s consider the GraphQLHub aggregation. Cre-ated by Clay Allsopp, you can use it to explore 5 popularAPIs: Hacker News, Reddit, GitHub, Twitter, and Giphyusing GraphQL. Though it’s technically an unofficial proxy— not manufactured by these companies — it’s a uniquedemonstration of the power of GraphQL to combinedisparate elements into the same query style.

Query of recent Hacker News posts

Say I wanted machine readable data of my last 5 posts toHacker News, with the URL, score, and unique identifier.Using theGraphQLHub interface, we can easily query thisand read the results in JSON. Reminiscent of a PostmanAPI collection, a GraphQL “hub” could be used by a teamto easily interactwith their ownuniqueAPI dependencies.

Page 92: GraphQL or Bust · Preface:Introductionto GraphQL Withinthelastcoupleofyears,therehasbeenaresur-genceofdiscussionaroundAPIdesignstandardssuch as REST, gRPC, GraphQL, and many others

10 GraphQL Consoles in Action 82

2: Brandfolder

Brandfolder is an asset management service. With theirAPI, developers can programmatically upload or retrievebrand asset files like images or fonts. Their GraphQL play-groundusesGraphQLify to provide aGraphQL server andschema to act as a middlemen between the Brandfolderbackend and frontend, translating a JSON API to interactwith React/Relay applications. To play around here you’llneed an account and authorization.

Testing Brandfolder’s GraphQL console will require account authoriza-tion

3: Buildkite

Buildkite specializes in helping companies with continu-ous deployments. They’ve been driving front end devel-opment through the https://graphql.buildkite.com end-point. Their GraphQL API has even leapfrogged the webUI, as you can use it to schedule builds. Also built on theofficial open source GraphiQL, their GraphQL console isaccompanied by a thorough step-by-step walkthrough;a good thing to consider to help new developers. AsTim Lucas of Buildkite states: “GraphQL was made to

Page 93: GraphQL or Bust · Preface:Introductionto GraphQL Withinthelastcoupleofyears,therehasbeenaresur-genceofdiscussionaroundAPIdesignstandardssuch as REST, gRPC, GraphQL, and many others

10 GraphQL Consoles in Action 83

be human friendly and empower people to easily use,explore, integrate with APIs.”

Buildkite demonstrates how to use GraphiQL to perform mutations ona deployment schedule

4: EHRI

The European Holocaust Research Infrastructure (EHRI)provides access to holocaust related data and archivematerials held in institutions throughout Europe. In ad-dition to offering a Search API to access the database, TheEHRI portal provides an experimental GraphQL API. AsEHRI describes, GraphQL is a “faster and more efficientoptionwhen the data required in known in advance.” Thisechoes issues that some have with GraphQL being onlyaccessible by developers familiar with the API.

Page 94: GraphQL or Bust · Preface:Introductionto GraphQL Withinthelastcoupleofyears,therehasbeenaresur-genceofdiscussionaroundAPIdesignstandardssuch as REST, gRPC, GraphQL, and many others

10 GraphQL Consoles in Action 84

5: GDOM

GDOM is a web parser open sourced on GitHub. Usingthe Graphene framework, GDOM uses GraphQL syntaxto traverse and scrape content off web pages. AnotherHacker News example, here we use GraphQL syntax totraverse the Y Combinator home page and return topstories:

GraphiQL in the context of DOM traversal and scraping

6: GitHub

From using ChatOps to initiating other company culturalinnovations, GitHub is quick to embrace cutting edge op-erational improvements. They’ve taken a stab at GraphQLas well. Currently in an early access alpha stage, you’llhave to register for the GitHub pre-release program touse it (which just means signing in via your GitHub ac-count and accepting a terms of use). Let’s use the GitHubGraphQL API to retrieve some basic account information:

Page 95: GraphQL or Bust · Preface:Introductionto GraphQL Withinthelastcoupleofyears,therehasbeenaresur-genceofdiscussionaroundAPIdesignstandardssuch as REST, gRPC, GraphQL, and many others

10 GraphQL Consoles in Action 85

Retrieving account information with the GitHub GraphiQL API sandbox

When will this become a full release? Well, GitHub placestheir GraphQL on the long-term side of their PlatformRoadmap.

7: HIV Drug Resistance Database

GraphQL may also be useful in the context of academicresearch. StanfordUniversity is currently usingGraphiQLto visually query their Sierra Web Service, which interactswith their curated database of HIV drug resistance data.Below is a GraphQL call to retrieve a genomic sequencefrom a virus with a specific mutation:

Sequence analysis on Stanford’s GraphiQL console

Page 96: GraphQL or Bust · Preface:Introductionto GraphQL Withinthelastcoupleofyears,therehasbeenaresur-genceofdiscussionaroundAPIdesignstandardssuch as REST, gRPC, GraphQL, and many others

10 GraphQL Consoles in Action 86

8: Helsinki Open Data

HSL is the **public transportation **authority in theHelsinki, Finland metropolitan region. They produce dataon routes, train stations, and more, which is all publiclyaccessible as open data on the HSL Developer Commu-nity. Say we wanted to retrieve basic information onall transit stations in the Helsinki area; using the HSLGraphiQL console we can use a single GraphQL queryto list stations and fields such as station name, specificlocation, and more:

A GraphQL query to retrieve information on transit stations in theHelsinki area. No “Prettify” option?! Oh well.

9: melodyCLI

MelodyCLI is a dependency manager for Go. It helpssave time by caching Go repositories, using a GraphQLAPI to routinely expose metadata on dependencies. Be-lowwe’ve used themelodyRepo Playground GraphiQL in-

Page 97: GraphQL or Bust · Preface:Introductionto GraphQL Withinthelastcoupleofyears,therehasbeenaresur-genceofdiscussionaroundAPIdesignstandardssuch as REST, gRPC, GraphQL, and many others

10 GraphQL Consoles in Action 87

terface to retrieve dependency information on a specificGitHub package:

MelodyCLI GraphQL playground call to sample dependency manage-ment functionality

10: SuperChargers.io

Superchargers.io is a web app map that provides thelocations of Tesla stores, powering stations, and otherservice centers. Wholly based on a GraphQL API, the sitedoes a nice job of onboarding developers to understandhow queries behave.

Page 98: GraphQL or Bust · Preface:Introductionto GraphQL Withinthelastcoupleofyears,therehasbeenaresur-genceofdiscussionaroundAPIdesignstandardssuch as REST, gRPC, GraphQL, and many others

10 GraphQL Consoles in Action 88

Query to Superchargers.io retrieves all Supercharger stations in Europe.

11: Microsoft

Some teams atMicrosoft are consideringGraphiQL adop-tion. Dimitry Pimenov, a Program Manager at MicrosoftGraph sharedwithNordic APIs a test of their live GraphQLconsole. Essentially, how the tooling works is it takes in anOData API description, parses it, and creates a GraphQLschema and code generates the necessary resolvers. Ac-cording to Pimenov, though there are some performancebottlenecks with this approach, it does provide a muchbetter developer experience as far as resource discoverygoes.

Page 99: GraphQL or Bust · Preface:Introductionto GraphQL Withinthelastcoupleofyears,therehasbeenaresur-genceofdiscussionaroundAPIdesignstandardssuch as REST, gRPC, GraphQL, and many others

10 GraphQL Consoles in Action 89

Does Increased Usage ValidateGraphQL?

Now used within asset management, academic study,public transportation, andmore, you can see thatGraphQLis getting around. However, trends alone shouldn’t vali-date the adoption of technology. So, why are more andmore groups appreciating GraphQL? Well, as we’ve dis-cussed before, there are some potential benefits:

• Better query efficiency: You can querymultiple APIcalls simultaneously.

• More elegant data retrieval: Combining calls canreturn a lot of data with a single request.

• Low adoption overhead: Since GraphQL is a wrap-per that can be defined, you don’t have to replace aREST system.

As the team behind melodyCLI put it:

“We chose GraphQL to give us greater flexibil-ity in how metadata is structured while givingclients more flexibility in how it’s queried”

GraphQL should not be viewed as the stand-alone endall solution for everyone — many APIs still need devel-oper documentation and strong API versioning strate-gies. A pain point is a lack of onboarding material in theGraphiQL interface; for developers unfamiliar with APIcalls, knowing how to structure a query is difficult as youwill have to dig into documentation for the correct ids,field names, Strings, etc.

Page 100: GraphQL or Bust · Preface:Introductionto GraphQL Withinthelastcoupleofyears,therehasbeenaresur-genceofdiscussionaroundAPIdesignstandardssuch as REST, gRPC, GraphQL, and many others

10 GraphQL Consoles in Action 90

Tips on Making GraphQL / GraphiQLAwesome

With that inmind, for API providers considering providinga GraphiQL style IDE, here are some tips for getting themost out of it:

• Introduce what GraphQL is: The technology is stillnew to many, and they would love your help instructuring their first queries.

• HaveexampleGraphQLqueries: Auto-fill theGraphiQLskeletonwith sample queries to help users get started.The Superchargers.io FAQ, for example, links to 4different sample queries that populate a GraphiQLconsole. </span>

• Have supplementary tutorials or FAQs on the sidethat explain your GraphQL schema and fields.

• Brand it: Lastly, it doesn’t hurt to include your ownskins. Include branding on top of the blankGraphiQLlayout to make it your own.

More Resources:

• Facebook cites roughly 70 companies implementingGraphQL here

• “GraphQL — A Legit Reason to Use It,” Edge Coders• APIs.guru’s ongoing Collection of GraphQL APIs• To help you get started, see this comprehensive listof community GraphQL libraries and tools

• Bruno Pedro of Hitch hq provides the counter argu-ment: 3 reasons not to use GraphQL

Page 101: GraphQL or Bust · Preface:Introductionto GraphQL Withinthelastcoupleofyears,therehasbeenaresur-genceofdiscussionaroundAPIdesignstandardssuch as REST, gRPC, GraphQL, and many others

10 GraphQL Consoles in Action 91

• Learn GraphQL: Step by step tutorial introduction toGraphQL

Page 102: GraphQL or Bust · Preface:Introductionto GraphQL Withinthelastcoupleofyears,therehasbeenaresur-genceofdiscussionaroundAPIdesignstandardssuch as REST, gRPC, GraphQL, and many others

10 Tools and ExtensionsFor GraphQL APIs

With the surge of interest in GraphQL, a vibrant newecosystemof supplementary software has quickly emerged.Open source communities and entrepreneuring startupsalike are validating new GraphQL use cases, filling inGraphQL implementation gaps, and enabling more andmore developers to adopt GraphQL practices with de-creased overhead through the use of some pretty awe-some tools.

This is fantastic news for the query language, becauseLee Byron, a designer of GraphQL at Facebook, recentlynoted that in order for GraphQL to reach ubiquity, theecosystem desperately needs additional tooling:

“Where we definitely still need focus is in build-

Page 103: GraphQL or Bust · Preface:Introductionto GraphQL Withinthelastcoupleofyears,therehasbeenaresur-genceofdiscussionaroundAPIdesignstandardssuch as REST, gRPC, GraphQL, and many others

10 Tools and Extensions For GraphQL APIs 93

ing and improving the tools for using GraphQLand lots of different environments”

Whether these tools handle performance analysis ofgraphical services, are pre-built GraphQL servers, or of-fer IDEs for exploring GraphQL schemas, a lot can bedone to improve the GraphQL usability and adoptionexperience. In this article, we’ll feature a short curatedselection of various kinds of tools that can be used toexplore GraphQL relationships, document a GraphQLAPI, optimize and monitor a GraphQL API, map a RESTAPI to GraphQL, and much more. If you have undergonea GraphQL transformation, or are planning one out, youmay want to consider whether extensions like these maybe a helpful addition to your API’s stack.

List of 10+ Tools & Extensions forGraphQL APIs

1: GraphiQL

An in-browser IDE for exploring GraphQL APIs Repo | Demo

As we’ve previously discussed, many GraphQL APIs usethis open source console as an interactive API playground.GraphiQL is the popular Integrated Development Envi-ronment (IDE) for interacting with GraphQL API calls, en-abling developers to query data and perform mutations.

This IDE is relatively easy to implement; forNode.js servers,express-GraphQL can automatically generate GraphiQL.

Page 104: GraphQL or Bust · Preface:Introductionto GraphQL Withinthelastcoupleofyears,therehasbeenaresur-genceofdiscussionaroundAPIdesignstandardssuch as REST, gRPC, GraphQL, and many others

10 Tools and Extensions For GraphQL APIs 94

Since it’s built on React, GraphiQL can also be injectedwith unique CSS for custom branding.

The GraphiQL left column provides a space to enter queries with asyntax editor to search for relevant schema using autocomplete. Whenthe request is run, the response is displayed on the right column

Having visual aid in the form of an API sandbox, play-ground, CLI, or other interactive means is an importantfacet of supporting a living, breathing API program thatcaters to the needs of your audience.

2: GraphQL Voyager by APIs.guru

� Represent any GraphQL API as an interactive graph Repo| Demo

If you’re hoping to visually see how relational your datais, running it through GraphQL Voyager can make for acool experiment. Voyager takes a GraphQL API and turnsit into a visual graph; after setting a root schema, you canvisually view how fields are connected to types. Voyager

Page 105: GraphQL or Bust · Preface:Introductionto GraphQL Withinthelastcoupleofyears,therehasbeenaresur-genceofdiscussionaroundAPIdesignstandardssuch as REST, gRPC, GraphQL, and many others

10 Tools and Extensions For GraphQL APIs 95

is interactive, too — selecting a type highlights the fieldsit is comprised of, and links to relevant data within thegraph.

Echoing Lee Byron, APIs.guru founder Ivan Goncharovrecently told Nordic APIs:

“Writing advanced toolingwhichworkswith anyexisting GraphQL API is possibly one of thecritical things that REST APIs are missing.”

GraphQL Voyager provides a left column that describesfield information, and a visual interface that providesquick navigation. Users can also simplify the graph byeliminating Relay wrapper classes. Beyond being a sweetvisualization, the Voyager tool could help companies en-vision their data model, and spark conversations on re-lational data — finally, we can view the “graph” behindGraphQL.

GraphQL Voyager, by APIs.guru

Page 106: GraphQL or Bust · Preface:Introductionto GraphQL Withinthelastcoupleofyears,therehasbeenaresur-genceofdiscussionaroundAPIdesignstandardssuch as REST, gRPC, GraphQL, and many others

10 Tools and Extensions For GraphQL APIs 96

3: GraphCMS

Build a GraphQL Content API in Minutes

GraphCMS is an API-centric ContentManagement System(CMS) that is intimately tiedwithGraphQL. It lets youbuilda hostedGraphQL backed for web apps, providing toolingtomanage content. Users define data structures, validatethem in a GraphQL console, and see the representationin the user interface, all within the same platform.

While GraphCMS is perhaps not a good fit for an ex-isting API platform, it would cater well to a blog, webapp, or other content structures that require the abilityto programmatically share data. A GraphQL-based CMSwould be an interesting alternative to traditional CMSslike Wordpress or Drupal, and would enable a more fu-turistic content management framework that comes API-equipped and is thus a more flexible management layerfor end user interfaces.

GraphCMS

Page 107: GraphQL or Bust · Preface:Introductionto GraphQL Withinthelastcoupleofyears,therehasbeenaresur-genceofdiscussionaroundAPIdesignstandardssuch as REST, gRPC, GraphQL, and many others

10 Tools and Extensions For GraphQL APIs 97

4: GraphQL Docs by Scaphold.io

Clean, minimalist documentation for GraphQL APIs Repo |Demo

Need static documentation for a GraphQL API schema?Look no further than GraphQL Docs. The site will gen-erate simple, functional documentation in under 10 sec-onds given a GraphQL endpoint URL. Visitors can chooseto catalogue their API documentation publicly, or to keepit private.

An open source equivalent for static documentation isgraphdoc— fork this to generate and host GraphQL docson your own. For both, the result is a clean interface,searchmnenu, and links to schema definitions for object,and more.

![GraphQL schema definition for the Album Object in theSpotify API)

5: GraphQL Faker

Mock or extend your GraphQL API with faked data. Repo

If you are mocking up a barebones API, why not addsome lorem ipsum data to test things out? With GraphQLFaker, GraphQL API developers can insert realistic data tomimic real life results. It’s powered by faker.js, enablingdevelopers to mock over 60 kinds of realistic data, likestreet address, first and last name, avatar images, andmore. All you need to initiate it is to write a GraphQLIDL, and GraphQL faker provides some examples to get

Page 108: GraphQL or Bust · Preface:Introductionto GraphQL Withinthelastcoupleofyears,therehasbeenaresur-genceofdiscussionaroundAPIdesignstandardssuch as REST, gRPC, GraphQL, and many others

10 Tools and Extensions For GraphQL APIs 98

started within the IDL editor. It’s as simple as adding adirective to a field or custom scalar definition:

type Person {

name: String @fake(type: firstName)

gender: String @examples(values: ["male", "female"])

}

6: Swagger to GraphQL

Migrate from REST to GraphQL in 5 minutes Repo

For those API providers entrenched with the traditionalREST model, they may be indifferent to try out GraphQL.Thismapper takes thepain away, taking a Swagger schemaand automatically wrapping it to GraphQL. Tooling likethis could be leveraged to decreasemigration headaches,and enable a provider tomaintain both aREST andGraphQLfacade. For more, read the creator’s thoughts on movingan existing API from REST to GraphQL.

7: GraphQL IDE

An extensive IDE for exploring GraphQL APIs Repo

An Integrated Development Environment, or IDE is typ-ically a source code editor that maximizes developerproductivity with things like debugging, code completion,compiling, and interpreting abilities. The GraphQL IDE isan alternative to GraphiQL, but the keyword here is ex-tensive. It offers additional project management features,

Page 109: GraphQL or Bust · Preface:Introductionto GraphQL Withinthelastcoupleofyears,therehasbeenaresur-genceofdiscussionaroundAPIdesignstandardssuch as REST, gRPC, GraphQL, and many others

10 Tools and Extensions For GraphQL APIs 99

custom and dynamic headers, import/export abilities,and the ability to store queries and view a query history.

8: GraphQL Network

Chrome Devtool that provides a “network”-style tab to allowdevelopers to debug more easily. Repo | Demo

Many of us techies are Google Chrome power users, soa GraphQL browser tab is a hot ticket or any seriousGraphQL API developer. Called GraphQL Network, thishelpful tab is similar to viewing network requests in theChrome DevTool — which is great for debugging RESTfulAPI calls, but falls short when working with GraphQL,since “/graphql” is usually displayed as the endpoint,meaning that differentiating seperate requests is a pain.

The tab shows a concise list of recent GraphQL requests,listing HTTPmethod name, status, and type of request. Inaddition, GraphQL Network also gives a raw view of thestring of GraphQL being sent, as well as a computed viewas the server interprets it. Having separate entries laidout as well as being able to view the machine-readablefragments in this way could be helpful to monitor anddebug GraphQL queries.

9: Graphcool

Flexible backend platform combining GraphQL+ AWS LambdaSite

Page 110: GraphQL or Bust · Preface:Introductionto GraphQL Withinthelastcoupleofyears,therehasbeenaresur-genceofdiscussionaroundAPIdesignstandardssuch as REST, gRPC, GraphQL, and many others

10 Tools and Extensions For GraphQL APIs 100

With flexible, scalable, serverless architecture the rage,having an agile backend ready to go is an interestingprospect, especially when it’s GraphQL compatible out-of-the-box. Graphcool is a platform to aidGraphQL schemadesign and app backend development, coming with avisual console to design and edit your your data schema,the ability to create advanced GraphQL data models,custom fields, and relations between data. With manyintegrations with popular tech like AWS Lambda, Algolia,and Auth0, Graphcool looks to be a powerful tool formodern database management.

Screenshot of the Graphcool console, where you can add new fields anddata relations.

10: Optics by Apollo

Optimize GraphQL queries Website | Apollo on Github

To round off our list of GraphQL tooling, last but certainlynot least is Optics, a product for monitoring GraphQLAPIs. Optics is an analytics solution for GraphQL APIsthat traces how queries run, helps you see what types ofqueries are being performed and their frequencies. ny As

Page 111: GraphQL or Bust · Preface:Introductionto GraphQL Withinthelastcoupleofyears,therehasbeenaresur-genceofdiscussionaroundAPIdesignstandardssuch as REST, gRPC, GraphQL, and many others

10 Tools and Extensions For GraphQL APIs 101

we’ve discussed before, API metrics are crucial, and anyweb API can benefit from adding an analytics solution totheir platform. Seeing request volumes displayed visually,aswell as having a better grasp onbottlenecks like latencyissues is necessary for optimizing performance and im-proving page load times.

Optics is developed by Apollo, who are big contributors tothe GraphQL ecosystem— their Apollo Client is a flexible,production ready GraphQL client for React and nativeapps, and Apollo also hosts events to spread GraphQLknowledge.

Example Optics visualization on latency trends over time

Final Thoughts

Other significant tools include Thunder, aGraphQL serverfor Go, Join Monster, an NPM package for arbitratingissues between GraphQL and SQL database, or Dgraph,a fast database that works with GraphQL.

Page 112: GraphQL or Bust · Preface:Introductionto GraphQL Withinthelastcoupleofyears,therehasbeenaresur-genceofdiscussionaroundAPIdesignstandardssuch as REST, gRPC, GraphQL, and many others

10 Tools and Extensions For GraphQL APIs 102

“Great tools are will what will make GraphQLubiquitous” -Lee Byron, GraphQL/Facebook

There are many more that seem to be emerging daily;hopefully with the advent of tools like the ones men-tioned in this article, more providers can reap the ben-efits of GraphQL and increase general extensibility withexpending little effort.

Did we leave out any awesome GraphQL tools? Pleasecomment below!

Resources

• Facebook’s Draft RFC Specification for GraphQL• Visit the Awesome GraphQL List for many moreGraphQL tools.

Page 113: GraphQL or Bust · Preface:Introductionto GraphQL Withinthelastcoupleofyears,therehasbeenaresur-genceofdiscussionaroundAPIdesignstandardssuch as REST, gRPC, GraphQL, and many others

What The GraphQLPatent Release MeansFor the API Industry

GraphQL has driven much of the conversation aroundmodern API web design, and for good reason — it’s pow-erful, extensible, and very useful for high data query ap-plications. The ability to request data in a predetermined,knowable format, and the ability to collate endpoints intoa single external point, has made GraphQL somethingthat powers some pretty huge projects.

Unfortunately, reliance on anear-ubiquitous format comeswith a negative – when a change is made to GraphQL,its effects are wide-ranging and significant. This can beseen in the recent troubles concerning GraphQL patentlicensing and the disputes that have arisen – a simple

Page 114: GraphQL or Bust · Preface:Introductionto GraphQL Withinthelastcoupleofyears,therehasbeenaresur-genceofdiscussionaroundAPIdesignstandardssuch as REST, gRPC, GraphQL, and many others

What The GraphQL Patent Release Means For the API Industry 104

change of license format and the resultant understanding(and in some cases, misunderstanding) in the communityhas sent shockwaves through the API landscape.

Today, we’re going to talk about some purported issuesrelated to the GraphQL patent release to provide con-text and a bit of clarity. We’ll take a look at whether ornot the GraphQL license issue is as significant as firstthought, and more to the point, what the newly releasedpatent scheme from GraphQL actually means for mostproviders.

Background

For those who don’t knowwhat GraphQL is, it can broadlybe summarized as an application layer query language.GraphQL interprets strings from the client, and returnsdata in an understandable, predictable, pre-definedman-ner. This is a very short, summarized explanation of whatGraphQL does, but there is so much more that makes itspecial – for a more complete summary, check out ourpiece on the potential benefits of GraphQL adoption.

What ismore important to this discussion is howGraphQLwas created. After internal development began in 2012at Facebook, GraphQL was released publicly in 2015,offering an alternative to the dominant architectures ofthe API space, notably REST.

GraphQL was initially developed to help Facebook copewith challenges in fetching specific data from their collec-tion of services without introducing bloat and complexity.By allowing the client to define the expected data for-mat, Facebook, through GraphQL, was able to design a

Page 115: GraphQL or Bust · Preface:Introductionto GraphQL Withinthelastcoupleofyears,therehasbeenaresur-genceofdiscussionaroundAPIdesignstandardssuch as REST, gRPC, GraphQL, and many others

What The GraphQL Patent Release Means For the API Industry 105

methodology to deliver data in a more usable, efficientmanner.

This usability and efficiency was very attractive to manyearly adopters. Companies like Pinterest, GitHub, andShopify quickly began to use GraphQL either wholesaleor in part. During the rush to adopt GraphQL, however,there were looming, unresolved questions arising fromGraphQL’s creation. There was no licensing language inthe public release, or information on whether or notthe language was patented, and whether or not legalramifications were possible. Many questions were leftunanswered.

Developers Express Concern

In September of 2017,GitLabofficially froze their GraphQLproject due to these concerns. In a GitLab issues post,senior director of legal affairs Jamie Hurewitz stated thatthe BSD+Patents license, which Facebook had adopted totry and alleviate patent concerns, was concerning.

“If we were to allow this license, it could lead topotential future conflicts with software licensedunder Apache. Also, we could be impairing thefuture rights of our customers. Essentially, thisis not really an open source product basedon the implications of the license. While thereis no payment of cash, payment is in the formof giving up future rights.”

The license that had been inserted into the GraphQLrelease allowed for the use of GraphQL under certain

Page 116: GraphQL or Bust · Preface:Introductionto GraphQL Withinthelastcoupleofyears,therehasbeenaresur-genceofdiscussionaroundAPIdesignstandardssuch as REST, gRPC, GraphQL, and many others

What The GraphQL Patent Release Means For the API Industry 106

terms that removes your license to use GraphQL underthe following terms:

“The [patent] license granted…will terminate …if you … initiate directly or indirectly, or take adirect financial interest in, any Patent Assertion:(i) against Facebook … (ii) against any party ifsuch Patent Assertion arises … from any soft-ware… of Facebook … or (iii) against any partyrelating to the Software.”

In other words, developers were free to use GraphQL,as long as they never challenged Facebook over patentinfringement from anything built upon their system byFacebook. Unresolved issues caused outrage among pro-grammers. It was very significant for the community ofGraphQL adoptees, and led to many developers pullingaway from Facebook and its new patent.

Developer and attorney Dennis Walsh subsequently dis-cussed this issue in a lengthy analysis onMedium,whereinhe posited that “Whether Facebook wants to assert thesepatents is the province of gut feelings and lore. I don’t believethat Facebook ever offensively litigated a patent, but thepotential for litigation is more than theoretical — it’s very realif they choose that path.” It was clear that for developerslike Walsh, the idea that you had a license to GraphQLas long as you didn’t try to patent or protect your ownprocesses and developments was troublesome.

On August 30th, the co-inventor of GraphQL at Facebook,Lee Byron, addressed concerns on GitHub, and statedthat he was “aware” of the patent problem, and that itwas currently being worked on. He stated:

“I’ll bring this to the attention of our legal coun-

Page 117: GraphQL or Bust · Preface:Introductionto GraphQL Withinthelastcoupleofyears,therehasbeenaresur-genceofdiscussionaroundAPIdesignstandardssuch as REST, gRPC, GraphQL, and many others

What The GraphQL Patent Release Means For the API Industry 107

cil for their suggestion on how to resolve thisissue. We definitely want to ensure the com-munity has all necessary rights to be able touse GraphQL! I’ll make sure we get a speedyresolution.”

Finally, on September 26th, 2017, Facebook relicensedGraphQL under an OWFa 1.0 license, granting a per-petual license to users of GraphQL. While this definitelyimproves the situation, easing many of the developerissues surrounding the issue, there may still be somecause for concern.

Out of the Frying Pan…

There’s still some cause for concern around the new li-censing scheme, however. Facebookhas broadly adoptedtheMIT license, which doesn’t expressly include a patentgrant. There was some concern expressed, such as thatof RedMonk founder Stephen O’Grady, that adopting MITover the Apache license, which gave a more clear patentsituation to developers, created new concerns:

“The problem is that by choosing this approach,Facebook does not convey with the MIT licenseany patent grants as they would have under theApache. If Facebook has patents that read onReact, in other words, users of that softwareare not given an explicit license to them viaMIT,only an untested implicit license.”

To O’Grady, this essentially means that Facebook hasresolved one patent issue by introducing a second.

Page 118: GraphQL or Bust · Preface:Introductionto GraphQL Withinthelastcoupleofyears,therehasbeenaresur-genceofdiscussionaroundAPIdesignstandardssuch as REST, gRPC, GraphQL, and many others

What The GraphQL Patent Release Means For the API Industry 108

Many of these issues are ones that must be tested tobe confirmed – in other words, until a patent infringe-ment suit is drawn against or by Facebook, most ofthe concerns are simply conjecture. Even so, the factremains that this continues to be, for some, a concern-ing development. This is certainly an artifact of the APIdevelopment world as a whole, and is something that willhave to be tested, vetted, deprecated, and rebuilt as timegoes on.

Patents in the United States were originally envisionedduring a time where reproduction could take months atgreat expense to the creator. Patents were put in placeto “promote the progress of science and useful arts”according to its Constitutional call. At the time, the ideaof rapidly developing upon an open source standard andforking these projects into additional sub-developmentswas simply impossible to imagine, and as such, applyingpatents to the modern web world is resulting in somesignificant complexity.

Is This a Concern?

That being said, there are just asmany pundits suggestingthat the issue has largely been blown out of propor-tion. The termination of a patent due to legal proceedingsis common in some spaces, and in fact has been practicedby policies applied to such juggernauts as the WebMcodec from Google. Such patent terminations, termed“defensive termination provisions”, are largely commonin enterprise implementations, and in many cases, theirfull teeth have yet to be significantly bared in a legalproceeding.

Page 119: GraphQL or Bust · Preface:Introductionto GraphQL Withinthelastcoupleofyears,therehasbeenaresur-genceofdiscussionaroundAPIdesignstandardssuch as REST, gRPC, GraphQL, and many others

What The GraphQL Patent Release Means For the API Industry 109

It should also be noted that the defensive terminationprovision as noted in Facebook’s GraphQL documenta-tion was not nearly as extreme as some others. TheMozilla Public License, for instance, not only strips yourpatent license in response to legal challenges, but yourcopyright license as well – without the copyright license,though you may lose the patent license, you could stillin theory continue to use the code. With a copyrighttermination, however, you would be legally obligated tostop using your derivative code entirely.

That is obviously a much more extreme type of licensetermination, but the issue remains at the forefront ofmany people’s discussions when adopting GraphQL.

Oil and Water

While some have tried to connect some sort of nefari-ous purpose to the patent issues at hand, the truth isthat what we’re witnessing is a collision of open sourceethoswith corporate reality. Facebook is a corporation,and as such, it’s to be expected that they would do every-thing they can to look after their best interest. This is anunfortunate fact of the corporate world, especially for apublicly traded company.

On the other hand, we have open-source philosophy;the idea that code should be shared, developed upon,refined, and extended, with minimal if any protectionsapplied to the foundational code base. While this is, intheory, benefits everyone – resulting in increase security,more refined code, and wider adoption – the fact is thata corporation like Facebook would likely find this sortof approach dangerous considering how many of their

Page 120: GraphQL or Bust · Preface:Introductionto GraphQL Withinthelastcoupleofyears,therehasbeenaresur-genceofdiscussionaroundAPIdesignstandardssuch as REST, gRPC, GraphQL, and many others

What The GraphQL Patent Release Means For the API Industry 110

core functions are driven by the codebase that is beingpatented.

Perhaps the most clear reason for much of this concernis the fact that intent can’t really be communicated inpatent legalese – whether or not Facebook would usesuch a patent agreement as ameans to attack developersis an entirely different conversation from whether ornot the actual patent license as it currently is would beacceptable to most developers. Unfortunately, the twotopics are being conflated, leading to the issue at hand.

Final Thoughts

So what does this all mean for the API space? It’s easy toassign nefarious intent to Facebook, but the reality is thatFacebook is a public company – as many companies inthe API community now are. This means that they havecertain concerns that they need to address, and certainexpectations concerning the use of their applications andcodebase.

That being said, stifling open source implementations isa significant issue – and while that’s not what’s happen-ing in this case, the reactions of some providers to therelicensing (such as dropping GraphQL in fear of possiblelegal issues) is understandable. That should be the take-away to all of this – while there are concerns about patentlicenses within the GraphQL license language, much ofthe fear is based on conjecture, and if the possibility offuture concern is significant enough to worry an organi-zation, they should consider moving away from GraphQLand into a more open-source friendly, freely licensedalternative.

Page 121: GraphQL or Bust · Preface:Introductionto GraphQL Withinthelastcoupleofyears,therehasbeenaresur-genceofdiscussionaroundAPIdesignstandardssuch as REST, gRPC, GraphQL, and many others

What The GraphQL Patent Release Means For the API Industry 111

If you do not intend on creating something that is mon-etized, or the new re-licensing scheme proposed is anacceptable mitigation, then by all means, continue touse GraphQL. If you still fear the possible issues in thefuture, ensure that your API can behave for a timewithoutGraphQL or any GraphQL-derived functionality. For thosesomewhere on the fence, do keep inmind that until thereis court action taken, these fears all conjecture.

Page 122: GraphQL or Bust · Preface:Introductionto GraphQL Withinthelastcoupleofyears,therehasbeenaresur-genceofdiscussionaroundAPIdesignstandardssuch as REST, gRPC, GraphQL, and many others

What The GraphQL Patent Release Means For the API Industry 112

## The GraphQL Community At Large

The community surrounding GraphQL has grown expo-nentially since developers caught wind. Now, with theevergrowing proof of its use in the case studies cited inthis volume, we see GraphQLmoving from fad status intoenterprise adoption.

If you would like to participate in the economy form-ing around GraphQL tooling, or to learn more aboutGraphQL strategy, there are events solely realted toGraphQL.We’ll surely cover the topic on the blog, but in-personGraphQL-specific events are listed on this event page site.

Stay Connected

Thank you again to our readers, event attendees, andevent sponsors andpartners. If you appreciatewhatwe’redoing, consider following @NordicAPIs and signing up toour newsletter for curated blog updates and future eventannouncements.

Page 123: GraphQL or Bust · Preface:Introductionto GraphQL Withinthelastcoupleofyears,therehasbeenaresur-genceofdiscussionaroundAPIdesignstandardssuch as REST, gRPC, GraphQL, and many others

Nordic APIs Resources

Visit our Youtube Page forDeep Dives

Watch full videos of high impact API-related talks onour Youtube Channel. In 2018 and beyond, we will befeaturing seminars on niche API topics in our LiveCasts;hour-long webinars on advanved topics given by corecommunity members.

Page 124: GraphQL or Bust · Preface:Introductionto GraphQL Withinthelastcoupleofyears,therehasbeenaresur-genceofdiscussionaroundAPIdesignstandardssuch as REST, gRPC, GraphQL, and many others

Nordic APIs Resources 114

More eBooks by NordicAPIs:

Visit our eBook page to download these eBooks for free!If you choose to purchase through LeanPub or Amazon,all proceeds go to the Red Cross’s efforts in Sweden.

HowtoSuccessfullyMarket anAPI: The bible for projectmanagers, technical evangelists, or marketing aficiona-dos in the process of promoting an API program.

The API Economy: APIs have given birth to a variety ofunprecedented services. Learn how to get the most outof this new economy.

API Driven-DevOps: One important development in re-cent years has been the emergence of DevOps — a disci-pline at the crossroads between application developmentand system administration.

Securing the API Stronghold: The most comprehensivefreely available deep dive into the core tenants ofmodernweb API security, identity control, and access manage-ment.

Developing The API Mindset: Distinguishes Public, Pri-vate, and Partner API business strategies with use casesfrom Nordic APIs events.

Page 125: GraphQL or Bust · Preface:Introductionto GraphQL Withinthelastcoupleofyears,therehasbeenaresur-genceofdiscussionaroundAPIdesignstandardssuch as REST, gRPC, GraphQL, and many others

EndnotesNordic APIs is an independent blog and this publica-tion has not been authorized, sponsored, or otherwiseapproved by any company mentioned in it. All trade-marks, servicemarks, registered trademarks, and regis-tered servicemarks are the property of their respectiveowners.

• Select icons made by Freepik and are licensed by CCBY 3.0

• Select images are copyright TwoboTechnologies andused by permission.

Nordic APIs AB ©

Facebook | Twitter | Linkedin | Google+ | YouTube

Blog | Home | Newsletter | Contact