|
7 | 7 | graphql-dsl
|
8 | 8 | ===========
|
9 | 9 |
|
10 |
| -Compose GraphQL queries by defining Python types |
11 |
| ------------------------------------------------- |
| 10 | +.. contents:: |
| 11 | + :local: |
| 12 | + |
| 13 | +Quick intro |
| 14 | +=========== |
12 | 15 |
|
13 | 16 | Let's take a manually written `GraphQL query <https://graphql.org/learn/schema/#the-query-and-mutation-types>`_:
|
14 | 17 |
|
@@ -85,9 +88,66 @@ field reference syntax (because dataclasses don't define class-level field gette
|
85 | 88 | | PASS | (Input, 'droid_id') * TO * (HeroAndDroid, 'droid') * AS * 'id'
|
86 | 89 | )
|
87 | 90 |
|
88 |
| -Indices and tables |
89 |
| -================== |
| 91 | +Simple queries |
| 92 | +-------------- |
| 93 | + |
| 94 | +Let's use `Countries API <https://countries.trevorblades.com/>`_ and prepare the simplest query for it. |
| 95 | + |
| 96 | +We want to fetch a list of all country codes |
| 97 | + |
| 98 | +.. code-block:: python |
| 99 | +
|
| 100 | + from typing import Sequence, NamedTuple |
| 101 | +
|
| 102 | + class Country(NamedTuple): |
| 103 | + code: str |
| 104 | +
|
| 105 | + class Query(NamedTuple): |
| 106 | + countries: Sequence[Country] |
| 107 | +
|
| 108 | +We can start composing our query with: |
| 109 | + |
| 110 | +.. code-block:: python |
| 111 | +
|
| 112 | + from graphql_dsl import QUERY |
| 113 | +
|
| 114 | + countries_query = QUERY | Query |
| 115 | +
|
| 116 | +
|
| 117 | +If we don't need to provide input parameters to the query, we can immediately compile it: |
| 118 | + |
| 119 | +.. code-block:: python |
| 120 | +
|
| 121 | + from graphql_dsl import GQL |
| 122 | +
|
| 123 | + compiled_query = GQL(countries_query) |
| 124 | +
|
| 125 | +
|
| 126 | +Now we are able to call the service and receive the typed result from it: |
| 127 | + |
| 128 | +.. code-block:: python |
| 129 | +
|
| 130 | + import requests |
| 131 | +
|
| 132 | + response = requests.post( |
| 133 | + url="https://countries.trevorblades.com/", |
| 134 | + json={ |
| 135 | + "operationName": compiled_query.name, |
| 136 | + "query": compiled_query.query, |
| 137 | + } |
| 138 | + ) |
| 139 | +
|
| 140 | + data = compiled_query.get_result(response) |
| 141 | + assert isinstance(data, Query) |
| 142 | +
|
| 143 | + # will print AD, AE, AF, AG, AI, AL, AM, AO, ... |
| 144 | + print(', '.join(country.code for country in data.countries)) |
| 145 | +
|
| 146 | +
|
| 147 | +
|
| 148 | +Documentation Indices and tables |
| 149 | +================================ |
90 | 150 |
|
91 | 151 | * :ref:`genindex`
|
92 | 152 | * :ref:`modindex`
|
93 |
| -* :ref:`search` |
| 153 | +* :ref:`search` |
0 commit comments