0
# Command Line Interface
1
2
Full-featured CLI for executing GraphQL queries, downloading schemas, and interacting with GraphQL servers. Supports multiple transport protocols, authentication methods, and comprehensive output formatting.
3
4
## Capabilities
5
6
### Main CLI Functions
7
8
Core functions for building and running the command-line interface.
9
10
```python { .api }
11
def gql_cli() -> None:
12
"""
13
Main CLI entry point registered as console script.
14
15
Available as the 'gql-cli' command after package installation.
16
Provides complete GraphQL client functionality from command line.
17
18
Features:
19
- Execute GraphQL queries, mutations, and subscriptions
20
- Download and print GraphQL schemas via introspection
21
- Multiple transport protocol support
22
- Authentication for AWS AppSync
23
- Configurable logging and debugging
24
- JSON variable input support
25
26
Usage:
27
gql-cli https://api.example.com/graphql
28
gql-cli wss://api.example.com/graphql -s
29
"""
30
31
def get_parser(with_examples: bool = False) -> ArgumentParser:
32
"""
33
Create argument parser for CLI.
34
35
Args:
36
with_examples: Include usage examples in help text
37
38
Returns:
39
Configured ArgumentParser instance with all CLI options
40
41
Used by:
42
gql_cli() function and testing infrastructure
43
"""
44
45
def get_transport(args: Namespace) -> Optional[AsyncTransport]:
46
"""
47
Create transport instance from CLI arguments.
48
49
Args:
50
args: Parsed command line arguments
51
52
Returns:
53
AsyncTransport instance based on URL scheme and transport options
54
55
Features:
56
- Auto-detection of transport type from URL
57
- Support for HTTP, WebSocket, and specialized transports
58
- Authentication configuration for AppSync
59
- Custom transport selection override
60
61
Supported Transports:
62
- aiohttp: HTTP transport using aiohttp
63
- httpx: HTTP transport using httpx
64
- websockets: WebSocket transport for subscriptions
65
- phoenix: Phoenix Channel WebSocket transport
66
- appsync: AWS AppSync WebSocket transport
67
"""
68
69
def autodetect_transport(url: URL) -> str:
70
"""
71
Determine appropriate transport based on URL scheme.
72
73
Args:
74
url: URL object with scheme information
75
76
Returns:
77
Transport name string
78
79
Logic:
80
- ws/wss schemes → "websockets"
81
- http/https schemes → "aiohttp" (default HTTP transport)
82
83
Example:
84
autodetect_transport(URL("wss://api.example.com/graphql")) # Returns "websockets"
85
autodetect_transport(URL("https://api.example.com/graphql")) # Returns "aiohttp"
86
"""
87
88
def get_transport_args(args: Namespace) -> Dict[str, Any]:
89
"""
90
Extract transport configuration from CLI arguments.
91
92
Args:
93
args: Parsed command line arguments
94
95
Returns:
96
Dictionary of transport configuration options
97
98
Extracts:
99
- HTTP headers from --headers arguments
100
- Transport-specific configuration options
101
"""
102
103
def get_execute_args(args: Namespace) -> Dict[str, Any]:
104
"""
105
Extract execution arguments from CLI arguments.
106
107
Args:
108
args: Parsed command line arguments
109
110
Returns:
111
Dictionary of execution options
112
113
Extracts:
114
- operation_name: Specific operation name for multi-operation documents
115
- variable_values: Parsed JSON variables from --variables arguments
116
"""
117
118
def get_introspection_args(args: Namespace) -> Dict[str, Any]:
119
"""
120
Parse schema download options from CLI arguments.
121
122
Args:
123
args: Parsed command line arguments
124
125
Returns:
126
Dictionary of introspection query configuration
127
128
Options:
129
- descriptions: Include field/type descriptions
130
- specified_by_url: Include specifiedByURL for scalars
131
- directive_is_repeatable: Include directive repeatability info
132
- schema_description: Include schema description
133
- input_value_deprecation: Include deprecated input fields
134
- type_recursion_level: Recursion depth for type references
135
"""
136
137
def positive_int_or_none(value_str: str) -> Optional[int]:
138
"""
139
Parse CLI integer arguments that can be None.
140
141
Args:
142
value_str: String value from command line
143
144
Returns:
145
Positive integer or None
146
147
Accepts:
148
- Positive integers: "10", "100"
149
- None string: "none", "None"
150
151
Raises:
152
argparse.ArgumentTypeError: If value is invalid
153
154
Used by:
155
Timeout and limit argument parsing
156
"""
157
```
158
159
## Command Line Options
160
161
### Required Arguments
162
163
```bash
164
server # GraphQL endpoint URL
165
# Examples: https://api.example.com/graphql
166
# wss://api.example.com/graphql
167
```
168
169
### Query and Variable Options
170
171
```bash
172
--variables, -V # Query variables as key:json_value pairs
173
# Format: key:json_value
174
# Examples: -V id:123 -V name:'"John"' -V active:true
175
176
--operation-name, -o # Operation name for multi-operation documents
177
# Used when GraphQL document contains multiple operations
178
179
--execute-timeout # Client execution timeout in seconds
180
# Default: 10 seconds
181
```
182
183
### Schema and Introspection Options
184
185
```bash
186
--print-schema # Download and print schema via introspection
187
# Outputs complete GraphQL schema definition
188
189
--schema-download # Configure introspection query options
190
# Comma-separated list of options:
191
# - descriptions (default: true)
192
# - specified_by_url (default: false)
193
# - directive_is_repeatable (default: false)
194
# - schema_description (default: false)
195
# - input_value_deprecation (default: true)
196
# - type_recursion_level:N (default: 7)
197
```
198
199
### Transport Options
200
201
```bash
202
--transport # Choose specific transport
203
# Options: auto (default), aiohttp, httpx, websockets, phoenix, appsync
204
# Auto-detection based on URL scheme if not specified
205
206
--headers, -H # HTTP headers as key:value pairs
207
# Format: key:value
208
# Examples: -H "Authorization:Bearer token123"
209
# -H "Content-Type:application/json"
210
```
211
212
### Authentication Options (AppSync)
213
214
```bash
215
--api-key # AppSync API key authentication
216
# Used with AppSync GraphQL endpoints
217
218
--jwt # AppSync JWT authentication
219
# JWT token for Cognito User Pools or OIDC
220
```
221
222
### Logging and Debug Options
223
224
```bash
225
--debug, -d # Enable debug logging
226
# Shows detailed transport and execution information
227
228
--verbose, -v # Enable info logging
229
# Shows general operation information
230
231
```
232
233
## Usage Examples
234
235
### Basic Query Execution
236
237
```bash
238
# Execute simple query
239
gql-cli https://api.example.com/graphql <<< 'query { hello }'
240
241
# Execute query with variables
242
gql-cli https://api.example.com/graphql \
243
-V id:123 -V name:'"John Doe"' \
244
<<< 'query GetUser($id: ID!, $name: String) { user(id: $id, name: $name) { id name email } }'
245
246
# Execute specific operation from multi-operation document
247
gql-cli https://api.example.com/graphql \
248
--operation-name GetUser \
249
<<< 'query GetUser { user { name } } query GetPosts { posts { title } }'
250
```
251
252
### Schema Introspection
253
254
```bash
255
# Download and print complete schema
256
gql-cli https://api.example.com/graphql --print-schema
257
258
# Download schema with custom introspection options
259
gql-cli https://api.example.com/graphql --print-schema \
260
--schema-download descriptions,specified_by_url,directive_is_repeatable
261
262
# Save schema to file
263
gql-cli https://api.example.com/graphql --print-schema > schema.graphql
264
```
265
266
### HTTP Transport with Authentication
267
268
```bash
269
# Basic authentication with headers
270
gql-cli https://api.example.com/graphql \
271
-H "Authorization:Bearer your-jwt-token" \
272
-H "User-Agent:MyApp/1.0" \
273
<<< 'query { currentUser { name } }'
274
275
# Force specific HTTP transport
276
gql-cli https://api.example.com/graphql \
277
--transport httpx \
278
-H "API-Key:your-api-key" \
279
<<< 'query { data }'
280
281
# With timeout configuration
282
gql-cli https://api.example.com/graphql \
283
--execute-timeout 30 \
284
<<< 'query { slowOperation }'
285
```
286
287
### WebSocket Subscriptions
288
289
```bash
290
# Basic WebSocket subscription
291
gql-cli wss://api.example.com/graphql \
292
<<< 'subscription { messageAdded { id content user } }'
293
294
# WebSocket with headers for authentication
295
gql-cli wss://api.example.com/graphql \
296
-H "Authorization:Bearer your-token" \
297
<<< 'subscription { notifications { type message } }'
298
299
# Force WebSocket transport (useful for dual HTTP/WS endpoints)
300
gql-cli https://api.example.com/graphql \
301
--transport websockets \
302
<<< 'subscription { events { id data } }'
303
```
304
305
### Phoenix Channel Integration
306
307
```bash
308
# Phoenix Framework Absinthe GraphQL server
309
gql-cli wss://phoenix-app.example.com/socket/websocket \
310
--transport phoenix \
311
<<< 'subscription { chatMessage { content user } }'
312
313
# Phoenix with custom channel (if supported by server)
314
gql-cli wss://phoenix-app.example.com/socket/websocket \
315
--transport phoenix \
316
-V channel:'"custom_channel"' \
317
<<< 'subscription { updates }'
318
```
319
320
### AWS AppSync Integration
321
322
```bash
323
# AppSync with API key authentication
324
gql-cli https://your-api.appsync-api.us-east-1.amazonaws.com/graphql \
325
--transport appsync \
326
--api-key your-api-key \
327
<<< 'subscription { onCommentAdded { id content } }'
328
329
# AppSync with JWT authentication (Cognito User Pools)
330
gql-cli https://your-api.appsync-api.us-east-1.amazonaws.com/graphql \
331
--transport appsync \
332
--jwt your-cognito-jwt-token \
333
<<< 'subscription { onPostUpdated { id title } }'
334
335
# AppSync with IAM authentication (uses AWS credentials from environment)
336
gql-cli https://your-api.appsync-api.us-east-1.amazonaws.com/graphql \
337
--transport appsync \
338
<<< 'subscription { onDataChange { id value } }'
339
```
340
341
### Complex Variable Examples
342
343
```bash
344
# Variables with different JSON types
345
gql-cli https://api.example.com/graphql \
346
-V userId:123 \
347
-V isActive:true \
348
-V tags:'["python", "graphql"]' \
349
-V metadata:'{"source": "cli", "version": 1}' \
350
<<< 'query GetUser($userId: ID!, $isActive: Boolean!, $tags: [String!]!, $metadata: JSON) {
351
user(id: $userId, active: $isActive) {
352
name
353
tags(filter: $tags)
354
metadata(input: $metadata)
355
}
356
}'
357
358
# Complex nested input objects
359
gql-cli https://api.example.com/graphql \
360
-V input:'{"name": "John Doe", "email": "john@example.com", "profile": {"age": 30, "city": "NYC"}}' \
361
<<< 'mutation CreateUser($input: UserInput!) {
362
createUser(input: $input) {
363
id
364
name
365
366
}
367
}'
368
```
369
370
### Debugging and Development
371
372
```bash
373
# Enable debug logging to see transport details
374
gql-cli https://api.example.com/graphql --debug \
375
<<< 'query { debug }'
376
377
# Enable verbose logging for general information
378
gql-cli https://api.example.com/graphql --verbose \
379
<<< 'query { status }'
380
381
# Combine with schema download for development
382
gql-cli https://api.example.com/graphql --debug --print-schema \
383
--schema-download descriptions,specified_by_url > debug_schema.graphql
384
```
385
386
### File Input and Output
387
388
```bash
389
# Read query from file
390
gql-cli https://api.example.com/graphql < query.graphql
391
392
# Save results to file
393
gql-cli https://api.example.com/graphql \
394
<<< 'query { users { id name } }' > results.json
395
396
# Pipeline with other tools
397
cat complex_query.graphql | \
398
gql-cli https://api.example.com/graphql \
399
-V limit:10 | \
400
jq '.data.users[].name'
401
```
402
403
### Multi-line Queries
404
405
```bash
406
# Using heredoc for complex queries
407
gql-cli https://api.example.com/graphql <<EOF
408
query GetUserWithPosts {
409
user(id: "123") {
410
id
411
name
412
413
posts(limit: 5) {
414
id
415
title
416
content
417
publishedAt
418
comments(limit: 3) {
419
id
420
content
421
author {
422
name
423
}
424
}
425
}
426
}
427
}
428
EOF
429
```
430
431
### Configuration Patterns
432
433
```bash
434
# Common pattern: alias for authenticated API
435
alias api-cli='gql-cli https://api.example.com/graphql -H "Authorization:Bearer $API_TOKEN"'
436
437
# Use the alias
438
api-cli <<< 'query { currentUser { name } }'
439
440
# Environment variable for dynamic configuration
441
export GQL_ENDPOINT="https://api.example.com/graphql"
442
export GQL_TOKEN="your-token-here"
443
444
gql-cli "$GQL_ENDPOINT" \
445
-H "Authorization:Bearer $GQL_TOKEN" \
446
<<< 'query { profile }'
447
```
448
449
## Return Codes and Error Handling
450
451
### Exit Codes
452
453
- **0**: Success - Query executed successfully
454
- **1**: General error - Invalid arguments, connection failure, or GraphQL errors
455
- **2**: Authentication error - Invalid credentials or authorization failure
456
457
### Error Output
458
459
The CLI outputs errors to stderr and results to stdout, enabling proper shell scripting:
460
461
```bash
462
# Capture only results
463
gql-cli https://api.example.com/graphql <<< 'query { data }' > results.json
464
465
# Capture only errors
466
gql-cli https://api.example.com/graphql <<< 'query { invalid }' 2> errors.log
467
468
# Handle errors in scripts
469
if ! gql-cli https://api.example.com/graphql <<< 'query { health }' >/dev/null 2>&1; then
470
echo "API is down"
471
exit 1
472
fi
473
```
474
475
## Integration Examples
476
477
### Shell Scripts
478
479
```bash
480
#!/bin/bash
481
# Check API health and get user count
482
483
API_URL="https://api.example.com/graphql"
484
AUTH_HEADER="Authorization:Bearer $API_TOKEN"
485
486
# Check if API is healthy
487
if ! gql-cli "$API_URL" -H "$AUTH_HEADER" <<< 'query { health }' >/dev/null 2>&1; then
488
echo "API health check failed"
489
exit 1
490
fi
491
492
# Get user count
493
USER_COUNT=$(gql-cli "$API_URL" -H "$AUTH_HEADER" \
494
<<< 'query { userCount }' | jq -r '.data.userCount')
495
496
echo "Current user count: $USER_COUNT"
497
```
498
499
### CI/CD Integration
500
501
```yaml
502
# GitHub Actions example
503
- name: Test GraphQL API
504
run: |
505
gql-cli https://api.example.com/graphql \
506
-H "Authorization:Bearer ${{ secrets.API_TOKEN }}" \
507
<<< 'query { health { status version } }' | \
508
jq -e '.data.health.status == "ok"'
509
```
510
511
### Monitoring Scripts
512
513
```bash
514
#!/bin/bash
515
# Monitor GraphQL subscription and log messages
516
517
LOG_FILE="/var/log/graphql-messages.log"
518
API_URL="wss://api.example.com/graphql"
519
520
# Continuous monitoring with restart on failure
521
while true; do
522
echo "$(date): Starting GraphQL subscription monitor" >> "$LOG_FILE"
523
524
gql-cli "$API_URL" \
525
-H "Authorization:Bearer $MONITOR_TOKEN" \
526
<<< 'subscription { alerts { level message timestamp } }' | \
527
while IFS= read -r line; do
528
echo "$(date): $line" >> "$LOG_FILE"
529
done
530
531
echo "$(date): Subscription ended, restarting in 5s" >> "$LOG_FILE"
532
sleep 5
533
done
534
```