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

Building a Web API with GraphQL

Building a Web API with GraphQL

https://trbmeetup.doorkeeper.jp/events/59184

現実の Web API は複雑なものになりがちで設計の悩みは尽きません。GraphQL は、API を提供するうえでありがちないくつかの問題に対するひとつの解決策を提供します。GraphQL は API のためのクエリ言語です。シンプルな文法でクライアントの要求を自然に、 また明確に記述できます。この発表では GraphQL とは何か、REST との比較、そして実際にアプリケーションを構築した事例について共有します。

Hibariya Hi

April 19, 2017
Tweet

More Decks by Hibariya Hi

Other Decks in Technology

Transcript

  1. Hello • Gentaro Terada (@hibariya) • Works at ESM, Inc.

    • A member of Idobata development team • A college student (engineering) • https://hibariya.org
  2. Building a Web API with GraphQL I’ll talk about: •

    What is GraphQL • How to Write a GraphQL Server • Practical GraphQL Server
  3. Difficulties w/ API Development • Multiple Round Trips • Over-fetching

    • Dealing with Association • Documentation https://flic.kr/p/obcZW9 (cropped)
  4. Multiple Round Trips Organization => Rooms => Members • GET

    /organizations/:id • GET /organizations/:org_id/rooms • GET /organizations/:org_id/rooms/:id/members Requests: Organizations Count * 2 + Rooms Count
  5. Over-fetching A client needs just its name. {“organization”: { “name”:

    “Tokyo Rubyist Meetup” “rooms”: [{..., “members”: { … }}, ...] “members”: [{...}, ...]}}
  6. Dealing with Association What associations should be included??? {“organization”: {

    “name”: “Tokyo Rubyist Meetup” “rooms”: [{..., “members”: { … }}, ...] “members”: [{...}, ...]}}
  7. Schema Describes the service • Type Definitions • Data Structure

    • Operations • Restrictions • Human-readable Descriptions
  8. What is GraphQL Summary: • GraphQL is a query language

    for API • API development is difficult • GraphQL is one of the best solutions
  9. Defining a Schema Describes the service • Type Definitions •

    Data Structure • Operations • Restrictions • Human-readable Descriptions
  10. Mutations For operations which have side-effects • Creating/updating/deleting entities •

    Marking messages as read • Joining/Leaving chat rooms • Sending mails
  11. How to Write a GraphQL Server Summary: • A schema

    can be defined w/ Ruby • Various protocols can be used • Mutations for operations which have side-effects
  12. Eager Loading? Message.includes(:room) won’t work: • A client might not

    need the association (:room) • Another client might need other associations
  13. Overload Protection • Too big/complex queries • Queries which causes

    too many communication with DB • Queries which take too long time https://flic.kr/p/aosdja
  14. Practical GraphQL Server Summary: • Connection is useful for pagination

    • Use batch-loading to avoid N+1 query • Protect overload with timeout and limiting query
  15. Conclusion • GraphQL solves common problems about Web API •

    You can use it with Ruby • There are common concerns and practical tips about implementing servers