Sitecore GraphQL APIの使用を開始する

Version: 22.x
日本語翻訳に関する免責事項

このページの翻訳はAIによって自動的に行われました。可能な限り正確な翻訳を心掛けていますが、原文と異なる表現や解釈が含まれる場合があります。正確で公式な情報については、必ず英語の原文をご参照ください。

このトピックでは、Sitecore GraphQL APIの設定方法と使用方法について説明します。GraphQLは、JSSサーバー コンポーネント パッケージをインストールすることで入手できます。

大事な

サイトでフォールバック言語をサポートしている場合は、開始する前にExperience Edge Connectorで 公開言語のフォールバックを有効にし てください。

Sitecore GraphQLを設定する

Sitecore GraphQLを設定するには:

  1. web.configファイルで、<compilation debug="true">.これにより、GraphQL GUIがデフォルトのセキュリティ設定で有効になります。セキュリティ上の理由から、GUIはデフォルトでは実稼働シナリオでは無効になっています。

  2. GraphQLサブスクリプションまたはWebSocketトランスポートを使用する場合は、IISでWebSocket機能を有効にしてから、IISをリセットする必要があります。

    メモ

    WebSocketは、Windows Server 2008 R2以前ではサポートされていません。これらのオペレーティング システムでホストされているサブスクリプションを使用することはできません。

  3. CORSまたは偽装を使用する場合は、master:/sitecore/system/Settings/Services/API KeysフォルダーにSSC APIキーを設定します。APIキーは、GraphQLとSitecore Services Clientと同じように機能します。

GraphQLエンドポイントの設定

Sitecoreヘッドレス サービス16.0以降では、Edgeプレビュー エンドポイント はデフォルトで有効になっていますが、追加のエンドポイントを設定できます。

GraphQLエンドポイントを設定するには:

  • GraphQL APIを使用するエンドポイントを少なくとも1つ定義します。

    次の例では、Masterデータベースに必要な認証を持つコンテンツAPIエンドポイントを定義しています。

    RequestResponse
    <?xml version="1.0" encoding="utf-8" ?>
    
    <!--
        Defines the system endpoint for the master database.
    -->
    <configuration xmlns:patch="http://www.sitecore.net/xmlconfig/" xmlns:role="http://www.sitecore.net/xmlconfig/role/">
        <sitecore>
            <api>
                <GraphQL>
                    <endpoints>
                        <master url="/sitecore/api/graph/items/master" type="Sitecore.Services.GraphQL.Hosting.GraphQLEndpoint, Sitecore.Services.GraphQL.NetFxHost" resolve="true">
                            <url>$(url)</url>
    
                            <enabled role:require="ContentDelivery">false</enabled>
    
                            <enableSubscriptions>true</enableSubscriptions>
    
                            <!-- lock down the endpoint when deployed to content delivery -->
                            <graphiql role:require="ContentDelivery">false</graphiql>
                            <enableSchemaExport role:require="ContentDelivery">false</enableSchemaExport>
                            <enableStats role:require="ContentDelivery">false</enableStats>
                            <enableCacheStats role:require="ContentDelivery">false</enableCacheStats>
                            <disableIntrospection role:require="ContentDelivery">true</disableIntrospection>
    
                            <schema hint="list:AddSchemaProvider">
                                <!-- defaults are defined in Sitecore.Services.GraphQL.Content.config -->
                                <content ref="/sitecore/api/GraphQL/defaults/content/schemaProviders/systemContent" param1="master" />
                            </schema>
    
                            <!-- Determines the security of the service. Defaults are defined in Sitecore.Services.GraphQL.config -->
                            <security ref="/sitecore/api/GraphQL/defaults/security/systemService" />
    
                            <!-- Determines how performance is logged for the service. Defaults are defined in Sitecore.Services.GraphQL.config -->
                            <performance ref="/sitecore/api/GraphQL/defaults/performance/standard" />
    
                            <!--
                                Cache improves the query performance by caching parsed queries.
                                It is also possible to implement query whitelisting by implementing an authoritative query cache;
                                WhitelistingGraphQLQueryCache is an example of this, capturing queries to files in open mode and allowing only captured queries in whitelist mode.
                            -->
                            <cache type="Sitecore.Services.GraphQL.Hosting.QueryTransformation.Caching.GraphQLQueryCache, Sitecore.Services.GraphQL.NetFxHost">
                                <param desc="name">$(url)</param>
                                <param desc="maxSize">10MB</param>
                            </cache>
                            
                            <!-- 
                                Extenders allow modifying schema types after they are created by a schema provider but before they are added to the final schema.
                                This is useful when you want to _extend_ a generated schema, for example, to add external API
                                data onto the item API, or to add in custom internal data (e.g. custom layout data to power an app)
                                without having to modify a schema provider directly.
                            
                                Extenders must derive from SchemaExtender.
                            -->
                            <extenders hint="list:AddExtender">
                                <!--<example type="Name.Space.ExtenderType, Assembly" resolve="true" />-->
                            </extenders>
                        </master>
                    </endpoints>
                </GraphQL>
            </api>
        </sitecore>
    </configuration>
    
    手記

    Sitecore GraphQLデフォルトの設定ファイルは、使用可能な設定オプションを理解するのに適したリソースです。エンドポイント設定でrefで参照されるデフォルトのプリセットは、特に興味深いものです。ファイルは /App_Config/Sitecore/Services.GraphQLフォルダにあります。

GraphQLエンドポイントを使用する

GraphQLエンドポイントを定義したら、定義したURLからアクセスできます。たとえば、次のようなURLでAPIをクエリできます: http://my.sitecore.domain/sitecore/api/graph/items/master

ただし、GraphiQL GUIでクエリを作成する方がはるかに簡単です。GUIにアクセスするには、エンドポイントURLにURL http://my.sitecore.domain/sitecore/api/graph/items/master/ui/uiを追加します。GUIでスキーマを利用したオートコンプリートを使用してGraphQLクエリを作成したり、クエリをテストしたり、スキーマのドキュメントを確認したりできます。

前の設定例で、GraphiQL GUIを使用してクエリを作成するには、次のようにします。

  1. Sitecoreにログインします (エンドポイントの例には認証が必要です)。

  2. /sitecore/api/graph/items/master/uiに移動します。このUIでは、Masterデータベース内のアイテムとテンプレートをクエリできます。

  3. Docs 」リンクをクリックして、タイプスキーマを参照します。

  4. GraphiQLコード補完機能を使用してGraphQLクエリを記述します ( CTRL-Spaceを押すと手動でトリガーされます)。たとえば、次のクエリは、項目、その子、およびそのテンプレート定義を1つのクエリで取得します。

    RequestResponse
    {
      item(path: "/sitecore/templates") {
        id
        path
        children {
          name
        }
        template {
           fields {
            name
          }
        }
      }
    }
    

    結果 (省略) は次のようになります。

    RequestResponse
    {
      "data": {
        "item": {
          "id": "{3C1715FE-6A13-4FCF-845F-DE308BA9741D}",
          "path": "/sitecore/templates",
          "children": [
            {
              "name": "Branches"
            },
            {
              "name": "Sample"
            },
            ...
          ],
          "template": {
            "fields": [
              {
                "name": "__Help link"
              },
              ...
            ]
          }
        }
      }
    }
    
手記

エンドポイントに認証が必要な場合、GUIも認証を必要とします。エンドポイントにSSC APIキー(?sc_apikey=api-key-guid)が必要な場合、GUIにはAPIキーも必要です。

APIのクエリ

Sitecore GraphQL APIのクエリは、他のGraphQLエンドポイントと比較して特別なことはありません。Apolloなどのクライアントライブラリを使用することをお勧めします。

Sitecore GraphQLエンドポイントは、次のタイプのGraphQLリクエストをサポートします。

  • 標準のJSONペイロード形式のapplication/jsonコンテンツ タイプとクエリを含むHTTP POST。

  • HTTP POST application/jsonコンテンツ タイプと標準ペイロードの配列 (バッチ処理に使用) JSON。

  • 本文にapplication/graphqlコンテンツタイプと未加工のGraphQLクエリを含むHTTP POST。

  • クエリ文字列パラメーター (queryoperationName、変数) を含むHTTP GET。

  • graphql-wsプロトコル(サブスクリプションまたはクエリ)を使用したWebSocket。

すべてのタイプのGraphQL操作は、APIフレームワークでサポートされています (スキーマは、これらの種類の操作をすべて実装する場合と実装しない場合があります)。

  • クエリ (データの読み取り)。

  • 突然変異(データの変更)。

  • サブスクリプション (データのリアルタイム更新をサブスクライブする)。

サブスクリプションは、WebSocketを使用するApollo subscriptions-transport-wsプロトコルを使用して実装されます。ソケット接続は、GraphQLエンドポイントURLに自動的に許可されます。

追加機能

GraphiQL /uiに加えて、各GraphQLエンドポイントはいくつかの追加部分もサポートしています。

  • $url/schema - GraphQLスキーマをスキーマ定義言語 (SDL) 形式でダンプします。SDL形式は、eslint-plugin-graphqlmなどのツールやgraphql-toolsなどのスキーマモックツールを使用した静的コード分析に役立ちます。

  • $url/stats - エンドポイントスキーマとそのパフォーマンスに関する基本的な統計を表示します。

  • $url/cache - エンドポイントのGraphQLクエリ キャッシュに関する詳細を表示します。

手記

これらの追加エンドポイント機能は、web.configファイルの設定パッチを使用してそれぞれ無効にできます。

RequestResponse
<enableSchemaExport role:require="ContentDelivery">false</enableSchemaExport>
<enableStats role:require="ContentDelivery">false</enableStats>
<enableCacheStats role:require="ContentDelivery">false</enableCacheStats>

何かフィードバックはありますか?

この記事を改善するための提案がある場合は、