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

NDC OSLO 2017

NDC OSLO 2017

Do you want a single endpoint to access your data? Fetch only the data your client needs all in a single network request? Evolve your API without versions? Well if the answer is yes to any of these questions then GraphQL might just be what you are looking for. GraphQL is a query language for your application and not your database. With GraphQL, developers can use composable typed queries to request and receive only what’s required from the server.

We’ll walk through an introduction to GraphQL, drawing comparisons with traditional RESTful API’s, highlighting the implications on server and client design. Live coding examples will be used to illustrate how to get started creating a GraphQL server including: defining a schema, connecting to a database, fetching/manipulating data and much more.

4e5fd4655e0c94ae66cebb466bf8e788?s=128

Sandeep Singh

June 16, 2017
Tweet

Transcript

  1. GOODBYE REST; HELLO GRAPHQL Sandeep Singh initialspark.co.uk @initial_spark

  2. ◦Modern API considerations & challenges ◦What it is, what it’s

    not and what GraphQL aims to solves? ◦GraphQL core concepts ◦Demo ◦Considerations Agenda @initial_spark
  3. ◦REST ◦SOAP ◦gRPC ◦OData ◦And many more … API Technologies

    @initial_spark
  4. ◦Architectural style ◦Resources ! a single resource e.g. api/patients (nouns)

    ◦Verbs ! GET, PUT, DELETE & POST ◦HATEOAS (Hypermedia As The Engine Of Application State) REST @initial_spark
  5. ◦Efficiency ◦Predictability ◦Versioning ◦Caching ◦Security, tooling, platforms, documentation and more

    Modern API considerations @initial_spark
  6. Let’s look at an example… @initial_spark

  7. @initial_spark

  8. Multiple round-trips (Under-fetching) Code Code REST API /patients /medications /allergies

    CLIENT @initial_spark api/patients/1
  9. Includes REST API /patients CLIENT api/patients/1?include=meds,allergies … /medications /allergies @initial_spark

  10. Over-fetching REST API /patients CLIENT … api/patients/1?include=meds,allergies @initial_spark

  11. Ad-hoc endpoints Code Code REST API /patients /medications /allergies /patients_summary

    CLIENT @initial_spark
  12. Ad-hoc endpoints CLIENT 1 REST API CLIENT 2 REST API

    REST API /patients_summary /patients_summary_mobile @initial_spark
  13. Building modern APIs can be difficult @initial_spark Q: So how

    does GraphQL fit in?
  14. GraphQL is a query language for your API. GraphQL allows

    developers to compose typed queries to request and receive only the data that’s required from the server in a single network request. “ @initial_spark
  15. @initial_spark

  16. ◦Specification ◦ Open sourced by Facebook in 2015 ◦Hierarchical ◦

    Objects with nested associations ◦Client specified queries ◦ Specify their own data needs against the capabilities exposed from the server ◦Strongly typed ◦ Server defines an application-specific type system What is GraphQL? @initial_spark
  17. ◦About graph databases ◦Assumes nothing about: ! Transport protocol !

    Data storage ◦A solution for binary streams e.g. file upload ◦Limited to JavaScript What GraphQL isn’t @initial_spark
  18. Server • .Net • JAVA • Scala • Python •

    And many more @initial_spark
  19. Q: What problems does it aim help us solve? @initial_spark

  20. Efficiency @initial_spark

  21. Efficiency query{ patient(id:"22344667"){ id firstName surname dateOfBirth gender nhsNumber medications(top:5){

    name dose prescribedOn } allergies { type recorded severity } } } { "data": { "patient": { "id": 1, "firstName": "Tom", "surname": "Smith", "dateOfBirth": "12/12/1980", "gender": "MALE", "nhsNumber": "12345678911", "medications": [ { "dose": "500mg twice a day", "name": "Amoxicillin", "prescribedOn": "10/01/2016" }, { "dose": "10mg once a day", "name": "Prednisolone", "prescribedOn": "01/05/2011" } ], "allergies":[] } } } @initial_spark
  22. Efficiency GraphQL API CLIENT 1 CLIENT 2 @initial_spark

  23. Versioning Evolution @initial_spark

  24. Versioning @initial_spark (http://graphql.org)

  25. Introspection @initial_spark

  26. Introspection { __schema{ types{ name } } } • Query

    schema, types and fields • Build tools • Auto complete /Validate • Code generation • Documentation @initial_spark
  27. Introspection @initial_spark

  28. @initial_spark

  29. REST GraphQL Persistence Business Logic HTTP Authentication Authorisation Technology Stack

    @initial_spark
  30. REST GraphQL Conceptual Model Resources Graph Related operations Yes No

    Introspection No Yes Data typing Weak Strong Real-Time No Yes Comparison @initial_spark
  31. GraphQL Core Concepts @initial_spark

  32. Schema Type System Operations GraphQL Core Concepts @initial_spark

  33. Type system @initial_spark • Object type • Scalar types •

    Enumeration Types • Lists • Interfaces • Unions type Medication{ id: Integer name: String dose: String } type Patient{ id:Integer identifier:String! firstName:String surname:String dateOfBirth:String isDeceased:Boolean medications: [Medication] }
  34. Resolve const PatientType = new GraphQLObjectType({ name: 'Patient', description: 'A

    Patient in the EHR.', fields: { name: { type: GraphQLString, description: ’Name of patient.', resolve(obj, args, ctx){ return ’Tony Stark'; } } ... }, }); • Call business logic • Map object • Call existing REST API • Query and mutate data • Applies to all fields @initial_spark
  35. Operations | Queries @initial_spark

  36. Operations – Queries @initial_spark

  37. Operations | Mutations @initial_spark

  38. Operations - Mutations @initial_spark

  39. Schema @initial_spark

  40. Schema @initial_spark const schema = new GraphQLSchema({ query: new GraphQLObjectType({

    name: 'RootQueryType', fields: { patient: { type: PatientType, description: 'Gets patient by nhs number', args: { nhsNumber: { type: new GraphQLNonNull(GraphQLString) } }, resolve: (obj, args, context) => context.db.getPatient(nhsNumber) } }), mutation: //optional subscription: //optional });
  41. Demo @initial_spark

  42. Considerations @initial_spark

  43. Caching ◦ Client and app server ◦ Can’t use network

    caching e.g. Varnish, Squid etc ◦ Solution: Cache queries (normalised cache) @initial_spark
  44. Performance ◦ Optimise queries/mutations ◦ N+1 problem ◦ Solution: Loaders

    - Batching @initial_spark
  45. Security ◦ Don’t expose anything you don’t want to be

    public ◦ Malicious queries ◦ Solution: Timeouts, max query depth/query complexity analysis @initial_spark
  46. Error handling ◦ Can’t use HTTP codes to provide information

    ◦ Surfacing errors to user(s) ◦ Solution: Validation, return errors in response object @initial_spark
  47. Q: Use cases? @initial_spark

  48. ◦http://graphql.org/learn/ ◦https://github.com/chentsulin/awesome-graphql ◦https://github.com/apollographql/apollo-client ◦https://github.com/initialspark/goodbye-rest-hello-graphql ◦http://graphql.org/swapi-graphql/ Resources @initial_spark

  49. Thank you ! You can find me at @initial_spark &

    initialspark.co.uk