Successfully reported this slideshow.
We use your LinkedIn profile and activity data to personalize ads and to show you more relevant ads. You can change your ad preferences anytime.

GraphQL over REST at Reactathon 2018

750 views

Published on

GraphQL is quickly becoming mainstream as one of the best ways to get data into your React application. When we see people modernize their app architecture and move to React, they often want to migrate their API to GraphQL as part of the same effort. But while React is super easy to adopt in a small part of your app at a time, GraphQL can seem like a much larger investment. In this talk, we’ll go over the fastest and most effective ways for React developers to incrementally migrate their existing APIs and backends to GraphQL, then talk about opportunities for improvement in the space. If you’re using React and are interested in GraphQL, but are looking for an extra push to get it up and running at your company, this is the talk for you!

Published in: Technology

GraphQL over REST at Reactathon 2018

  1. 1. GraphQL over REST. Sashko Stubailo, @stubailo Open Source Lead, Apollo apollographql.com @apollographql
  2. 2. What’s Apollo? GraphQL (huge potential) You (have real work to do) Our mission is to bring the benefits of developing with GraphQL to you as quickly and easily as possible.
  3. 3. What’s GraphQL? 1. Define a schema for your data 2. Write a query to get the data you need It’s an API specification that is quickly replacing REST for how people communicate between their backends and frontends.
  4. 4. What do APIs have to do with React? It turns out, a lot of what’s complicated in today’s frontend development involves dealing with APIs and state management.
  5. 5. GraphQL removes complexity from the frontend. Reducers Sagas Optimistic UI .then .catch fetch Error handling Polling Retries Offline Normalization Instead of manipulating data on the client, you get it in just the shape that you need right away. Action creators
  6. 6. Apollo Client: GraphQL state management for React By enabling React developers to simplify their workflow, in the last 2 years Apollo Client has become the second most popular React state management solution, after only Redux!
  7. 7. And GraphQL + React is only getting better With new directions like client-side state management, and quick support for cutting-edge technology like React Async, with Apollo Client GraphQL and React are a match made in heaven.
  8. 8. There’s only one issue left. To get the most of all this, you need a GraphQL API.
  9. 9. GraphQL is often presented as a big rewrite, but you don’t have to do it that way. To get the main benefits for product development velocity we talked about above, you don’t need to rethink your architecture. You can get GraphQL working in just a few hours, and something running in production in days.
  10. 10. You’ve already got an API. If you work with React and don’t use GraphQL, you probably work with a REST API or similar. You often aren’t able to jump in and make major changes to the backend when you want. Even if you could, rewriting all your hard-built business logic probably isn’t a good idea. So what’s the solution? REST REST REST Complexity Your app
  11. 11. Put GraphQL over REST. Put a GraphQL layer in between your existing REST backends and your React app. Get all of the benefits of a GraphQL architecture without modifying your backends. From the point of view of the REST API, the same calls will be made as before. But now, the frontend doesn’t have to format, filter, and manage the data anymore. REST REST REST GraphQL API
  12. 12. Same feature, better result, less work GET /api/sandwich/bread GET /api/sandwich/meat GET /api/sandwich/toppings With REST Filter down data to what you want Do waterfall requests for related data and combine everything together yourself With GraphQL query { sandwich { bread { baguette } meat { turkey } toppings { avocado, tomato } } } ● Same REST API calls ● No roundtrips from the client ● No manual data reformatting and management ● Only get the fields you need - reduce bandwidth usage and increase performance A case study with sandwiches.
  13. 13. Article published by Medium literally yesterday:
  14. 14. GraphQL is changing the game. We talk to companies using GraphQL in production every day, and some teams tell us they can ship features fully twice as fast as before. That more than makes up for the effort of getting that new API up and running. Without GraphQL With GraphQL Existence of GraphQL Development Velocity 2x 1x
  15. 15. OK, so where do I start? Answer: With the schema.
  16. 16. Describe the API you wish you had. Design it based on the needs of your UI, but try to make it general purpose enough to evolve. We’ve found that teams are most successful when the GraphQL API is designed primarily by the frontend developers that will use it. Upcoming events Justin Timberlake @jtimberlake Beyoncé @beyonce Man of the Woods tour April 29, 2018 Man of the Woods tour June 14, 2018 Man of the Woods tour July 30, 2018
  17. 17. Coming up with part of our schema Upcoming events Justin Timberlake @jtimberlake Beyoncé @beyonce Man of the Woods tour April 29, 2018 Man of the Woods tour June 14, 2018 Man of the Woods tour July 30, 2018
  18. 18. Using graphql-tools to implement the schema github.com/apollographql/graphql-tools graphql-tools makes it easy to create a production-ready GraphQL schema using the schema language. Nostalgia: It’s one of the first libraries we’ve ever published and today most GraphQL servers use it!
  19. 19. Testing it out via mocking
  20. 20. Some GraphQL schema design tips Use field parameters for different versions of the same field, something you can’t easily do with REST! For ultimate future-proofing, use globally unique IDs to avoid depending on a specific backend. Stick to simple fields over general purpose fields that take complex queries. This makes your API easier to test and refactor. posts( searchQuery: String sort: SortOptions authorId: String tags: [String] ) searchPosts( query: String ) query { post(id: “asdf”) { title postedAt( format: “mm/dd/yyyy” ) } } # Don’t use SQL ids directly post(id: 5) # Have an abstracted ID post( id: “1224845c-4582” )
  21. 21. Now, fill in the data.
  22. 22. It’s just like filling in the blanks. GraphQL API types and fields REST API endpoints
  23. 23. Every GraphQL schema field is a function. You can think of a GraphQL schema as a web of tiny endpoints, and a query is a way of calling a bunch of them in one request. The function that implements a field is called a resolver, and it can do basically anything. Resolvers give GraphQL the flexibility of being a general-purpose API layer.
  24. 24. Your GraphQL resolvers can call your REST backend. We can take the REST data fetches from the client, and move them into the server. This organizes all our REST API calls in one place, removing data management complexity from the client.
  25. 25. Partially mocked data Real artist information from the API. Fake “Hello World” fields from the mock.
  26. 26. Let’s finish it up. Let’s take a partially implemented schema, and add a resolver to call one more endpoint. Now, with a single GraphQL query, we can retrieve data that used to take two endpoint fetches in a single request.
  27. 27. Fully API-driven data
  28. 28. Visualizing execution with Apollo Tracing + Engine
  29. 29. Tips when wrapping a REST API with GraphQL If your REST API has permissions, just pass through your header from the GraphQL request to the underlying REST API. The performance bar is that your new GraphQL API doesn’t make more REST calls than the equivalent view did in React. When you’re starting, build just enough data for one view of your app with one query. DB REST API REST API
  30. 30. Going to production
  31. 31. What do we need from our production GraphQL? Deploy and run just like any Node server. Tip: we found many teams already have this for server-side rendering. Performance monitoring is important to make sure UI doesn’t slow over time. Dataloader per-request caching will help reduce load on your REST backend. GraphQL result caching for commonly viewed data can make some queries nearly instant. REST REST REST GraphQL API
  32. 32. Deployment You can run a GraphQL server anywhere you can run Node, for example Heroku, or Zeit Now. If you’re talking to your REST backends from the GraphQL API, you probably want to run the new API in the same region for faster roundtrips. Check out the article on the Apollo Blog.
  33. 33. Monitoring GraphQL Since current APM tools are often built around endpoints, you’ll need to put in a little extra effort to identify the performance of different chunks of data. We recommend using meaningful query and mutation names, and organizing your stats using those. Apollo Engine is a tool/service we provide that sets this up for you, and lets you browse data in a GraphQL-specific way. apollographql.com/engine
  34. 34. Dataloader For cases where a single query would request the same resource multiple times, Dataloader can help you collapse them into one request by identifying the duplicates during execution. github.com/facebook/dataloader
  35. 35. GraphQL result caching Just like with REST API calls, you can cache the entire GraphQL result on a TTL, based on the query. There are a lot of ways you can set it up, but with the Apollo cacheControl extension and Apollo Engine, you can specify the cache expiration right in the schema.
  36. 36. TL;DR tips for GraphQL over REST 1. Design the GraphQL schema you want based on frontend needs 2. Fill in your schema with data from your existing REST endpoints 3. Optimize until you have the same number of fetches you used to do from the frontend Above all, do it fast, since it could make a huge difference in how long it takes to iterate on features.
  37. 37. GraphQL over REST. Sashko Stubailo, @stubailo Open Source Lead, Apollo apollographql.com @apollographql <Query query={GET_TODOS}> {({ loading, error, data }) => { if (loading) return <p>Loading...</p>; if (error) return <p>Error :(</p>; return data.todos.map(({ id, type }) => ( <p key={id}>{type}</p> )); }} </Query> Breaking news The new React API for Apollo Client shipped today, with the new Query component! dev-blog.apollodata.com

×