-
Notifications
You must be signed in to change notification settings - Fork 205
/
+page.markdoc
384 lines (311 loc) · 11.4 KB
/
+page.markdoc
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
---
layout: article
title: GraphQL
description: Leverage the Appwrite GraphQL API for flexible data querying and manipulation. Explore GraphQL schema, queries, mutations, and how to integrate with your applications.
---
Appwrite supports multiple protocols for accessing the server, including [REST](/docs/apis/rest), [GraphQL](/docs/apis/graphql), and [Realtime](/docs/apis/realtime).
The GraphQL API allows you to query and mutate any resource type on your Appwrite server through the endpoint `/v1/graphql`.
Every endpoint available through REST is available through GraphQL, except for OAuth.
# Requests {% #requests %}
Although every query executes through the same endpoint, there are multiple ways to make a GraphQL request. All requests, however, share a common structure.
| Name | Type | Description |
|----------------|--------|---------------------------------------------------------------------------|
| query | string | **Required**, the GraphQL query to execute. |
| operationName | string | **Optional**, if the query contains several named operations, controls which one to execute. |
| variables | object | **Optional**, an object containing variable names and values for the query. Variables are made available to your query with the `$` prefix. |
## GraphQL model parameters {% #graphql-model-parameters %}
In Appwrite's GraphQL API, all internal model parameters are prefixed with `_` instead of `$` because `$` is reserved by GraphQL.
For example, `$collectionId` in the REST API would be referenced as `_collectionId` in the GraphQL API.
## GET requests {% #get-resquest %}
You can execute a GraphQL query via a GET request, passing a `query` and optionally `operationName` and `variables` as query parameters.
## POST requests {% #post-request %}
There are multiple ways to make a GraphQL POST request, differentiated by content type.
{% tabs %}
{% tabsitem #json title="JSON" %}
There are two ways to make requests with the `application/json` content type.
You can send a JSON object containing a `query` and optionally `operationName` and `variables`, or an array of objects with the same structure.
### Object
```json
{
"query": "",
"operationName": "",
"variables": {}
}
```
### Array
```json
[
{
"query": "",
"operationName": "",
"variables": {}
}
]
```
{% /tabsitem %}
{% tabsitem #graphql title="GraphQL" %}
The `application/graphql` content type can be used to send a query as the raw POST body.
```graphql
query GetAccount {
accountGet {
_id
email
}
}
```
{% /tabsitem %}
{% /tabs %}
## Multipart form data {% #multipart-form-data %}
The `multipart/form-data` content type can be used to upload files via GraphQL.
In this case, the form data must include the following parts in addition to the files to upload.
| Name | Type | Description |
|-------------|--------|---------------------------------------------------------------------------------------------------------------------------|
| operations |string | **Required**, JSON encoded GraphQL query and optionally operation name and variables. File variables should contain null values. |
| map | string | **Required**, JSON encoded map of form-data filenames to the operations dot-path to inject the file to, e.g. `variables.file`. |
# Responses {% #responses %}
A response to a GraphQL request will have the following structure:
| Name | Type | Description |
|--------|----------|--------------------------------------------------------------------------------|
| data | object | The data returned by the query, maps requested field names to their results. |
| errors | object[] | An array of errors that occurred during the request. |
The data object will contain a map of requested field names to their results.
If no data is returned, the object will not be present in the response.
The errors array will contain error objects, each with their own **message** and **path**.
The path will contain the field key that is null due to the error.
If no errors occur, the array will not be present in the response.
# Authentication {% #authentication %}
GraphQL authenticates using Appwrite accounts and sessions.
Both accounts and sessions can be created with GraphQL using the `accountCreate`, `accountCreateEmailSession`,
`accountCreateAnonymousSession`, or `accountCreatePhoneSession` mutations.
More information and examples of authenticating users can be found in the dedicated [authentication guide](/docs/products/auth).
# GraphQL vs REST {% #graphql-vs-rest %}
There are two main features that make GraphQL appealing when compared to the REST API: **selection sets** and **query batching**.
## Selection sets {% #selection-sets %}
Selection sets can be used to tell a GraphQL API exactly which fields of a particular resource you would like to receive in the response.
The server will respond with only those fields, nothing more, nothing less. This gives you full control over what data comes into your application.
For example, to retrieve only the email of a currently authenticated user, you could query the `accountGet` field,
passing only email as the **field selection set**.
```graphql
query GetAccount {
accountGet {
_id
email
}
}
```
Given this query, the GraphQL API will respond with:
```json
{
"data": {
"accountGet": {
"_id": "...",
"email": "..."
}
}
}
```
This can be a useful feature for performance, network efficiency, and app responsiveness.
As the processing happens on the server, the bandwidth consumed for the request can be dramatically reduced.
# Query batching {% #query-batching %}
GraphQL allows sending multiple queries or mutations in the same request.
There are two different ways to batch queries. The simplest way is to include multiple fields in a single query **or** mutation.
```graphql
query GetAccountAndLocale {
accountGet {
_id
email
}
localeGet {
ip
}
}
```
If both field executions succeed, the response will contain a data key for each field, containing the values of the selected fields.
```json
{
"data": {
"accountGet": {
"_id": "...",
"email": "..."
},
"localeGet": {
"ip": "..."
}
}
}
```
If there was no authenticated user, the `accountGet` field would fail to resolve.
In such a case the value of the data key for that field will be null, and an object will be added to the errors array instead.
```json
{
"data": {
"accountGet": null,
"localeGet": {
"ip": "...",
"country": "..."
}
},
"errors": [
{
"message": "User (role: guest) missing scope (account)",
"path": ["accountGet"]
}
]
}
```
Batching with a single query or mutation has some down-sides.
You cannot mix and match queries and mutations within the same request unless you provide an operationName,
in which case you can only execute one query per request.
Additionally, all **variables** must be passed in the same object, which can be cumbersome and hard to maintain.
The second way to batch is to pass an array of queries or mutations in the request.
In this way, you can execute queries **and** mutations and keep variables separated for each.
```json
[
{
"query": "query GetAccount { accountGet{ email } }",
},
{
"query": "query GetLocale { localeGet { ip } }"
}
]
```
This allows you to execute complex actions in a single network request.
# SDK usage {% #sdk-usage %}
Appwrite SDKs also support GraphQL in addition to the REST services.
{% multicode %}
```js
import { Client, Graphql } from "appwrite";
const client = new Client()
.setEndpoint('https://cloud.appwrite.io/v1') // Your Appwrite Endpoint
.setProject('[PROJECT_ID]'); // Your project ID
const graphql = new Graphql(client);
const mutation = graphql.mutation({
query: `mutation CreateAccount(
$email: String!,
$password: String!,
$name: String
) {
accountCreate(
email: $email,
password: $password,
name: $name,
userId: "unique()"
) {
_id
}
}`,
variables: {
email: '...',
password: '...',
name: '...'
}
});
mutation.then(response => {
console.log(response);
}).catch(error => {
console.log(error);
});
```
```dart
import 'package:appwrite/appwrite.dart';
final client = Client()
.setEndpoint('https://cloud.appwrite.io/v1') // Your Appwrite Endpoint
.setProject('[PROJECT_ID]'); // Your project ID
final graphql = Graphql(client);
Future mutation = graphql.mutation({
'query': '''mutation CreateAccount(
\$email: String!,
\$password: String!,
\$name: String
) {
accountCreate(
email: \$email,
password: \$password,
name: \$name,
userId: "unique()"
) {
_id
}
}''',
'variables': {
'email': '...',
'password': '...',
'name': '...'
}
});
mutation.then((response) {
print(response);
}).catchError((error) {
print(error.message);
});
```
```kotlin
import io.appwrite.Client
import io.appwrite.services.Graphql
val client = Client(context)
.setEndpoint("https://cloud.appwrite.io/v1") // Your API Endpoint
.setProject("[PROJECT_ID]") // Your project ID
val graphql = Graphql(client)
try {
val response = graphql.mutation(mapOf(
"query" to """mutation CreateAccount(
${'$'}email: String!,
${'$'}password: String!,
${'$'}name: String
) {
accountCreate(
email: ${'$'}email,
password: ${'$'}password,
name: ${'$'}name,
userId: "unique()"
) {
_id
}
}""",
"variables" to mapOf(
"email" to "...",
"password" to "...",
"name" to "..."
)
))
Log.d(javaClass.name, response)
} catch (ex: AppwriteException) {
ex.printStackTrace()
}
```
```swift
import Appwrite
let client = Client()
.setEndpoint("https://cloud.appwrite.io/v1") // Your API Endpoint
.setProject("[PROJECT_ID]") // Your project ID
let graphql = Graphql(client)
do {
let response = try await graphql.mutation([
"query": """
mutation CreateAccount(
$email: String!,
$password: String!,
$name: String
) {
accountCreate(
email: $email,
password: $password,
name: $name,
userId: "unique()"
) {
_id
}
}
""",
"variables": [
"email": "...",
"password": "...",
"name": "..."
]
])
print(String(describing: response))
} catch {
print(error.localizedDescription)
}
```
{% /multicode %}