Early Praise for Craft GraphQL APIs in Elixir with Absinthe Like GraphQL’s meteoric rise, this book is sure to be a breakout hit for readers looking to revolutionize the way they write APIs. Ben and Bruce combine their Absinthe expertise with their production experience to take readers from the basics of GraphQL to exercising its most powerful features with Elixir and Phoenix. ➤ Chris McCord Author, Phoenix framework If we’re lucky, about once per decade or so we’ll come across a technology that has the chance to revolutionize the Web. GraphQL is one such set of technologies. This book is written by two of the industry’s experts—co-authors of one of the best and most complete GraphQL implementations. Even if you’re not planning to deploy on Elixir, this book will show you GraphQL done right. ➤ Chad Fowler Microsoft and BlueYard Capital Absinthe single-handedly made one of the most critical and complex parts of Trailpost’s infrastructure the piece I worry about least. This book should be on the radar of anyone developing APIs in Elixir, and probably some who aren’t. ➤ Daniel Pehrson Founder, Trailpost.com GraphQL is a broad but rewarding topic, and Bruce and Ben have covered it comprehensively. The book introduces the key GraphQL concepts in a very ap- proachable way. It then makes sure you have all the tools and techniques to build robust, well-structured, and incredibly fast GraphQL APIs using Elixir, Absinthe, Ecto, and Phoenix. A killer combination for building amazing applications if ever there was one! ➤ Josh Price Technical Director, Alembic GraphQL is a game changer, and now you can use it with Elixir! This book is an invaluable must-read for any Elixir developer. I referred to it often as I helped prepare our web team for the next generation of APIs. ➤ Daniel Berkompas Senior Software Engineer, Infinite Red; Creator of LearnElixir.tv & LearnPhoenix.tv Craft GraphQL APIs in Elixir with Absinthe Flexible, Robust Services for Queries, Mutations, and Subscriptions Bruce Williams Ben Wilson The Pragmatic Bookshelf Raleigh, North Carolina Many of the designations used by manufacturers and sellers to distinguish their products are claimed as trademarks. Where those designations appear in this book, and The Pragmatic Programmers, LLC was aware of a trademark claim, the designations have been printed in initial capital letters or in all capitals. The Pragmatic Starter Kit, The Pragmatic Programmer, Pragmatic Programming, Pragmatic Bookshelf, PragProg and the linking g device are trade- marks of The Pragmatic Programmers, LLC. Every precaution was taken in the preparation of this book. However, the publisher assumes no responsibility for errors or omissions, or for damages that may result from the use of information (including program listings) contained herein. Our Pragmatic books, screencasts, and audio books can help you and your team create better software and have more fun. Visit us at https://pragprog.com. The team that produced this book includes: Publisher: Andy Hunt VP of Operations: Janet Furlow Managing Editor: Brian MacDonald Supervising Editor: Jacquelyn Carter Series Editor: Bruce A. Tate Copy Editor: Nicole Abramowitz Indexing: Potomac Indexing, LLC Layout: Gilson Graphics For sales, volume licensing, and support, please contact [email protected]. For international rights, please contact [email protected]. Copyright © 2018 The Pragmatic Programmers, LLC. All rights reserved. No part of this publication may be reproduced, stored in a retrieval system, or transmitted, in any form, or by any means, electronic, mechanical, photocopying, recording, or otherwise, without the prior consent of the publisher. Printed in the United States of America. ISBN-13: 978-1-68050-255-8 Encoded using the finest acid-free high-entropy binary digits. Book version: P1.0—March 2018 Contents Acknowledgements . . . . . . . . . . . ix Introduction . . . . . . . . . . . . . xi Part I — Build a GraphQL API 1. Meet GraphQL . . . . . . . . . . . . 3 On the Client 3 On the Server 8 Absinthe and the Tech Stack 13 Moving On 14 2. Building a Schema . . . . . . . . . . . 15 Preparing the Application 15 Our Schema Module 16 Making a Query 21 Running Our Query with GraphiQL 24 Testing Our Query 27 Moving On 29 3. Taking User Input . . . . . . . . . . . 31 Defining Field Arguments 31 Providing Field Argument Values 35 Using Enumeration Types 41 Modeling Input Objects 44 Marking Arguments as Non-Null 48 Creating Your Own Scalar Types 50 Moving On 57 4. Adding Flexibility . . . . . . . . . . . 59 Organizing a Schema 59 Contents • vi Understanding Abstract Types 63 Using Named Fragments 74 Moving On 76 5. Making a Change with Mutations . . . . . . . 77 Defining a Root Mutation Type 77 Building the Resolver 80 Handling Mutation Errors 86 Moving On 95 6. Going Live with Subscriptions . . . . . . . . 97 Setting Up Subscriptions 98 Event Modeling 100 Submitting Subscriptions 108 Testing Subscriptions 111 Subscription Triggers 114 Moving On 120 Part II — Publish Your API 7. Resolution Middleware . . . . . . . . . . 123 Our First Module 123 Applying Middleware 127 Setting Defaults 132 Moving On 137 8. Securing with Authentication and Authorization . . . 139 Logging In 139 Using the Execution Context 148 Securing Fields 153 Structuring for Authorization 162 Moving On 165 9. Tuning Resolution . . . . . . . . . . . 167 Understanding the Problem 169 Using Built-in Plugins 176 Discovering Dataloader 184 Moving On 191 Contents • vii Part III — Use Your API 10. Driving Phoenix Actions with GraphQL . . . . . . 195 Building an Action 196 Handling Input 203 Complex Queries 209 Moving On 219 11. Integrating with the Frontend . . . . . . . . 221 Starting Simple 221 Choosing a Framework 229 Using Apollo Client 231 Using Relay 243 Wrapping Up 258 A1. GraphQL Types. . . . . . . . . . . . 261 Object 261 InputObject 261 Enum 262 Interface 263 Union 263 Scalar Types 264 Special Types 266 Bibliography . . . . . . . . . . . . 269 Index . . . . . . . . . . . . . . 271 Acknowledgements We’d like to thank our editor, Jackie Carter, and the rest of the staff at The Pragmatic Bookshelf for their guidance and assistance turning this book into a reality. While it’s a cliché, writing a book is hard work…and it would have been immeasurably more difficult without your help. Likewise, a small army of technical reviewers—Andrea Leopardi, Brian O’Grady, Chad Wooley, Chengyin Liu, Gabor Hajba, Jack Marchant, James Fish, Jesse Cooke, Kim Shieir, Lou Xun, Mark Goody, Nate Vick, Paulo A. Pereira, Rodrigo Franco, and Sebastian Kosch—helped us improve the content and code in this book. Any remaining issues fall squarely and solely on our shoulders. Bruce would like to thank his wife, Melissa, and their three sons—Braedyn, Jamis, and Cole—without whose love, support, and deep, abiding well of patience, no book would be worth writing (or would get done in the first place). He’d also like to thank Maria Gutierrez, a dear friend who he’ll eventually forgive for the gentle nudge that convinced him to invest the time to write another book. Ben is grateful to his colleagues, friends, and family for their seemingly endless willingness to listen, offer advice, and humor the most insane ideas throughout this process. In particular, Ben wants to thank his wife, Becca, whose constant care and dedication to those around her serves as both an inspiration and a daily joy. Finally, we’d like to show our appreciation for those who have contributed to Absinthe, the project this book covers. We deeply appreciate the time and encouragement given to us by José Valim and Chris McCord as the Absinthe project has grown. Their answers to hard questions and warnings about pitfalls, their open minds and imaginations, have made all the difference between the project becoming a fun yet subtly broken toy, and a robust, useful tool for the Elixir/Phoenix community they lead. report erratum • discuss