Upgrade to Pro — share decks privately, control downloads, hide ads and more …

From Restful to GraphQL

chema
November 24, 2017

From Restful to GraphQL

De RESTful a GraphQL: revolucionando la forma de comunicación entre cliente y servidor

GraphQL es el candidato predestinado a sustituir REST, sobre todo en el ecosistema móvil dónde los desarrolladores creamos productos cada vez más complejo más allá de un simple CRUD.

La migración de algunas de las APIs y servicios más populares está demostrando exponencialmente que el futuro de GraphQL está cada vez está más cerca. Facebook es su principal impulsor desde 2012 construyendo sus servicios en torno a ella, así como Github o Shopify

En esta charla vamos a repasar la evolución de API REST a GraphQL como un query language para escribir APIs, así como sus principios fundamentales: la introspection, type system o ejecución de query/mutation.

También veremos cómo añadir GraphQL a tu arquitectura tanto en server side como en cliente para aprovechar al máximo la tecnología. Repasaremos algunas de las herramientas que nos facilitarán la tarea de construir y usar APIs GraphQL.

La charla es una evolución del post introductorio que escribí en Genbeta Dev ¿Por qué deberíamos abandonar REST y empezar a usar GraphQL en nuestras APIs? y la charla que impartí en el pasado T3chfest sobre GraphQL.

chema

November 24, 2017
Tweet

More Decks by chema

Other Decks in Technology

Transcript

  1. 3 “Instead of working with rigid server-defined endpoints, you can

    send queries to get exactly the data you’re looking for in one request”
  2. 5

  3. Reviewing RESTful - Define separate resources. Fetch via URI -

    These resources are manipulated using HTTP requests where the method (GET, POST, PUT, PATCH, DELETE) has specific meaning. - Discover resources, thanks to HATEOAS (Hypertext As The Engine Of Application State). 7
  4. Collections of API RESTFul Endpoint resources GET /posts - Retrieves

    a list of posts GET /posts/12 - Retrieves a specific post GET /posts/12/comments - Retrieves comments GET /posts/12/comments/42/ - Retrieve specific comment POST /posts - Creates a new post PUT /posts/12 - Updates post #12 with payload provided PATCH /posts/12 - Partially updates post #12 DELETE /posts/12 - Deletes post #12 9
  5. Example Payload JSON { "name": "Luke Skywalker", "height": "172", "mass":

    "77", "hair_color": "blond", "skin_color": "fair", "eye_color": "blue", "birth_year": "19BBY", "gender": "male", "homeworld": "http://swapi.co/api/planets/1/", "films": [ "http://swapi.co/api/films/6/", "http://swapi.co/api/films/3/", "http://swapi.co/api/films/2/", "http://swapi.co/api/films/1/", "http://swapi.co/api/films/7/" ], "species": [ "http://swapi.co/api/species/1/" ], "vehicles": [ "http://swapi.co/api/vehicles/14/", "http://swapi.co/api/vehicles/30/" ], "starships": [ "http://swapi.co/api/starships/12/", "http://swapi.co/api/starships/22/" 10
  6. 12

  7. 13 Where is my API? Where are my endpoints? Why

    does it not work? How many endpoint will be needed? How many changes should we do?
  8. Versioning APIs: breaking changes 17 What is the correct way

    to version my API? - The URL way? /api/v1/post/12232 V2, v3, v4….?? - The Header way? GET /api/article/1234 HTTP/1.1 Accept: application/vnd.api.article+xml; version=1.0
  9. Why not like REST? - Most REST API are really

    Ad-hoc RPC with custom endpoint definitions. Time spent maintaining many versioned endpoint - REST requires many requests (many Roundtrips) - With REST, you request too much or too little data REST often turns into a maze of poorly-documented endpoints - Weak Typing and Poor Metadata 18
  10. 19

  11. 21

  12. 22

  13. GraphQL is a query language, like SQL? You don’t connect

    GraphQL directly to your backend or database. It’s an API layer, just like REST. GraphQL can be layered over multiple backends and databases, without the client being aware of where the data is coming from, just like REST. 23
  14. “GraphQL is a query language designed to build client applications

    by providing an intuitive and flexible syntax and system for describing their data requirements and interactions.” - GraphQL Specification https://facebook.github.io/graphql/ 24
  15. Query Language “hello world” Query { me { name }

    } { "me": { "name": "@durbon" } } 27
  16. { speaker(id: 27) { name profilePics { width height url

    } } } { "speaker": { "name": "@durbon" "profilePics" : { "width": 250, "height": 250, "url": "http://avatarurl.com/250.jpg" } } } Ask for you want 28
  17. { speaker(id: 27) { name twitter profilePics(size: 640) { width

    height url } } } { "speaker": { "name": "Txema Rodríguez" "twitter": "@durbon" "profilePics" : { "width": 640, "height": 640, "url": "http://avatar.com/640.jpg" } } } Ask for you want 29
  18. { speaker(id: 27) { name, licPic: profilePics (size: 90){ width,

    height, url }, bigPic: profilePics (size: 800){ width, height, url } } } "speaker": { "name": "Txema Rodríguez" "licPic" : { "width": 90, "height": 90, "url": "http://avatar.com/90.jpg" }, "bigPic" : { "width": 800, "height": 800, "url": "http://avatar.com/800.jpg" } } } Ask for you want 30
  19. Nested connection resources { me { name talks { title

    } } } { "me": { "name": "@durbon" "talks" : [ { title: "GraphQL is cool" }, { title: "API REST is dead" }, { title: "Kotlin in Android" },.. 31
  20. { latestTalk { title, speaker { name, twitter } },

    allSpeakers { name } } { "data": { "latestTalk": { "title": "¿Por qué deberíamos abandonar REST?", "speaker": { "name": "Txema Rodríguez", "twitter": "@durbon", } }, "allSpeakers": [ { "name": "Txema Rodriguez" }, { "name": "David Bonilla" } ] } } 32 Combining Queries
  21. 33

  22. Mutation: also you can write using GraphQL: mutation { writePost

    (input : { author: “durbon”, title: “graphql for beginners” content: "it's awesome." }) { id, title } } 34
  23. Type System GraphQL schema language it's similar to the query

    language, and allows us to talk about GraphQL schemas in a language-agnostic way. 36
  24. Schemas and types - Object types with fields: speakers, talks,...

    - Scalar types: Int, Float, String, Boolean, ID - Lists and Non-Null - Arguments: every field on a GraphQL object type can have zero or more arguments - Enumeration types: a special kind of scalar that is restricted to a particular set of allowed values 37
  25. The GraphQL schema provides a clear contract for client-server communication

    Client Backend Possibilities GraphQL Type System GraphQL Schema Requirements GraphQL Languages Queries Mutation App Server View 38
  26. Schema type Query { me: Speaker speaker (id: Int): Speaker!

    } type ProfilePicture { width: Int! height: Int! url: String! } type Speaker { name: String! profilePicture(size: Int = 50): ProfilePicture talks: [Talks!] } 39 input TalkInput{ content: String! author: Speaker! } type Mutation { createTalk: (input: TalkInput): Talk } type Talk { author: Speaker! content: String! }
  27. IntrospectionQuery { __type(name: "Speaker") { name description } } {

    "data": { "__type": { "name": "Speaker", "description": "The speaker of a talk.", } } } 41
  28. IntrospectionQuery query IntrospectionQueryTypeQuery { __schema { queryType { name fields

    { name description type { name kind } } } } } { "data": { "__type": { "name": "Developer", “Description”: “Name developer” "fields": [ { "name": "id", "type": { "name": null, "kind": "NON_NULL" } }, { "name": "name", "type": { "name": null, "kind": "NON_NULL" } 42
  29. Documentation by default Generates API documentation for our consumers, and

    prevents us from spending precious coding time on documentation. 43
  30. 44

  31. Execution After being validated, a GraphQL query is executed by

    a GraphQL server which returns a result that mirrors the shape of the requested query 47
  32. 48

  33. Object, consisting of two major components: • the schema definition

    • the actual implementation in the form of resolver functions 50 Structure vs Behaviour
  34. Think in Graph, not endpoint Fields independently of each other.

    Apply different context in order to retrieve such data 51
  35. Each field on each type is backed by a function

    called the resolver which is provided by the GraphQL server When a field is executed, the corresponding resolver is called to produce the next value. 52
  36. 54 Every feature you build first manifests itself in the

    GraphQL schema — then gets implemented through corresponding resolvers it allows frontend developers to start working against a mocked API, before it is actually implemented by backend developers Schema First development
  37. 56

  38. 57

  39. 60

  40. 64

  41. Javascript Python (graphene) Scala (sangria) Ruby Java Clojure Go PHP

    C# .NET Elixir Swift …. graphql.org/code/ 65
  42. 67

  43. Public GraphQL APIs 68 Early Github GraphQL API https://developer.github.com/early-access/graphql/explorer/ Yelp

    https://www.yelp.es/developers/graphql/guides/intro SWAPI http://graphql.org/swapi-graphql/ More APIs https://github.com/APIs-guru/graphql-apis
  44. Benefits of Exposing Data Through GraphQL - Boost your client

    development: combining and Querying Data and Picking Your Payload - Specification: the spec determines the validity, Strongly Typed, hierarchical with nested fields - Structure vs Behaviour. This allows you to focus on separation of concerns, not technologies. 69