GraphQL

GraphQL
開発元 Facebookとコミュニティ
初版 2015年 (2015)
最新版
2018年6月[1]
リポジトリ github.com/graphql/graphql-spec
プログラミング
言語
JavaJavaScriptRubyScalaなど
対応OS クロスプラットフォーム
ライセンス 3条項BSDライセンス
公式サイト graphql.org ウィキデータを編集
テンプレートを表示

GraphQL(グラフQL)はAPI向けに作られたクエリ言語およびランタイムである[2]。 ベンダーフリーな GraphQL財団の支援を受け、開発が進められている[3]

ウェブAPIの開発に、RESTやその他のWebサービスと比較して、効率的で堅牢、かつ柔軟なアプローチを提供する。GraphQLでは、クライアントが必要なデータの構造を定義することができ、サーバーからは定義したのと同じ構造のデータが返される。したがって、必要以上に大きなデータが返されるのを防ぐことができクエリの効率が良い。また、柔軟性と豊かな表現が可能なクエリ言語は複雑さを加えるため、シンプルなAPIには適さない可能性もある[4][5][6]。GraphQLは、型システム、クエリ言語、実行セマンティクス、静的な検証、型チェックから構成される。

GraphQLは、データの問い合わせ (query)、書き換え (mutation)、購読 (subscription) をサポートする[7]

概要

GraphQLでは、クライアントがクエリ内容を記したdocumentを送信し、GraphQLサービスがクエリを実行し結果を返信する。documentDSLであるGraphQL query languageを用いて記述される[8]。以下の例は明日の天気を取得するクエリのdocumentとGraphQLサービスから返されたクエリ結果のJSONである。

// document
{
  tomorrow {
    weather
    rainyPercent
  }
}
{
  "tomorrow": {
    "weather": "cloudy",
    "rainyPercent": 30
  }
}

リソースをURLパスで表現するRESTful APIと異なり、GraphQLはリソースをdocumentで表現する。GraphQL WebAPIの場合、単一のAPIエンドポイントへこのdocumentをPOSTする(例:https://API.internal./graphqlエンドポイントへdocumentをBodyとしてPOSTする)ことでクエリが実行される(参考: アプリケーションプログラミングインタフェース#様式 )。

Documentを受け取ったGraphQLサービスはDocument中のfield (例: tomorrow) をトップレベルから1つずつresolverにより値へ解決する。クライアントが受け取りたい値はすべてfieldとして過不足なくDocumentに記載されているので、resolver群により全てのfieldを解決すれば過不足ないデータが1回のクエリで得られる。GraphQLサービス処理系はこのfieldからなるグラフ構造を上からresolverを用いて解決する役割を果たす。resolverはサービス実装者により実装される。

構造が事前に決められたリソースへアクセスするRESTful APIと異なり、GraphQLではその場でdocumentから与えられた構造に対しresolver群を連続適用して解決する。ゆえにRESTful APIでは定められたリソースしか1度のアクセスでは取得できないが、GraphQLではschema-validな任意のリソースを1度のアクセスで得られる。例えばRESTful APIでは「ある人の友人リスト」APIがあっても「ある人の友人の友人リスト」を得るためには1度友人リストを得たのちにクライアントからもう一度APIを叩く(クライアントで自前の再帰を行う)必要がある。一方GraphQLでは「Persion.friends field」resolverさえあれば{personA {friends {friends {name} } } }DocumentをPOSTするだけでresolverが連続適用されて「友人の友人リスト」が1度に得られる。

このようにGraphQLはクライアントからクエリ構造を渡せる柔軟性を持ち、また1度のクエリで必要十分な値のみを得られる効率性を持つ。

GraphQLサービスが受け入れられる型を、IDLである"type system definition language" (schema definition languageとも) で書かれたSchemaで記述する。

GraphQLはあくまでAPI仕様であり、通信方式の実装とは独立している。例えばGraphQL WebAPIを実装する際、documentをURLクエリ文字列に載せることも可能である(例:GET https://API.internal./graphql?query={tomorrow{weather}}[9]

機能

Arguments

GraphQLではargumentを用いたクエリの制御が可能である。GraphQLオブジェクトの各field(例: tomorrow)は0個以上のargumentsを持てる[10]。GraphQLサービスではクエリをトップレベルのfieldからresolverによって解決していくが、argumentsはその時にresolverへ渡されresolverの振る舞いを制御する[11]。次の例では"都道府県名/name" argumentと"天気/weather" argumentを用い、都道府県-街リストから東京/tokyoに含まれる晴れ/sunnyの街を取得する。

// document
{
  prefecture(name: "Tokyo") {
    prefName
    cities(weather: "sunny") {
      cityName
      rainyPercent
}}}
{
  "prefecture": {
    {
      "prefName": "Tokyo",
      "cities": [
        {
          "cityName": "Shinjuku",
          "rainyPercent": 10
        },{
          "cityName": "Ikebukuro",
          "rainyPercent": 0
}]}}}

directives

GraphQLではdirectivesを用いたクエリの制御が可能である。GraphQLオブジェクトの各field(例: tomorrow)はdirectiveを持てる[12]directivesは処理系に依存したあらゆる処理を指定するアノテーションである[13]。全ての処理系に実装されるdirectiveの例としてfieldの無視を指定する@include(if: Boolean)がある。

{
  sinjuku {
    weather
  }
  ikebukuro @include(if: false) {
    weather
    rainyPercent
}}
{
  "sinjuku": {
    "weather": "cloudy"
}}

全てのresolver@include相当の引数を用意すれば同等の機能を提供できるが、directivesを用いることでresolverに手を加えずかつdirective処理系1箇所での実装のみでこの機能を提供できる。

directivesはGraphQLサービス処理系以外にも利用されうる。例えばAWS AmplifyはSchema上のdirectivesに基づいたクラウドリソースプロビジョニングコード生成("GraphQL Transform")を実装している[14]@modelが付与されたfieldはresolverが自動で生成されかつDynamoDBにリソースが準備される。これはGraphQLサービス処理系ではなく、Amplify CLIによっておこなわれる。

形式

Document

Documentは1つ以上のOperationDefinitionからなる。1つのみの場合Nameが省略可能であり、さらにOperationTypeがqueryならこれも省略できる。

// document
OpType Name [VarDef][Directives] {
  ...
}
OpType Name [VarDef][Directives] {
  ...
}
// e.g.
query ExampleQuery1 {
  resource
}
query ExampleQuery2 ($var: S) @skip(if: false) {
  time
}

Field

FieldはNameからなっており、Alias, Arguments, Directivesを利用できる。さらにサブFieldを持つことができる。

// document
{
  [Alias] Name [Arguments][Directives] [SelectionSet]
}
// e.g.1 - simple
{  resource  }
// e.g.2 - full
{  time: resource (arg1: "arg") @skip(if:false) {  subResource  }  }

処理系

値解決

値解決(Value Resolution)はFieldの値を算出するステップである[15]ResolveFieldValue関数インターフェスに該当し、[オブジェクト型, オブジェクト値, field名, arguments]からfieldの値を生成する(例: Person型, Obamaオブジェクト, job fieldName, no argument => presidentfield value)。擬似JavaScriptコードで以下になる。

function ResolveFieldValue(objectType, objectValue, fieldName, argumentValues){
  const resolver = getExternalResolver(ojectType, fieldName);
  return resolver(objectValue, argumentValues);
}

歴史

GraphQLは、2012年にFacebookの内部で開発され、2015年に公開された[16]。2018年11月7日、GraphQLプロジェクトは、Facebookから非営利のLinux Foundationがホストする新たに設立されたGraphQL Foundationに移譲された[17][18]。2012年以来、GraphQLの利用数は、GraphQLの作者のLee Byronが想定したとおりのスケジュールに正確に従って増加している[19] 。Byronの目標は、GraphQLをWebプラットフォーム全体で利用されるようにすることである。

2018年2月9日、GraphQL Schema Definition Language(SDL)が仕様の一部となった[20]

実装

クライアント

GraphQLクライアントは適切なdocumentをGraphQL APIエンドポイントへPOSTするだけでクエリを実行できるため、ライブラリを採用せずとも容易にクエリを実行できる[21]

より高度な機能を有するGraphQLクライアント実装としては、Apollo Client[22]とRelay[23]がある。

サービス/サーバー

GraphQLサーバーは複数の言語で利用可能であり、Haskell、JavaScript[24]、Perl[25]、Python[26]、Ruby、Java、C#、Scala、Go、Elixir[27]、Erlang、PHP、R、Clojureで書かれたものがある。

利用例

GitHub API

GitHubは第4世代のAPIとしてGraphQL API「GitHub GraphQL API v4」を提供している[28]

GitHubはその選定理由として「more flexibility for our integrators(我々のインテグレータに対する更なる柔軟性)」を挙げている[29]。GitHubではIssueをプロジェクト管理アプリに組み込むシステムインテグレータ、CI/CDパイプラインを管理するエンジニアやライブラリ作者、レポジトリ統計を取り出す個人など、多様なAPI利用者を抱えている。その多様な要求から、全ての利用者に必要かつ十分な(オーバーフェッチもアンダーフェッチもしない)APIを提供することは困難である(無数のREST APIエンドポイント・サーバー実装は管理しきれない)。結果として一部の利用者にとっては柔軟性が足りなく感じられていた[30]。GitHubはレスポンス種に限りがあるREST APIから利用者側がレスポンス(クエリ構造)を指定するGraphQLにAPIを変更し、上記の問題を解決した。

関連項目

出典

  1. ^ GraphQL June 2018 Release Notes”. 26 March 2019閲覧。
  2. ^ GraphQL is a query language for APIs and a runtime for fulfilling those queries with your existing data. https://graphql.org/
  3. ^ GraphQL foundation. https://graphql.org/foundation/
  4. ^ “GraphQL vs REST: Overview” (英語). Phil Sturgeon. (2017年1月24日). https://phil.tech/api/2017/01/24/graphql-vs-rest-overview/ 2018年11月25日閲覧。 
  5. ^ “Why use GraphQL, good and bad reasons” (英語). Honest Engineering. (2018年8月4日). https://honest.engineering/posts/why-use-graphql-good-and-bad-reasons 2018年11月26日閲覧。 
  6. ^ GraphQL Fundamentals”. Howto GraphQL. 4 July 2018閲覧。
  7. ^ GraphQL”. facebook.github.io. Facebook. 4 July 2018閲覧。
  8. ^ Clients use the GraphQL query language to make requests to a GraphQL service. We refer to these request sources as documents. GraphQL specification
  9. ^ When receiving an HTTP GET request, the GraphQL query should be specified in the "query" query string. GraphQL
  10. ^ Every field on a GraphQL object type can have zero or more arguments GraphQL specification
  11. ^ Each field on each type is backed by a function called the resolver which is provided by the GraphQL server developer. When a field is executed, the corresponding resolver is called to produce the next value. GraphQL
  12. ^ A directive can be attached to a field or fragment inclusion, and can affect execution of the query in any way the server desires. GraphQL
  13. ^ Directives provide a way to describe alternate runtime execution and type validation behavior in a GraphQL document GraphQL Specification
  14. ^ Because the Todo type was decorated with an @model directive of the GraphQL Transform library, the CLI created the additional schema and resolvers for queries, mutations, and subscriptions as well as a DynamoDB table to hold the Todos. Amplify Libraries
  15. ^ This is exposed via ResolveFieldValue, which produces a value for a given field on a type for a real value. 6.4.2 Value Resolution
  16. ^ GraphQL: A data query language”. 2019年10月19日閲覧。
  17. ^ “Facebook’s GraphQL gets its own open-source foundation” (英語). TechCrunch. https://techcrunch.com/2018/11/06/facebooks-graphql-gets-its-own-open-source-foundation/ 2018年11月7日閲覧。 
  18. ^ “The Linux Foundation Announces Intent to Form New Foundation to Support GraphQL - The Linux Foundation” (英語). The Linux Foundation. (2018年11月6日). https://www.linuxfoundation.org/press-release/2018/11/intent_to_form_graphql/ 2018年11月7日閲覧。 
  19. ^ Anthony. “Is GraphQL Moving Toward Ubiquity?”. NordicAPIs. 2019年10月19日閲覧。
  20. ^ [RFC GraphQL Schema Definition Language (SDL) by leebyron · Pull Request #90 · graphql/graphql-spec]” (英語). GitHub. 2019年10月19日閲覧。
  21. ^ But you don't need a complex client to call a GraphQL server. With express-graphql, you can just send an HTTP POST request to the endpoint you mounted your GraphQL server on, passing the GraphQL query as the query field in a JSON payload. graphql.org
  22. ^ Introduction”. Apollo GraphQL Docs. 2019年10月19日閲覧。
  23. ^ Relay · A JavaScript framework for building data-driven React applications” (英語). relay.dev. 2019年10月19日閲覧。
  24. ^ A reference implementation of GraphQL for JavaScript: graphql/graphql-js, GraphQL, (2019-10-19), https://github.com/graphql/graphql-js 2019年10月19日閲覧。 
  25. ^ GraphQL - Perl implementation of GraphQL - metacpan.org”. metacpan.org. 2019年10月19日閲覧。
  26. ^ Graphene”. graphene-python.org. 2017年6月18日閲覧。
  27. ^ Absinthe: The GraphQL toolkit for Elixir”. 19 July 2018閲覧。
  28. ^ GitHub chose GraphQL for our API v4 GitHub Developer
  29. ^ because it offers significantly more flexibility for our integrators. GitHub Developer
  30. ^ Despite all the information we provided, we heard from integrators that our REST API also wasn’t very flexible. GitHub blog

外部リンク

Read other articles:

MontefiasconeKomuneComune di MontefiasconeMontefiasconeLokasi Montefiascone di ItaliaKoordinat: 42°32′25″N 12°02′13″E / 42.54028°N 12.03694°E / 42.54028; 12.03694Negara ItaliaWilayahLazioProvinsiViterbo (VT)FrazioniLe Coste, Le Grazie, Le Mosse, ZepponamiPemerintahan • Wali kotaMassimo PaoliniLuas • Total104,93 km2 (4,051 sq mi)Ketinggian590 m (1,940 ft)Populasi (30 November 2017)[1] �...

This is a list of notable YMCA buildings. Buildings for YMCA use are prominent in many cities and towns. Canada Birks Building (1901), in North Bay, Ontario, listed on Canadian Register of Historic Places in 2004 Shane Homes YMCA at Rocky Ridge (2018), in Calgary, Alberta, owned by city of Calgary Hong Kong YMCA of Hong Kong at 22 Salisbury road, Tsim Sha Tsui since 1922. In 1996, YMCA of Hong Kong established the College of Continuing Education.[1] India YMCA Institute of Engineering...

2012 studio album by You KikkawaVocalist?Studio album by You KikkawaReleasedNovember 7, 2012 (2012-11-07)Recorded2012GenreJ-popdance-popLength49:50LanguageJapaneseLabelUniversal JProducerHachioji PDarvishPKEINishizawasan PJunkyYairiMSRcoleteKameriaT-PocketYou Kikkawa chronology One for You!(2012) Vocalist?(2012) Two You(2013) Limited Edition cover Vocalist? (ボカリスト?, Bokarisuto?) is a cover album by Japanese singer You Kikkawa. Released through Universal J on N...

Pakistani soldier (1944-1971) Lance NaikMuhammad Mahfuz AwanNishan-e-HaiderBirth nameMahfoozNickname(s)BoxerBorn25 October 1944 (1944-10-25)Pind Malikan (now Mehfoozabad), Rawalpindi District, Punjab, British IndiaDied18 December 1971(1971-12-18) (aged 27)Wahga-Attari SectorBuriedMehfoozabad, Islamabad, PakistanAllegiance PakistanService/branch Pakistan ArmyYears of service1962–1971Rank Lance NaikUnit3/16th Punjab Regiment 15 Punjab RegimentBattles/warsIndo-Pakistan...

Arje Simon‏אריה סימון‎ major (Rav Seren) Data i miejsce urodzenia 1913 Moguncja Data i miejsce śmierci 2002 Tel Awiwu Przebieg służby Lata służby 1940−1950 Siły zbrojne Hagana Siły Obronne Izraela Jednostki Brygada Żydowska Główne wojny i bitwy II wojna światowa,wojna o niepodległość Arje Simon (ur. 1913; zm. 2002) – izraelski dowódca wojskowy w stopniu majora (Rav Seren), oficer dyplomowany Sił Obronnych Izraela, nauczyciel i pedagog. Młodoś

Japanese artist (1922–1971) Kiyoshi Yamashita on Ebisubashi Bridge, 1955 Kiyoshi Yamashita (山下 清, Yamashita Kiyoshi (born Seiji Obashi, 10 March 1922 – 12 July 1971) was a Japanese artist. He is famous for his wanderings throughout Japan, during which he often wore a sleeveless undershirt, garnering the nickname The Naked General. Early life Yamashita was born in Asakusa, Tokyo. At the age of three, he had an acute abdominal disorder which, although not life-threatening, left him wi...

Penyihir CintaNama alternatifMagician of Love versi IndonesiaGenre Drama Fantasi PembuatSinemArtBerdasarkanMagician of LoveDitulis olehSerena LunaSkenarioSerena LunaSutradaraMaruli AraPemeran Chelsea Olivia Jonathan Frizzy Andrew White Andrew Ralph Roxburgh Chacha Frederica Rorencia Natassia Yadi Timo Farah Debby Alexandra Gottardo Stefanie Hariadi Theresia Inggrid Kansil Maya Wulan Penggubah lagu temaUnguLagu pembukaBerjanjilah — UnguLagu penutupBerjanjilah — UnguNegara asalIndonesiaBaha...

Artikel ini perlu diwikifikasi agar memenuhi standar kualitas Wikipedia. Anda dapat memberikan bantuan berupa penambahan pranala dalam, atau dengan merapikan tata letak dari artikel ini. Untuk keterangan lebih lanjut, klik [tampil] di bagian kanan. Mengganti markah HTML dengan markah wiki bila dimungkinkan. Tambahkan pranala wiki. Bila dirasa perlu, buatlah pautan ke artikel wiki lainnya dengan cara menambahkan [[ dan ]] pada kata yang bersangkutan (lihat WP:LINK untuk keterangan lebih lanjut...

Das Marxists Internet Archive (MIA, auch bekannt als marx.org oder marxists.org) ist das größte Internet-Archiv von Originaltexten marxistischer Autoren und weiterer politisch linker Strömungen (Sozialisten, Anarchisten etc.). Die mehrsprachigen Editionen werden von einer Non-Profit-Organisation mit ehrenamtlichen Mitarbeitern erstellt. Vom MIA erstellter Inhalt steht unter der Creative Commons License. Inhaltsverzeichnis 1 Geschichte 2 Organisation 3 Inhalt 3.1 Marx & Engels Internet ...

Temple servant community in south India SataniRegions with significant populationsSouth IndiaAndhra Pradesh, Telangana, Tamil Nadu, KarnatakaReligion Hinduism Satani is a community that renders temple services in the states of Andhra Pradesh, Karnataka, Tamil Nadu and Telangana in India. Traditionally, they have rendered a variety of services as supervisors and purohits of minor temples, guardians of temple properties, heralds, singers and torch-bearers at festivals, bodyguards of Jiyars, and...

Covaxin Covaxin (tên mã là BBV152) là một loại vắc xin COVID-19 dựa trên virus bất hoạt được Bharat Biotech phối hợp với Hội đồng Nghiên cứu Y khoa Ấn Độ phát triển. Hiệu quả Vào tháng 7 năm 2021, Bharat Biotech báo cáo vắc xin có hiệu quả 64% đối với các trường hợp không có triệu chứng, 78% hiệu quả đối với các trường hợp có triệu chứng, 93% hiệu quả chống lại nhiễm COVID-19 nghiêm tr�...

Eva EvdokimovaBorn(1948-12-01)December 1, 1948Geneva, SwitzerlandDiedApril 3, 2009(2009-04-03) (aged 60)New York City, U.S.NationalityAmericanEducationRoyal Ballet SchoolOccupationdancerYears active1966-2005SpouseMichael S. GregoriCareerFormer groupsBerlin Opera Ballet, Royal Danish Ballet, London Festival Ballet Eva Maria Evdokimova-Gregori (December 1, 1948 – April 3, 2009)[1][2][3] was a Bulgarian-American Prima Ballerina Assoluta with the Royal...

The Vietnam Forces National Memorial Images on back wall Descriptive phrases on right wall The Australian Vietnam Forces National Memorial is on Anzac Parade, the principal ceremonial and memorial avenue in Canberra, the capital city of Australia. The memorial was dedicated on 3 October 1992. It commemorates the 50,000 Australian Army, Royal Australian Navy, and Royal Australian Air Force and associated personnel who served in Vietnam during the Vietnam War. Design Three concrete stelae, risi...

1919 film by J. Gordon Edwards Wings of the MorningAdvertising of Wings of the Morning on page 11 of the Duluth Herald (April 8, 1920).Directed byJ. Gordon EdwardsWritten byCharles Kenyon (scenario)Based onThe Wings of the Morningby Louis TracyProduced byWilliam FoxStarringWilliam FarnumHerschel MayallFrank ElliottG. Raymond NyeClarence BurtonHarry De VereCinematographyJohn W. BoyleMusic byW.C. PollaProductioncompanyFox Film CorporationDistributed byFox Film CorporationRelease date November&#...

Canton in Grand Est, FranceRemiremontCantonCountryFranceRegionGrand EstDepartmentVosgesNo. of communes9SeatRemiremontArea165.44 km2 (63.88 sq mi)Population (Jan. 2020)[1]25,118 • Density152/km2 (390/sq mi)INSEE code88 12 The Canton of Remiremont is a French administrative and electoral grouping of communes in the Vosges département of eastern France and in the region of Grand Est. Its administrative centre is at Remiremont. Composit...

У этого термина существуют и другие значения, см. Станица (значения). Субъекты России, в которых станицы являются населёнными пунктами. Количество станиц в России по субъектам РФ Стани́ца (от сущ. стан — остановка в пути для отдыха, временного пребывания, бивак, лагерь) �...

Torneo di Wimbledon 1988Singolare maschile Sport Tennis Vincitore Stefan Edberg Finalista Boris Becker Punteggio 4-6, 7-6(2), 6-4, 6-2 Tornei Singolare uomini donne   Doppio uomini donne misto 1987 1989 Voce principale: Torneo di Wimbledon 1988. Il detentore del titolo Pat Cash ha perso nei quarti di finale contro Boris Becker. Stefan Edberg ha battuto in finale Boris Becker per 4-6, 7-6(2), 6-4, 6-2 conquistando il suo primo Wimbledon e il terzo Slam in carriera. La finale è stata inte...

1461 battle in the Wars of the Roses Battle of TowtonPart of the Wars of the RosesThe Battle of Towton, Richard Caton Woodville Jr. (1922)Date29 March 1461LocationNear Towton, Yorkshire, United Kingdom53°50′10″N 01°16′25″W / 53.83611°N 1.27361°W / 53.83611; -1.27361Result Yorkist victoryBelligerents House of York House of LancasterCommanders and leaders Edward IV Earl of Warwick Baron Fauconberg Duke of Norfolk Duke of Somerset Duke of Exeter Earl of Northu...

Radio station in Blackville, South CarolinaWIIZBlackville, South CarolinaBroadcast areaBarnwell, South Carolina & Augusta, GeorgiaFrequency97.9 MHzBrandingThe Wiz 97.9ProgrammingFormatMainstream UrbanOwnershipOwnerNicwild Communications, Inc.HistoryFormer call signsWAAN (1993-1995)Technical informationFacility ID15307ClassC2ERP50,000 wattsHAAT132 metersTransmitter coordinates33°6′52.00″N 81°23′13.00″W / 33.1144444°N 81.3869444°W / 33.1144444; -81.386944...

يفتقر محتوى هذه المقالة إلى الاستشهاد بمصادر. فضلاً، ساهم في تطوير هذه المقالة من خلال إضافة مصادر موثوق بها. أي معلومات غير موثقة يمكن التشكيك بها وإزالتها. (ديسمبر 2018) 31° خط طول 31 شرق خريطة لجميع الإحداثيات من جوجل خريطة لجميع الإحداثيات من بينغ تصدير جميع الإحداثيات من كي...